Home | History | Annotate | Download | only in orig
      1 /******************************************************************************
      2 ** This file is an amalgamation of many separate C source files from SQLite
      3 ** version 3.8.6.  By combining all the individual C code files into this
      4 ** single large file, the entire code can be compiled as a single translation
      5 ** unit.  This allows many compilers to do optimizations that would not be
      6 ** possible if the files were compiled separately.  Performance improvements
      7 ** of 5% or more are commonly seen when SQLite is compiled as a single
      8 ** translation unit.
      9 **
     10 ** This file is all you need to compile SQLite.  To use SQLite in other
     11 ** programs, you need this file and the "sqlite3.h" header file that defines
     12 ** the programming interface to the SQLite library.  (If you do not have
     13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
     14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
     15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
     16 ** if you want a wrapper to interface SQLite with your choice of programming
     17 ** language. The code for the "sqlite3" command-line shell is also in a
     18 ** separate file. This file contains only code for the core SQLite library.
     19 */
     20 #define SQLITE_CORE 1
     21 #define SQLITE_AMALGAMATION 1
     22 #ifndef SQLITE_PRIVATE
     23 # define SQLITE_PRIVATE static
     24 #endif
     25 #ifndef SQLITE_API
     26 # define SQLITE_API
     27 #endif
     28 /************** Begin file sqliteInt.h ***************************************/
     29 /*
     30 ** 2001 September 15
     31 **
     32 ** The author disclaims copyright to this source code.  In place of
     33 ** a legal notice, here is a blessing:
     34 **
     35 **    May you do good and not evil.
     36 **    May you find forgiveness for yourself and forgive others.
     37 **    May you share freely, never taking more than you give.
     38 **
     39 *************************************************************************
     40 ** Internal interface definitions for SQLite.
     41 **
     42 */
     43 #ifndef _SQLITEINT_H_
     44 #define _SQLITEINT_H_
     45 
     46 /*
     47 ** These #defines should enable >2GB file support on POSIX if the
     48 ** underlying operating system supports it.  If the OS lacks
     49 ** large file support, or if the OS is windows, these should be no-ops.
     50 **
     51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
     52 ** system #includes.  Hence, this block of code must be the very first
     53 ** code in all source files.
     54 **
     55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
     56 ** on the compiler command line.  This is necessary if you are compiling
     57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
     58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
     59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
     60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
     61 ** portability you should omit LFS.
     62 **
     63 ** The previous paragraph was written in 2005.  (This paragraph is written
     64 ** on 2008-11-28.) These days, all Linux kernels support large files, so
     65 ** you should probably leave LFS enabled.  But some embedded platforms might
     66 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
     67 **
     68 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
     69 */
     70 #ifndef SQLITE_DISABLE_LFS
     71 # define _LARGE_FILE       1
     72 # ifndef _FILE_OFFSET_BITS
     73 #   define _FILE_OFFSET_BITS 64
     74 # endif
     75 # define _LARGEFILE_SOURCE 1
     76 #endif
     77 
     78 /*
     79 ** For MinGW, check to see if we can include the header file containing its
     80 ** version information, among other things.  Normally, this internal MinGW
     81 ** header file would [only] be included automatically by other MinGW header
     82 ** files; however, the contained version information is now required by this
     83 ** header file to work around binary compatibility issues (see below) and
     84 ** this is the only known way to reliably obtain it.  This entire #if block
     85 ** would be completely unnecessary if there was any other way of detecting
     86 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
     87 ** some MinGW-specific macros).  When compiling for MinGW, either the
     88 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
     89 ** defined; otherwise, detection of conditions specific to MinGW will be
     90 ** disabled.
     91 */
     92 #if defined(_HAVE_MINGW_H)
     93 # include "mingw.h"
     94 #elif defined(_HAVE__MINGW_H)
     95 # include "_mingw.h"
     96 #endif
     97 
     98 /*
     99 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
    100 ** define is required to maintain binary compatibility with the MSVC runtime
    101 ** library in use (e.g. for Windows XP).
    102 */
    103 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
    104     defined(_WIN32) && !defined(_WIN64) && \
    105     defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
    106     defined(__MSVCRT__)
    107 # define _USE_32BIT_TIME_T
    108 #endif
    109 
    110 /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
    111 ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
    112 ** MinGW.
    113 */
    114 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
    115 /************** Begin file sqlite3.h *****************************************/
    116 /*
    117 ** 2001 September 15
    118 **
    119 ** The author disclaims copyright to this source code.  In place of
    120 ** a legal notice, here is a blessing:
    121 **
    122 **    May you do good and not evil.
    123 **    May you find forgiveness for yourself and forgive others.
    124 **    May you share freely, never taking more than you give.
    125 **
    126 *************************************************************************
    127 ** This header file defines the interface that the SQLite library
    128 ** presents to client programs.  If a C-function, structure, datatype,
    129 ** or constant definition does not appear in this file, then it is
    130 ** not a published API of SQLite, is subject to change without
    131 ** notice, and should not be referenced by programs that use SQLite.
    132 **
    133 ** Some of the definitions that are in this file are marked as
    134 ** "experimental".  Experimental interfaces are normally new
    135 ** features recently added to SQLite.  We do not anticipate changes
    136 ** to experimental interfaces but reserve the right to make minor changes
    137 ** if experience from use "in the wild" suggest such changes are prudent.
    138 **
    139 ** The official C-language API documentation for SQLite is derived
    140 ** from comments in this file.  This file is the authoritative source
    141 ** on how SQLite interfaces are suppose to operate.
    142 **
    143 ** The name of this file under configuration management is "sqlite.h.in".
    144 ** The makefile makes some minor changes to this file (such as inserting
    145 ** the version number) and changes its name to "sqlite3.h" as
    146 ** part of the build process.
    147 */
    148 #ifndef _SQLITE3_H_
    149 #define _SQLITE3_H_
    150 #include <stdarg.h>     /* Needed for the definition of va_list */
    151 
    152 /*
    153 ** Make sure we can call this stuff from C++.
    154 */
    155 #if 0
    156 extern "C" {
    157 #endif
    158 
    159 
    160 /*
    161 ** Add the ability to override 'extern'
    162 */
    163 #ifndef SQLITE_EXTERN
    164 # define SQLITE_EXTERN extern
    165 #endif
    166 
    167 #ifndef SQLITE_API
    168 # define SQLITE_API
    169 #endif
    170 
    171 
    172 /*
    173 ** These no-op macros are used in front of interfaces to mark those
    174 ** interfaces as either deprecated or experimental.  New applications
    175 ** should not use deprecated interfaces - they are support for backwards
    176 ** compatibility only.  Application writers should be aware that
    177 ** experimental interfaces are subject to change in point releases.
    178 **
    179 ** These macros used to resolve to various kinds of compiler magic that
    180 ** would generate warning messages when they were used.  But that
    181 ** compiler magic ended up generating such a flurry of bug reports
    182 ** that we have taken it all out and gone back to using simple
    183 ** noop macros.
    184 */
    185 #define SQLITE_DEPRECATED
    186 #define SQLITE_EXPERIMENTAL
    187 
    188 /*
    189 ** Ensure these symbols were not defined by some previous header file.
    190 */
    191 #ifdef SQLITE_VERSION
    192 # undef SQLITE_VERSION
    193 #endif
    194 #ifdef SQLITE_VERSION_NUMBER
    195 # undef SQLITE_VERSION_NUMBER
    196 #endif
    197 
    198 /*
    199 ** CAPI3REF: Compile-Time Library Version Numbers
    200 **
    201 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
    202 ** evaluates to a string literal that is the SQLite version in the
    203 ** format "X.Y.Z" where X is the major version number (always 3 for
    204 ** SQLite3) and Y is the minor version number and Z is the release number.)^
    205 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
    206 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
    207 ** numbers used in [SQLITE_VERSION].)^
    208 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
    209 ** be larger than the release from which it is derived.  Either Y will
    210 ** be held constant and Z will be incremented or else Y will be incremented
    211 ** and Z will be reset to zero.
    212 **
    213 ** Since version 3.6.18, SQLite source code has been stored in the
    214 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
    215 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
    216 ** a string which identifies a particular check-in of SQLite
    217 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
    218 ** string contains the date and time of the check-in (UTC) and an SHA1
    219 ** hash of the entire source tree.
    220 **
    221 ** See also: [sqlite3_libversion()],
    222 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
    223 ** [sqlite_version()] and [sqlite_source_id()].
    224 */
    225 #define SQLITE_VERSION        "3.8.6"
    226 #define SQLITE_VERSION_NUMBER 3008006
    227 #define SQLITE_SOURCE_ID      "2014-08-15 11:46:33 9491ba7d738528f168657adb43a198238abde19e"
    228 
    229 /*
    230 ** CAPI3REF: Run-Time Library Version Numbers
    231 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
    232 **
    233 ** These interfaces provide the same information as the [SQLITE_VERSION],
    234 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
    235 ** but are associated with the library instead of the header file.  ^(Cautious
    236 ** programmers might include assert() statements in their application to
    237 ** verify that values returned by these interfaces match the macros in
    238 ** the header, and thus insure that the application is
    239 ** compiled with matching library and header files.
    240 **
    241 ** <blockquote><pre>
    242 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
    243 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
    244 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
    245 ** </pre></blockquote>)^
    246 **
    247 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
    248 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
    249 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
    250 ** function is provided for use in DLLs since DLL users usually do not have
    251 ** direct access to string constants within the DLL.  ^The
    252 ** sqlite3_libversion_number() function returns an integer equal to
    253 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
    254 ** a pointer to a string constant whose value is the same as the
    255 ** [SQLITE_SOURCE_ID] C preprocessor macro.
    256 **
    257 ** See also: [sqlite_version()] and [sqlite_source_id()].
    258 */
    259 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
    260 SQLITE_API const char *sqlite3_libversion(void);
    261 SQLITE_API const char *sqlite3_sourceid(void);
    262 SQLITE_API int sqlite3_libversion_number(void);
    263 
    264 /*
    265 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
    266 **
    267 ** ^The sqlite3_compileoption_used() function returns 0 or 1
    268 ** indicating whether the specified option was defined at
    269 ** compile time.  ^The SQLITE_ prefix may be omitted from the
    270 ** option name passed to sqlite3_compileoption_used().
    271 **
    272 ** ^The sqlite3_compileoption_get() function allows iterating
    273 ** over the list of options that were defined at compile time by
    274 ** returning the N-th compile time option string.  ^If N is out of range,
    275 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
    276 ** prefix is omitted from any strings returned by
    277 ** sqlite3_compileoption_get().
    278 **
    279 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
    280 ** and sqlite3_compileoption_get() may be omitted by specifying the
    281 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
    282 **
    283 ** See also: SQL functions [sqlite_compileoption_used()] and
    284 ** [sqlite_compileoption_get()] and the [compile_options pragma].
    285 */
    286 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
    287 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
    288 SQLITE_API const char *sqlite3_compileoption_get(int N);
    289 #endif
    290 
    291 /*
    292 ** CAPI3REF: Test To See If The Library Is Threadsafe
    293 **
    294 ** ^The sqlite3_threadsafe() function returns zero if and only if
    295 ** SQLite was compiled with mutexing code omitted due to the
    296 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
    297 **
    298 ** SQLite can be compiled with or without mutexes.  When
    299 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
    300 ** are enabled and SQLite is threadsafe.  When the
    301 ** [SQLITE_THREADSAFE] macro is 0,
    302 ** the mutexes are omitted.  Without the mutexes, it is not safe
    303 ** to use SQLite concurrently from more than one thread.
    304 **
    305 ** Enabling mutexes incurs a measurable performance penalty.
    306 ** So if speed is of utmost importance, it makes sense to disable
    307 ** the mutexes.  But for maximum safety, mutexes should be enabled.
    308 ** ^The default behavior is for mutexes to be enabled.
    309 **
    310 ** This interface can be used by an application to make sure that the
    311 ** version of SQLite that it is linking against was compiled with
    312 ** the desired setting of the [SQLITE_THREADSAFE] macro.
    313 **
    314 ** This interface only reports on the compile-time mutex setting
    315 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
    316 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
    317 ** can be fully or partially disabled using a call to [sqlite3_config()]
    318 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
    319 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
    320 ** sqlite3_threadsafe() function shows only the compile-time setting of
    321 ** thread safety, not any run-time changes to that setting made by
    322 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
    323 ** is unchanged by calls to sqlite3_config().)^
    324 **
    325 ** See the [threading mode] documentation for additional information.
    326 */
    327 SQLITE_API int sqlite3_threadsafe(void);
    328 
    329 /*
    330 ** CAPI3REF: Database Connection Handle
    331 ** KEYWORDS: {database connection} {database connections}
    332 **
    333 ** Each open SQLite database is represented by a pointer to an instance of
    334 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
    335 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
    336 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
    337 ** and [sqlite3_close_v2()] are its destructors.  There are many other
    338 ** interfaces (such as
    339 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
    340 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
    341 ** sqlite3 object.
    342 */
    343 typedef struct sqlite3 sqlite3;
    344 
    345 /*
    346 ** CAPI3REF: 64-Bit Integer Types
    347 ** KEYWORDS: sqlite_int64 sqlite_uint64
    348 **
    349 ** Because there is no cross-platform way to specify 64-bit integer types
    350 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
    351 **
    352 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
    353 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
    354 ** compatibility only.
    355 **
    356 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
    357 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
    358 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
    359 ** between 0 and +18446744073709551615 inclusive.
    360 */
    361 #ifdef SQLITE_INT64_TYPE
    362   typedef SQLITE_INT64_TYPE sqlite_int64;
    363   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
    364 #elif defined(_MSC_VER) || defined(__BORLANDC__)
    365   typedef __int64 sqlite_int64;
    366   typedef unsigned __int64 sqlite_uint64;
    367 #else
    368   typedef long long int sqlite_int64;
    369   typedef unsigned long long int sqlite_uint64;
    370 #endif
    371 typedef sqlite_int64 sqlite3_int64;
    372 typedef sqlite_uint64 sqlite3_uint64;
    373 
    374 /*
    375 ** If compiling for a processor that lacks floating point support,
    376 ** substitute integer for floating-point.
    377 */
    378 #ifdef SQLITE_OMIT_FLOATING_POINT
    379 # define double sqlite3_int64
    380 #endif
    381 
    382 /*
    383 ** CAPI3REF: Closing A Database Connection
    384 **
    385 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
    386 ** for the [sqlite3] object.
    387 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
    388 ** the [sqlite3] object is successfully destroyed and all associated
    389 ** resources are deallocated.
    390 **
    391 ** ^If the database connection is associated with unfinalized prepared
    392 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
    393 ** will leave the database connection open and return [SQLITE_BUSY].
    394 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
    395 ** and/or unfinished sqlite3_backups, then the database connection becomes
    396 ** an unusable "zombie" which will automatically be deallocated when the
    397 ** last prepared statement is finalized or the last sqlite3_backup is
    398 ** finished.  The sqlite3_close_v2() interface is intended for use with
    399 ** host languages that are garbage collected, and where the order in which
    400 ** destructors are called is arbitrary.
    401 **
    402 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
    403 ** [sqlite3_blob_close | close] all [BLOB handles], and
    404 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
    405 ** with the [sqlite3] object prior to attempting to close the object.  ^If
    406 ** sqlite3_close_v2() is called on a [database connection] that still has
    407 ** outstanding [prepared statements], [BLOB handles], and/or
    408 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
    409 ** of resources is deferred until all [prepared statements], [BLOB handles],
    410 ** and [sqlite3_backup] objects are also destroyed.
    411 **
    412 ** ^If an [sqlite3] object is destroyed while a transaction is open,
    413 ** the transaction is automatically rolled back.
    414 **
    415 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
    416 ** must be either a NULL
    417 ** pointer or an [sqlite3] object pointer obtained
    418 ** from [sqlite3_open()], [sqlite3_open16()], or
    419 ** [sqlite3_open_v2()], and not previously closed.
    420 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
    421 ** argument is a harmless no-op.
    422 */
    423 SQLITE_API int sqlite3_close(sqlite3*);
    424 SQLITE_API int sqlite3_close_v2(sqlite3*);
    425 
    426 /*
    427 ** The type for a callback function.
    428 ** This is legacy and deprecated.  It is included for historical
    429 ** compatibility and is not documented.
    430 */
    431 typedef int (*sqlite3_callback)(void*,int,char**, char**);
    432 
    433 /*
    434 ** CAPI3REF: One-Step Query Execution Interface
    435 **
    436 ** The sqlite3_exec() interface is a convenience wrapper around
    437 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
    438 ** that allows an application to run multiple statements of SQL
    439 ** without having to use a lot of C code.
    440 **
    441 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
    442 ** semicolon-separate SQL statements passed into its 2nd argument,
    443 ** in the context of the [database connection] passed in as its 1st
    444 ** argument.  ^If the callback function of the 3rd argument to
    445 ** sqlite3_exec() is not NULL, then it is invoked for each result row
    446 ** coming out of the evaluated SQL statements.  ^The 4th argument to
    447 ** sqlite3_exec() is relayed through to the 1st argument of each
    448 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
    449 ** is NULL, then no callback is ever invoked and result rows are
    450 ** ignored.
    451 **
    452 ** ^If an error occurs while evaluating the SQL statements passed into
    453 ** sqlite3_exec(), then execution of the current statement stops and
    454 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
    455 ** is not NULL then any error message is written into memory obtained
    456 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
    457 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
    458 ** on error message strings returned through the 5th parameter of
    459 ** of sqlite3_exec() after the error message string is no longer needed.
    460 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
    461 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
    462 ** NULL before returning.
    463 **
    464 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
    465 ** routine returns SQLITE_ABORT without invoking the callback again and
    466 ** without running any subsequent SQL statements.
    467 **
    468 ** ^The 2nd argument to the sqlite3_exec() callback function is the
    469 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
    470 ** callback is an array of pointers to strings obtained as if from
    471 ** [sqlite3_column_text()], one for each column.  ^If an element of a
    472 ** result row is NULL then the corresponding string pointer for the
    473 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
    474 ** sqlite3_exec() callback is an array of pointers to strings where each
    475 ** entry represents the name of corresponding result column as obtained
    476 ** from [sqlite3_column_name()].
    477 **
    478 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
    479 ** to an empty string, or a pointer that contains only whitespace and/or
    480 ** SQL comments, then no SQL statements are evaluated and the database
    481 ** is not changed.
    482 **
    483 ** Restrictions:
    484 **
    485 ** <ul>
    486 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
    487 **      is a valid and open [database connection].
    488 ** <li> The application must not close the [database connection] specified by
    489 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
    490 ** <li> The application must not modify the SQL statement text passed into
    491 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
    492 ** </ul>
    493 */
    494 SQLITE_API int sqlite3_exec(
    495   sqlite3*,                                  /* An open database */
    496   const char *sql,                           /* SQL to be evaluated */
    497   int (*callback)(void*,int,char**,char**),  /* Callback function */
    498   void *,                                    /* 1st argument to callback */
    499   char **errmsg                              /* Error msg written here */
    500 );
    501 
    502 /*
    503 ** CAPI3REF: Result Codes
    504 ** KEYWORDS: {result code definitions}
    505 **
    506 ** Many SQLite functions return an integer result code from the set shown
    507 ** here in order to indicate success or failure.
    508 **
    509 ** New error codes may be added in future versions of SQLite.
    510 **
    511 ** See also: [extended result code definitions]
    512 */
    513 #define SQLITE_OK           0   /* Successful result */
    514 /* beginning-of-error-codes */
    515 #define SQLITE_ERROR        1   /* SQL error or missing database */
    516 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
    517 #define SQLITE_PERM         3   /* Access permission denied */
    518 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
    519 #define SQLITE_BUSY         5   /* The database file is locked */
    520 #define SQLITE_LOCKED       6   /* A table in the database is locked */
    521 #define SQLITE_NOMEM        7   /* A malloc() failed */
    522 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
    523 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
    524 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
    525 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
    526 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
    527 #define SQLITE_FULL        13   /* Insertion failed because database is full */
    528 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
    529 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
    530 #define SQLITE_EMPTY       16   /* Database is empty */
    531 #define SQLITE_SCHEMA      17   /* The database schema changed */
    532 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
    533 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
    534 #define SQLITE_MISMATCH    20   /* Data type mismatch */
    535 #define SQLITE_MISUSE      21   /* Library used incorrectly */
    536 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
    537 #define SQLITE_AUTH        23   /* Authorization denied */
    538 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
    539 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
    540 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
    541 #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
    542 #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
    543 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
    544 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
    545 /* end-of-error-codes */
    546 
    547 /*
    548 ** CAPI3REF: Extended Result Codes
    549 ** KEYWORDS: {extended result code definitions}
    550 **
    551 ** In its default configuration, SQLite API routines return one of 30 integer
    552 ** [result codes].  However, experience has shown that many of
    553 ** these result codes are too coarse-grained.  They do not provide as
    554 ** much information about problems as programmers might like.  In an effort to
    555 ** address this, newer versions of SQLite (version 3.3.8 and later) include
    556 ** support for additional result codes that provide more detailed information
    557 ** about errors. These [extended result codes] are enabled or disabled
    558 ** on a per database connection basis using the
    559 ** [sqlite3_extended_result_codes()] API.  Or, the extended code for
    560 ** the most recent error can be obtained using
    561 ** [sqlite3_extended_errcode()].
    562 */
    563 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
    564 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
    565 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
    566 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
    567 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
    568 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
    569 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
    570 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
    571 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
    572 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
    573 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
    574 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
    575 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
    576 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
    577 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
    578 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
    579 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
    580 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
    581 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
    582 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
    583 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
    584 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
    585 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
    586 #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
    587 #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
    588 #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
    589 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
    590 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
    591 #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
    592 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
    593 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
    594 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
    595 #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
    596 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
    597 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
    598 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
    599 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
    600 #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
    601 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
    602 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
    603 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
    604 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
    605 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
    606 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
    607 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
    608 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
    609 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
    610 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
    611 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
    612 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
    613 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
    614 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
    615 
    616 /*
    617 ** CAPI3REF: Flags For File Open Operations
    618 **
    619 ** These bit values are intended for use in the
    620 ** 3rd parameter to the [sqlite3_open_v2()] interface and
    621 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
    622 */
    623 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
    624 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
    625 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
    626 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
    627 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
    628 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
    629 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
    630 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
    631 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
    632 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
    633 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
    634 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
    635 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
    636 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
    637 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
    638 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
    639 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
    640 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
    641 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
    642 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
    643 
    644 /* Reserved:                         0x00F00000 */
    645 
    646 /*
    647 ** CAPI3REF: Device Characteristics
    648 **
    649 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
    650 ** object returns an integer which is a vector of these
    651 ** bit values expressing I/O characteristics of the mass storage
    652 ** device that holds the file that the [sqlite3_io_methods]
    653 ** refers to.
    654 **
    655 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
    656 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
    657 ** mean that writes of blocks that are nnn bytes in size and
    658 ** are aligned to an address which is an integer multiple of
    659 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
    660 ** that when data is appended to a file, the data is appended
    661 ** first then the size of the file is extended, never the other
    662 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
    663 ** information is written to disk in the same order as calls
    664 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
    665 ** after reboot following a crash or power loss, the only bytes in a
    666 ** file that were written at the application level might have changed
    667 ** and that adjacent bytes, even bytes within the same sector are
    668 ** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
    669 ** flag indicate that a file cannot be deleted when open.  The
    670 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
    671 ** read-only media and cannot be changed even by processes with
    672 ** elevated privileges.
    673 */
    674 #define SQLITE_IOCAP_ATOMIC                 0x00000001
    675 #define SQLITE_IOCAP_ATOMIC512              0x00000002
    676 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
    677 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
    678 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
    679 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
    680 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
    681 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
    682 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
    683 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
    684 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
    685 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
    686 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
    687 #define SQLITE_IOCAP_IMMUTABLE              0x00002000
    688 
    689 /*
    690 ** CAPI3REF: File Locking Levels
    691 **
    692 ** SQLite uses one of these integer values as the second
    693 ** argument to calls it makes to the xLock() and xUnlock() methods
    694 ** of an [sqlite3_io_methods] object.
    695 */
    696 #define SQLITE_LOCK_NONE          0
    697 #define SQLITE_LOCK_SHARED        1
    698 #define SQLITE_LOCK_RESERVED      2
    699 #define SQLITE_LOCK_PENDING       3
    700 #define SQLITE_LOCK_EXCLUSIVE     4
    701 
    702 /*
    703 ** CAPI3REF: Synchronization Type Flags
    704 **
    705 ** When SQLite invokes the xSync() method of an
    706 ** [sqlite3_io_methods] object it uses a combination of
    707 ** these integer values as the second argument.
    708 **
    709 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
    710 ** sync operation only needs to flush data to mass storage.  Inode
    711 ** information need not be flushed. If the lower four bits of the flag
    712 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
    713 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
    714 ** to use Mac OS X style fullsync instead of fsync().
    715 **
    716 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
    717 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
    718 ** settings.  The [synchronous pragma] determines when calls to the
    719 ** xSync VFS method occur and applies uniformly across all platforms.
    720 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
    721 ** energetic or rigorous or forceful the sync operations are and
    722 ** only make a difference on Mac OSX for the default SQLite code.
    723 ** (Third-party VFS implementations might also make the distinction
    724 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
    725 ** operating systems natively supported by SQLite, only Mac OSX
    726 ** cares about the difference.)
    727 */
    728 #define SQLITE_SYNC_NORMAL        0x00002
    729 #define SQLITE_SYNC_FULL          0x00003
    730 #define SQLITE_SYNC_DATAONLY      0x00010
    731 
    732 /*
    733 ** CAPI3REF: OS Interface Open File Handle
    734 **
    735 ** An [sqlite3_file] object represents an open file in the
    736 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
    737 ** implementations will
    738 ** want to subclass this object by appending additional fields
    739 ** for their own use.  The pMethods entry is a pointer to an
    740 ** [sqlite3_io_methods] object that defines methods for performing
    741 ** I/O operations on the open file.
    742 */
    743 typedef struct sqlite3_file sqlite3_file;
    744 struct sqlite3_file {
    745   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
    746 };
    747 
    748 /*
    749 ** CAPI3REF: OS Interface File Virtual Methods Object
    750 **
    751 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
    752 ** [sqlite3_file] object (or, more commonly, a subclass of the
    753 ** [sqlite3_file] object) with a pointer to an instance of this object.
    754 ** This object defines the methods used to perform various operations
    755 ** against the open file represented by the [sqlite3_file] object.
    756 **
    757 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
    758 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
    759 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
    760 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
    761 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
    762 ** to NULL.
    763 **
    764 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
    765 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
    766 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
    767 ** flag may be ORed in to indicate that only the data of the file
    768 ** and not its inode needs to be synced.
    769 **
    770 ** The integer values to xLock() and xUnlock() are one of
    771 ** <ul>
    772 ** <li> [SQLITE_LOCK_NONE],
    773 ** <li> [SQLITE_LOCK_SHARED],
    774 ** <li> [SQLITE_LOCK_RESERVED],
    775 ** <li> [SQLITE_LOCK_PENDING], or
    776 ** <li> [SQLITE_LOCK_EXCLUSIVE].
    777 ** </ul>
    778 ** xLock() increases the lock. xUnlock() decreases the lock.
    779 ** The xCheckReservedLock() method checks whether any database connection,
    780 ** either in this process or in some other process, is holding a RESERVED,
    781 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
    782 ** if such a lock exists and false otherwise.
    783 **
    784 ** The xFileControl() method is a generic interface that allows custom
    785 ** VFS implementations to directly control an open file using the
    786 ** [sqlite3_file_control()] interface.  The second "op" argument is an
    787 ** integer opcode.  The third argument is a generic pointer intended to
    788 ** point to a structure that may contain arguments or space in which to
    789 ** write return values.  Potential uses for xFileControl() might be
    790 ** functions to enable blocking locks with timeouts, to change the
    791 ** locking strategy (for example to use dot-file locks), to inquire
    792 ** about the status of a lock, or to break stale locks.  The SQLite
    793 ** core reserves all opcodes less than 100 for its own use.
    794 ** A [file control opcodes | list of opcodes] less than 100 is available.
    795 ** Applications that define a custom xFileControl method should use opcodes
    796 ** greater than 100 to avoid conflicts.  VFS implementations should
    797 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
    798 ** recognize.
    799 **
    800 ** The xSectorSize() method returns the sector size of the
    801 ** device that underlies the file.  The sector size is the
    802 ** minimum write that can be performed without disturbing
    803 ** other bytes in the file.  The xDeviceCharacteristics()
    804 ** method returns a bit vector describing behaviors of the
    805 ** underlying device:
    806 **
    807 ** <ul>
    808 ** <li> [SQLITE_IOCAP_ATOMIC]
    809 ** <li> [SQLITE_IOCAP_ATOMIC512]
    810 ** <li> [SQLITE_IOCAP_ATOMIC1K]
    811 ** <li> [SQLITE_IOCAP_ATOMIC2K]
    812 ** <li> [SQLITE_IOCAP_ATOMIC4K]
    813 ** <li> [SQLITE_IOCAP_ATOMIC8K]
    814 ** <li> [SQLITE_IOCAP_ATOMIC16K]
    815 ** <li> [SQLITE_IOCAP_ATOMIC32K]
    816 ** <li> [SQLITE_IOCAP_ATOMIC64K]
    817 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
    818 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
    819 ** </ul>
    820 **
    821 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
    822 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
    823 ** mean that writes of blocks that are nnn bytes in size and
    824 ** are aligned to an address which is an integer multiple of
    825 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
    826 ** that when data is appended to a file, the data is appended
    827 ** first then the size of the file is extended, never the other
    828 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
    829 ** information is written to disk in the same order as calls
    830 ** to xWrite().
    831 **
    832 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
    833 ** in the unread portions of the buffer with zeros.  A VFS that
    834 ** fails to zero-fill short reads might seem to work.  However,
    835 ** failure to zero-fill short reads will eventually lead to
    836 ** database corruption.
    837 */
    838 typedef struct sqlite3_io_methods sqlite3_io_methods;
    839 struct sqlite3_io_methods {
    840   int iVersion;
    841   int (*xClose)(sqlite3_file*);
    842   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
    843   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
    844   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
    845   int (*xSync)(sqlite3_file*, int flags);
    846   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
    847   int (*xLock)(sqlite3_file*, int);
    848   int (*xUnlock)(sqlite3_file*, int);
    849   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
    850   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
    851   int (*xSectorSize)(sqlite3_file*);
    852   int (*xDeviceCharacteristics)(sqlite3_file*);
    853   /* Methods above are valid for version 1 */
    854   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
    855   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
    856   void (*xShmBarrier)(sqlite3_file*);
    857   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
    858   /* Methods above are valid for version 2 */
    859   int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
    860   int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
    861   /* Methods above are valid for version 3 */
    862   /* Additional methods may be added in future releases */
    863 };
    864 
    865 /*
    866 ** CAPI3REF: Standard File Control Opcodes
    867 ** KEYWORDS: {file control opcodes} {file control opcode}
    868 **
    869 ** These integer constants are opcodes for the xFileControl method
    870 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
    871 ** interface.
    872 **
    873 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
    874 ** opcode causes the xFileControl method to write the current state of
    875 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
    876 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
    877 ** into an integer that the pArg argument points to. This capability
    878 ** is used during testing and only needs to be supported when SQLITE_TEST
    879 ** is defined.
    880 ** <ul>
    881 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
    882 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
    883 ** layer a hint of how large the database file will grow to be during the
    884 ** current transaction.  This hint is not guaranteed to be accurate but it
    885 ** is often close.  The underlying VFS might choose to preallocate database
    886 ** file space based on this hint in order to help writes to the database
    887 ** file run faster.
    888 **
    889 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
    890 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
    891 ** extends and truncates the database file in chunks of a size specified
    892 ** by the user. The fourth argument to [sqlite3_file_control()] should
    893 ** point to an integer (type int) containing the new chunk-size to use
    894 ** for the nominated database. Allocating database file space in large
    895 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
    896 ** improve performance on some systems.
    897 **
    898 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
    899 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
    900 ** to the [sqlite3_file] object associated with a particular database
    901 ** connection.  See the [sqlite3_file_control()] documentation for
    902 ** additional information.
    903 **
    904 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
    905 ** No longer in use.
    906 **
    907 ** <li>[[SQLITE_FCNTL_SYNC]]
    908 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
    909 ** sent to the VFS immediately before the xSync method is invoked on a
    910 ** database file descriptor. Or, if the xSync method is not invoked
    911 ** because the user has configured SQLite with
    912 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
    913 ** of the xSync method. In most cases, the pointer argument passed with
    914 ** this file-control is NULL. However, if the database file is being synced
    915 ** as part of a multi-database commit, the argument points to a nul-terminated
    916 ** string containing the transactions master-journal file name. VFSes that
    917 ** do not need this signal should silently ignore this opcode. Applications
    918 ** should not call [sqlite3_file_control()] with this opcode as doing so may
    919 ** disrupt the operation of the specialized VFSes that do require it.
    920 **
    921 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
    922 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
    923 ** and sent to the VFS after a transaction has been committed immediately
    924 ** but before the database is unlocked. VFSes that do not need this signal
    925 ** should silently ignore this opcode. Applications should not call
    926 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
    927 ** operation of the specialized VFSes that do require it.
    928 **
    929 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
    930 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
    931 ** retry counts and intervals for certain disk I/O operations for the
    932 ** windows [VFS] in order to provide robustness in the presence of
    933 ** anti-virus programs.  By default, the windows VFS will retry file read,
    934 ** file write, and file delete operations up to 10 times, with a delay
    935 ** of 25 milliseconds before the first retry and with the delay increasing
    936 ** by an additional 25 milliseconds with each subsequent retry.  This
    937 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
    938 ** to be adjusted.  The values are changed for all database connections
    939 ** within the same process.  The argument is a pointer to an array of two
    940 ** integers where the first integer i the new retry count and the second
    941 ** integer is the delay.  If either integer is negative, then the setting
    942 ** is not changed but instead the prior value of that setting is written
    943 ** into the array entry, allowing the current retry settings to be
    944 ** interrogated.  The zDbName parameter is ignored.
    945 **
    946 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
    947 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
    948 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
    949 ** write ahead log and shared memory files used for transaction control
    950 ** are automatically deleted when the latest connection to the database
    951 ** closes.  Setting persistent WAL mode causes those files to persist after
    952 ** close.  Persisting the files is useful when other processes that do not
    953 ** have write permission on the directory containing the database file want
    954 ** to read the database file, as the WAL and shared memory files must exist
    955 ** in order for the database to be readable.  The fourth parameter to
    956 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
    957 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
    958 ** WAL mode.  If the integer is -1, then it is overwritten with the current
    959 ** WAL persistence setting.
    960 **
    961 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
    962 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
    963 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
    964 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
    965 ** xDeviceCharacteristics methods. The fourth parameter to
    966 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
    967 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
    968 ** mode.  If the integer is -1, then it is overwritten with the current
    969 ** zero-damage mode setting.
    970 **
    971 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
    972 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
    973 ** a write transaction to indicate that, unless it is rolled back for some
    974 ** reason, the entire database file will be overwritten by the current
    975 ** transaction. This is used by VACUUM operations.
    976 **
    977 ** <li>[[SQLITE_FCNTL_VFSNAME]]
    978 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
    979 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
    980 ** final bottom-level VFS are written into memory obtained from
    981 ** [sqlite3_malloc()] and the result is stored in the char* variable
    982 ** that the fourth parameter of [sqlite3_file_control()] points to.
    983 ** The caller is responsible for freeing the memory when done.  As with
    984 ** all file-control actions, there is no guarantee that this will actually
    985 ** do anything.  Callers should initialize the char* variable to a NULL
    986 ** pointer in case this file-control is not implemented.  This file-control
    987 ** is intended for diagnostic use only.
    988 **
    989 ** <li>[[SQLITE_FCNTL_PRAGMA]]
    990 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
    991 ** file control is sent to the open [sqlite3_file] object corresponding
    992 ** to the database file to which the pragma statement refers. ^The argument
    993 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
    994 ** pointers to strings (char**) in which the second element of the array
    995 ** is the name of the pragma and the third element is the argument to the
    996 ** pragma or NULL if the pragma has no argument.  ^The handler for an
    997 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
    998 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
    999 ** or the equivalent and that string will become the result of the pragma or
   1000 ** the error message if the pragma fails. ^If the
   1001 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
   1002 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
   1003 ** file control returns [SQLITE_OK], then the parser assumes that the
   1004 ** VFS has handled the PRAGMA itself and the parser generates a no-op
   1005 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
   1006 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
   1007 ** that the VFS encountered an error while handling the [PRAGMA] and the
   1008 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
   1009 ** file control occurs at the beginning of pragma statement analysis and so
   1010 ** it is able to override built-in [PRAGMA] statements.
   1011 **
   1012 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
   1013 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
   1014 ** file-control may be invoked by SQLite on the database file handle
   1015 ** shortly after it is opened in order to provide a custom VFS with access
   1016 ** to the connections busy-handler callback. The argument is of type (void **)
   1017 ** - an array of two (void *) values. The first (void *) actually points
   1018 ** to a function of type (int (*)(void *)). In order to invoke the connections
   1019 ** busy-handler, this function should be invoked with the second (void *) in
   1020 ** the array as the only argument. If it returns non-zero, then the operation
   1021 ** should be retried. If it returns zero, the custom VFS should abandon the
   1022 ** current operation.
   1023 **
   1024 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
   1025 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
   1026 ** to have SQLite generate a
   1027 ** temporary filename using the same algorithm that is followed to generate
   1028 ** temporary filenames for TEMP tables and other internal uses.  The
   1029 ** argument should be a char** which will be filled with the filename
   1030 ** written into memory obtained from [sqlite3_malloc()].  The caller should
   1031 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
   1032 **
   1033 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
   1034 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
   1035 ** maximum number of bytes that will be used for memory-mapped I/O.
   1036 ** The argument is a pointer to a value of type sqlite3_int64 that
   1037 ** is an advisory maximum number of bytes in the file to memory map.  The
   1038 ** pointer is overwritten with the old value.  The limit is not changed if
   1039 ** the value originally pointed to is negative, and so the current limit
   1040 ** can be queried by passing in a pointer to a negative number.  This
   1041 ** file-control is used internally to implement [PRAGMA mmap_size].
   1042 **
   1043 ** <li>[[SQLITE_FCNTL_TRACE]]
   1044 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
   1045 ** to the VFS about what the higher layers of the SQLite stack are doing.
   1046 ** This file control is used by some VFS activity tracing [shims].
   1047 ** The argument is a zero-terminated string.  Higher layers in the
   1048 ** SQLite stack may generate instances of this file control if
   1049 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
   1050 **
   1051 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
   1052 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
   1053 ** pointer to an integer and it writes a boolean into that integer depending
   1054 ** on whether or not the file has been renamed, moved, or deleted since it
   1055 ** was first opened.
   1056 **
   1057 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
   1058 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
   1059 ** opcode causes the xFileControl method to swap the file handle with the one
   1060 ** pointed to by the pArg argument.  This capability is used during testing
   1061 ** and only needs to be supported when SQLITE_TEST is defined.
   1062 **
   1063 ** </ul>
   1064 */
   1065 #define SQLITE_FCNTL_LOCKSTATE               1
   1066 #define SQLITE_GET_LOCKPROXYFILE             2
   1067 #define SQLITE_SET_LOCKPROXYFILE             3
   1068 #define SQLITE_LAST_ERRNO                    4
   1069 #define SQLITE_FCNTL_SIZE_HINT               5
   1070 #define SQLITE_FCNTL_CHUNK_SIZE              6
   1071 #define SQLITE_FCNTL_FILE_POINTER            7
   1072 #define SQLITE_FCNTL_SYNC_OMITTED            8
   1073 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
   1074 #define SQLITE_FCNTL_PERSIST_WAL            10
   1075 #define SQLITE_FCNTL_OVERWRITE              11
   1076 #define SQLITE_FCNTL_VFSNAME                12
   1077 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
   1078 #define SQLITE_FCNTL_PRAGMA                 14
   1079 #define SQLITE_FCNTL_BUSYHANDLER            15
   1080 #define SQLITE_FCNTL_TEMPFILENAME           16
   1081 #define SQLITE_FCNTL_MMAP_SIZE              18
   1082 #define SQLITE_FCNTL_TRACE                  19
   1083 #define SQLITE_FCNTL_HAS_MOVED              20
   1084 #define SQLITE_FCNTL_SYNC                   21
   1085 #define SQLITE_FCNTL_COMMIT_PHASETWO        22
   1086 #define SQLITE_FCNTL_WIN32_SET_HANDLE       23
   1087 
   1088 /*
   1089 ** CAPI3REF: Mutex Handle
   1090 **
   1091 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
   1092 ** abstract type for a mutex object.  The SQLite core never looks
   1093 ** at the internal representation of an [sqlite3_mutex].  It only
   1094 ** deals with pointers to the [sqlite3_mutex] object.
   1095 **
   1096 ** Mutexes are created using [sqlite3_mutex_alloc()].
   1097 */
   1098 typedef struct sqlite3_mutex sqlite3_mutex;
   1099 
   1100 /*
   1101 ** CAPI3REF: OS Interface Object
   1102 **
   1103 ** An instance of the sqlite3_vfs object defines the interface between
   1104 ** the SQLite core and the underlying operating system.  The "vfs"
   1105 ** in the name of the object stands for "virtual file system".  See
   1106 ** the [VFS | VFS documentation] for further information.
   1107 **
   1108 ** The value of the iVersion field is initially 1 but may be larger in
   1109 ** future versions of SQLite.  Additional fields may be appended to this
   1110 ** object when the iVersion value is increased.  Note that the structure
   1111 ** of the sqlite3_vfs object changes in the transaction between
   1112 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
   1113 ** modified.
   1114 **
   1115 ** The szOsFile field is the size of the subclassed [sqlite3_file]
   1116 ** structure used by this VFS.  mxPathname is the maximum length of
   1117 ** a pathname in this VFS.
   1118 **
   1119 ** Registered sqlite3_vfs objects are kept on a linked list formed by
   1120 ** the pNext pointer.  The [sqlite3_vfs_register()]
   1121 ** and [sqlite3_vfs_unregister()] interfaces manage this list
   1122 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
   1123 ** searches the list.  Neither the application code nor the VFS
   1124 ** implementation should use the pNext pointer.
   1125 **
   1126 ** The pNext field is the only field in the sqlite3_vfs
   1127 ** structure that SQLite will ever modify.  SQLite will only access
   1128 ** or modify this field while holding a particular static mutex.
   1129 ** The application should never modify anything within the sqlite3_vfs
   1130 ** object once the object has been registered.
   1131 **
   1132 ** The zName field holds the name of the VFS module.  The name must
   1133 ** be unique across all VFS modules.
   1134 **
   1135 ** [[sqlite3_vfs.xOpen]]
   1136 ** ^SQLite guarantees that the zFilename parameter to xOpen
   1137 ** is either a NULL pointer or string obtained
   1138 ** from xFullPathname() with an optional suffix added.
   1139 ** ^If a suffix is added to the zFilename parameter, it will
   1140 ** consist of a single "-" character followed by no more than
   1141 ** 11 alphanumeric and/or "-" characters.
   1142 ** ^SQLite further guarantees that
   1143 ** the string will be valid and unchanged until xClose() is
   1144 ** called. Because of the previous sentence,
   1145 ** the [sqlite3_file] can safely store a pointer to the
   1146 ** filename if it needs to remember the filename for some reason.
   1147 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
   1148 ** must invent its own temporary name for the file.  ^Whenever the
   1149 ** xFilename parameter is NULL it will also be the case that the
   1150 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
   1151 **
   1152 ** The flags argument to xOpen() includes all bits set in
   1153 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
   1154 ** or [sqlite3_open16()] is used, then flags includes at least
   1155 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
   1156 ** If xOpen() opens a file read-only then it sets *pOutFlags to
   1157 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
   1158 **
   1159 ** ^(SQLite will also add one of the following flags to the xOpen()
   1160 ** call, depending on the object being opened:
   1161 **
   1162 ** <ul>
   1163 ** <li>  [SQLITE_OPEN_MAIN_DB]
   1164 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
   1165 ** <li>  [SQLITE_OPEN_TEMP_DB]
   1166 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
   1167 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
   1168 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
   1169 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
   1170 ** <li>  [SQLITE_OPEN_WAL]
   1171 ** </ul>)^
   1172 **
   1173 ** The file I/O implementation can use the object type flags to
   1174 ** change the way it deals with files.  For example, an application
   1175 ** that does not care about crash recovery or rollback might make
   1176 ** the open of a journal file a no-op.  Writes to this journal would
   1177 ** also be no-ops, and any attempt to read the journal would return
   1178 ** SQLITE_IOERR.  Or the implementation might recognize that a database
   1179 ** file will be doing page-aligned sector reads and writes in a random
   1180 ** order and set up its I/O subsystem accordingly.
   1181 **
   1182 ** SQLite might also add one of the following flags to the xOpen method:
   1183 **
   1184 ** <ul>
   1185 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
   1186 ** <li> [SQLITE_OPEN_EXCLUSIVE]
   1187 ** </ul>
   1188 **
   1189 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
   1190 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
   1191 ** will be set for TEMP databases and their journals, transient
   1192 ** databases, and subjournals.
   1193 **
   1194 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
   1195 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
   1196 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
   1197 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
   1198 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
   1199 ** be created, and that it is an error if it already exists.
   1200 ** It is <i>not</i> used to indicate the file should be opened
   1201 ** for exclusive access.
   1202 **
   1203 ** ^At least szOsFile bytes of memory are allocated by SQLite
   1204 ** to hold the  [sqlite3_file] structure passed as the third
   1205 ** argument to xOpen.  The xOpen method does not have to
   1206 ** allocate the structure; it should just fill it in.  Note that
   1207 ** the xOpen method must set the sqlite3_file.pMethods to either
   1208 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
   1209 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
   1210 ** element will be valid after xOpen returns regardless of the success
   1211 ** or failure of the xOpen call.
   1212 **
   1213 ** [[sqlite3_vfs.xAccess]]
   1214 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
   1215 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
   1216 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
   1217 ** to test whether a file is at least readable.   The file can be a
   1218 ** directory.
   1219 **
   1220 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
   1221 ** output buffer xFullPathname.  The exact size of the output buffer
   1222 ** is also passed as a parameter to both  methods. If the output buffer
   1223 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
   1224 ** handled as a fatal error by SQLite, vfs implementations should endeavor
   1225 ** to prevent this by setting mxPathname to a sufficiently large value.
   1226 **
   1227 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
   1228 ** interfaces are not strictly a part of the filesystem, but they are
   1229 ** included in the VFS structure for completeness.
   1230 ** The xRandomness() function attempts to return nBytes bytes
   1231 ** of good-quality randomness into zOut.  The return value is
   1232 ** the actual number of bytes of randomness obtained.
   1233 ** The xSleep() method causes the calling thread to sleep for at
   1234 ** least the number of microseconds given.  ^The xCurrentTime()
   1235 ** method returns a Julian Day Number for the current date and time as
   1236 ** a floating point value.
   1237 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
   1238 ** Day Number multiplied by 86400000 (the number of milliseconds in
   1239 ** a 24-hour day).
   1240 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
   1241 ** date and time if that method is available (if iVersion is 2 or
   1242 ** greater and the function pointer is not NULL) and will fall back
   1243 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
   1244 **
   1245 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
   1246 ** are not used by the SQLite core.  These optional interfaces are provided
   1247 ** by some VFSes to facilitate testing of the VFS code. By overriding
   1248 ** system calls with functions under its control, a test program can
   1249 ** simulate faults and error conditions that would otherwise be difficult
   1250 ** or impossible to induce.  The set of system calls that can be overridden
   1251 ** varies from one VFS to another, and from one version of the same VFS to the
   1252 ** next.  Applications that use these interfaces must be prepared for any
   1253 ** or all of these interfaces to be NULL or for their behavior to change
   1254 ** from one release to the next.  Applications must not attempt to access
   1255 ** any of these methods if the iVersion of the VFS is less than 3.
   1256 */
   1257 typedef struct sqlite3_vfs sqlite3_vfs;
   1258 typedef void (*sqlite3_syscall_ptr)(void);
   1259 struct sqlite3_vfs {
   1260   int iVersion;            /* Structure version number (currently 3) */
   1261   int szOsFile;            /* Size of subclassed sqlite3_file */
   1262   int mxPathname;          /* Maximum file pathname length */
   1263   sqlite3_vfs *pNext;      /* Next registered VFS */
   1264   const char *zName;       /* Name of this virtual file system */
   1265   void *pAppData;          /* Pointer to application-specific data */
   1266   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
   1267                int flags, int *pOutFlags);
   1268   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
   1269   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
   1270   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
   1271   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
   1272   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
   1273   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
   1274   void (*xDlClose)(sqlite3_vfs*, void*);
   1275   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
   1276   int (*xSleep)(sqlite3_vfs*, int microseconds);
   1277   int (*xCurrentTime)(sqlite3_vfs*, double*);
   1278   int (*xGetLastError)(sqlite3_vfs*, int, char *);
   1279   /*
   1280   ** The methods above are in version 1 of the sqlite_vfs object
   1281   ** definition.  Those that follow are added in version 2 or later
   1282   */
   1283   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
   1284   /*
   1285   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
   1286   ** Those below are for version 3 and greater.
   1287   */
   1288   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
   1289   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
   1290   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
   1291   /*
   1292   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
   1293   ** New fields may be appended in figure versions.  The iVersion
   1294   ** value will increment whenever this happens.
   1295   */
   1296 };
   1297 
   1298 /*
   1299 ** CAPI3REF: Flags for the xAccess VFS method
   1300 **
   1301 ** These integer constants can be used as the third parameter to
   1302 ** the xAccess method of an [sqlite3_vfs] object.  They determine
   1303 ** what kind of permissions the xAccess method is looking for.
   1304 ** With SQLITE_ACCESS_EXISTS, the xAccess method
   1305 ** simply checks whether the file exists.
   1306 ** With SQLITE_ACCESS_READWRITE, the xAccess method
   1307 ** checks whether the named directory is both readable and writable
   1308 ** (in other words, if files can be added, removed, and renamed within
   1309 ** the directory).
   1310 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
   1311 ** [temp_store_directory pragma], though this could change in a future
   1312 ** release of SQLite.
   1313 ** With SQLITE_ACCESS_READ, the xAccess method
   1314 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
   1315 ** currently unused, though it might be used in a future release of
   1316 ** SQLite.
   1317 */
   1318 #define SQLITE_ACCESS_EXISTS    0
   1319 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
   1320 #define SQLITE_ACCESS_READ      2   /* Unused */
   1321 
   1322 /*
   1323 ** CAPI3REF: Flags for the xShmLock VFS method
   1324 **
   1325 ** These integer constants define the various locking operations
   1326 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
   1327 ** following are the only legal combinations of flags to the
   1328 ** xShmLock method:
   1329 **
   1330 ** <ul>
   1331 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
   1332 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
   1333 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
   1334 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
   1335 ** </ul>
   1336 **
   1337 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
   1338 ** was given no the corresponding lock.
   1339 **
   1340 ** The xShmLock method can transition between unlocked and SHARED or
   1341 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
   1342 ** and EXCLUSIVE.
   1343 */
   1344 #define SQLITE_SHM_UNLOCK       1
   1345 #define SQLITE_SHM_LOCK         2
   1346 #define SQLITE_SHM_SHARED       4
   1347 #define SQLITE_SHM_EXCLUSIVE    8
   1348 
   1349 /*
   1350 ** CAPI3REF: Maximum xShmLock index
   1351 **
   1352 ** The xShmLock method on [sqlite3_io_methods] may use values
   1353 ** between 0 and this upper bound as its "offset" argument.
   1354 ** The SQLite core will never attempt to acquire or release a
   1355 ** lock outside of this range
   1356 */
   1357 #define SQLITE_SHM_NLOCK        8
   1358 
   1359 
   1360 /*
   1361 ** CAPI3REF: Initialize The SQLite Library
   1362 **
   1363 ** ^The sqlite3_initialize() routine initializes the
   1364 ** SQLite library.  ^The sqlite3_shutdown() routine
   1365 ** deallocates any resources that were allocated by sqlite3_initialize().
   1366 ** These routines are designed to aid in process initialization and
   1367 ** shutdown on embedded systems.  Workstation applications using
   1368 ** SQLite normally do not need to invoke either of these routines.
   1369 **
   1370 ** A call to sqlite3_initialize() is an "effective" call if it is
   1371 ** the first time sqlite3_initialize() is invoked during the lifetime of
   1372 ** the process, or if it is the first time sqlite3_initialize() is invoked
   1373 ** following a call to sqlite3_shutdown().  ^(Only an effective call
   1374 ** of sqlite3_initialize() does any initialization.  All other calls
   1375 ** are harmless no-ops.)^
   1376 **
   1377 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
   1378 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
   1379 ** an effective call to sqlite3_shutdown() does any deinitialization.
   1380 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
   1381 **
   1382 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
   1383 ** is not.  The sqlite3_shutdown() interface must only be called from a
   1384 ** single thread.  All open [database connections] must be closed and all
   1385 ** other SQLite resources must be deallocated prior to invoking
   1386 ** sqlite3_shutdown().
   1387 **
   1388 ** Among other things, ^sqlite3_initialize() will invoke
   1389 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
   1390 ** will invoke sqlite3_os_end().
   1391 **
   1392 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
   1393 ** ^If for some reason, sqlite3_initialize() is unable to initialize
   1394 ** the library (perhaps it is unable to allocate a needed resource such
   1395 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
   1396 **
   1397 ** ^The sqlite3_initialize() routine is called internally by many other
   1398 ** SQLite interfaces so that an application usually does not need to
   1399 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
   1400 ** calls sqlite3_initialize() so the SQLite library will be automatically
   1401 ** initialized when [sqlite3_open()] is called if it has not be initialized
   1402 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
   1403 ** compile-time option, then the automatic calls to sqlite3_initialize()
   1404 ** are omitted and the application must call sqlite3_initialize() directly
   1405 ** prior to using any other SQLite interface.  For maximum portability,
   1406 ** it is recommended that applications always invoke sqlite3_initialize()
   1407 ** directly prior to using any other SQLite interface.  Future releases
   1408 ** of SQLite may require this.  In other words, the behavior exhibited
   1409 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
   1410 ** default behavior in some future release of SQLite.
   1411 **
   1412 ** The sqlite3_os_init() routine does operating-system specific
   1413 ** initialization of the SQLite library.  The sqlite3_os_end()
   1414 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
   1415 ** performed by these routines include allocation or deallocation
   1416 ** of static resources, initialization of global variables,
   1417 ** setting up a default [sqlite3_vfs] module, or setting up
   1418 ** a default configuration using [sqlite3_config()].
   1419 **
   1420 ** The application should never invoke either sqlite3_os_init()
   1421 ** or sqlite3_os_end() directly.  The application should only invoke
   1422 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
   1423 ** interface is called automatically by sqlite3_initialize() and
   1424 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
   1425 ** implementations for sqlite3_os_init() and sqlite3_os_end()
   1426 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
   1427 ** When [custom builds | built for other platforms]
   1428 ** (using the [SQLITE_OS_OTHER=1] compile-time
   1429 ** option) the application must supply a suitable implementation for
   1430 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
   1431 ** implementation of sqlite3_os_init() or sqlite3_os_end()
   1432 ** must return [SQLITE_OK] on success and some other [error code] upon
   1433 ** failure.
   1434 */
   1435 SQLITE_API int sqlite3_initialize(void);
   1436 SQLITE_API int sqlite3_shutdown(void);
   1437 SQLITE_API int sqlite3_os_init(void);
   1438 SQLITE_API int sqlite3_os_end(void);
   1439 
   1440 /*
   1441 ** CAPI3REF: Configuring The SQLite Library
   1442 **
   1443 ** The sqlite3_config() interface is used to make global configuration
   1444 ** changes to SQLite in order to tune SQLite to the specific needs of
   1445 ** the application.  The default configuration is recommended for most
   1446 ** applications and so this routine is usually not necessary.  It is
   1447 ** provided to support rare applications with unusual needs.
   1448 **
   1449 ** The sqlite3_config() interface is not threadsafe.  The application
   1450 ** must insure that no other SQLite interfaces are invoked by other
   1451 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
   1452 ** may only be invoked prior to library initialization using
   1453 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
   1454 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
   1455 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
   1456 ** Note, however, that ^sqlite3_config() can be called as part of the
   1457 ** implementation of an application-defined [sqlite3_os_init()].
   1458 **
   1459 ** The first argument to sqlite3_config() is an integer
   1460 ** [configuration option] that determines
   1461 ** what property of SQLite is to be configured.  Subsequent arguments
   1462 ** vary depending on the [configuration option]
   1463 ** in the first argument.
   1464 **
   1465 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
   1466 ** ^If the option is unknown or SQLite is unable to set the option
   1467 ** then this routine returns a non-zero [error code].
   1468 */
   1469 SQLITE_API int sqlite3_config(int, ...);
   1470 
   1471 /*
   1472 ** CAPI3REF: Configure database connections
   1473 **
   1474 ** The sqlite3_db_config() interface is used to make configuration
   1475 ** changes to a [database connection].  The interface is similar to
   1476 ** [sqlite3_config()] except that the changes apply to a single
   1477 ** [database connection] (specified in the first argument).
   1478 **
   1479 ** The second argument to sqlite3_db_config(D,V,...)  is the
   1480 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
   1481 ** that indicates what aspect of the [database connection] is being configured.
   1482 ** Subsequent arguments vary depending on the configuration verb.
   1483 **
   1484 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
   1485 ** the call is considered successful.
   1486 */
   1487 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
   1488 
   1489 /*
   1490 ** CAPI3REF: Memory Allocation Routines
   1491 **
   1492 ** An instance of this object defines the interface between SQLite
   1493 ** and low-level memory allocation routines.
   1494 **
   1495 ** This object is used in only one place in the SQLite interface.
   1496 ** A pointer to an instance of this object is the argument to
   1497 ** [sqlite3_config()] when the configuration option is
   1498 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
   1499 ** By creating an instance of this object
   1500 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
   1501 ** during configuration, an application can specify an alternative
   1502 ** memory allocation subsystem for SQLite to use for all of its
   1503 ** dynamic memory needs.
   1504 **
   1505 ** Note that SQLite comes with several [built-in memory allocators]
   1506 ** that are perfectly adequate for the overwhelming majority of applications
   1507 ** and that this object is only useful to a tiny minority of applications
   1508 ** with specialized memory allocation requirements.  This object is
   1509 ** also used during testing of SQLite in order to specify an alternative
   1510 ** memory allocator that simulates memory out-of-memory conditions in
   1511 ** order to verify that SQLite recovers gracefully from such
   1512 ** conditions.
   1513 **
   1514 ** The xMalloc, xRealloc, and xFree methods must work like the
   1515 ** malloc(), realloc() and free() functions from the standard C library.
   1516 ** ^SQLite guarantees that the second argument to
   1517 ** xRealloc is always a value returned by a prior call to xRoundup.
   1518 **
   1519 ** xSize should return the allocated size of a memory allocation
   1520 ** previously obtained from xMalloc or xRealloc.  The allocated size
   1521 ** is always at least as big as the requested size but may be larger.
   1522 **
   1523 ** The xRoundup method returns what would be the allocated size of
   1524 ** a memory allocation given a particular requested size.  Most memory
   1525 ** allocators round up memory allocations at least to the next multiple
   1526 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
   1527 ** Every memory allocation request coming in through [sqlite3_malloc()]
   1528 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
   1529 ** that causes the corresponding memory allocation to fail.
   1530 **
   1531 ** The xInit method initializes the memory allocator.  For example,
   1532 ** it might allocate any require mutexes or initialize internal data
   1533 ** structures.  The xShutdown method is invoked (indirectly) by
   1534 ** [sqlite3_shutdown()] and should deallocate any resources acquired
   1535 ** by xInit.  The pAppData pointer is used as the only parameter to
   1536 ** xInit and xShutdown.
   1537 **
   1538 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
   1539 ** the xInit method, so the xInit method need not be threadsafe.  The
   1540 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   1541 ** not need to be threadsafe either.  For all other methods, SQLite
   1542 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
   1543 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
   1544 ** it is by default) and so the methods are automatically serialized.
   1545 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
   1546 ** methods must be threadsafe or else make their own arrangements for
   1547 ** serialization.
   1548 **
   1549 ** SQLite will never invoke xInit() more than once without an intervening
   1550 ** call to xShutdown().
   1551 */
   1552 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
   1553 struct sqlite3_mem_methods {
   1554   void *(*xMalloc)(int);         /* Memory allocation function */
   1555   void (*xFree)(void*);          /* Free a prior allocation */
   1556   void *(*xRealloc)(void*,int);  /* Resize an allocation */
   1557   int (*xSize)(void*);           /* Return the size of an allocation */
   1558   int (*xRoundup)(int);          /* Round up request size to allocation size */
   1559   int (*xInit)(void*);           /* Initialize the memory allocator */
   1560   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
   1561   void *pAppData;                /* Argument to xInit() and xShutdown() */
   1562 };
   1563 
   1564 /*
   1565 ** CAPI3REF: Configuration Options
   1566 ** KEYWORDS: {configuration option}
   1567 **
   1568 ** These constants are the available integer configuration options that
   1569 ** can be passed as the first argument to the [sqlite3_config()] interface.
   1570 **
   1571 ** New configuration options may be added in future releases of SQLite.
   1572 ** Existing configuration options might be discontinued.  Applications
   1573 ** should check the return code from [sqlite3_config()] to make sure that
   1574 ** the call worked.  The [sqlite3_config()] interface will return a
   1575 ** non-zero [error code] if a discontinued or unsupported configuration option
   1576 ** is invoked.
   1577 **
   1578 ** <dl>
   1579 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
   1580 ** <dd>There are no arguments to this option.  ^This option sets the
   1581 ** [threading mode] to Single-thread.  In other words, it disables
   1582 ** all mutexing and puts SQLite into a mode where it can only be used
   1583 ** by a single thread.   ^If SQLite is compiled with
   1584 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1585 ** it is not possible to change the [threading mode] from its default
   1586 ** value of Single-thread and so [sqlite3_config()] will return
   1587 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
   1588 ** configuration option.</dd>
   1589 **
   1590 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
   1591 ** <dd>There are no arguments to this option.  ^This option sets the
   1592 ** [threading mode] to Multi-thread.  In other words, it disables
   1593 ** mutexing on [database connection] and [prepared statement] objects.
   1594 ** The application is responsible for serializing access to
   1595 ** [database connections] and [prepared statements].  But other mutexes
   1596 ** are enabled so that SQLite will be safe to use in a multi-threaded
   1597 ** environment as long as no two threads attempt to use the same
   1598 ** [database connection] at the same time.  ^If SQLite is compiled with
   1599 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1600 ** it is not possible to set the Multi-thread [threading mode] and
   1601 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1602 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
   1603 **
   1604 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
   1605 ** <dd>There are no arguments to this option.  ^This option sets the
   1606 ** [threading mode] to Serialized. In other words, this option enables
   1607 ** all mutexes including the recursive
   1608 ** mutexes on [database connection] and [prepared statement] objects.
   1609 ** In this mode (which is the default when SQLite is compiled with
   1610 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
   1611 ** to [database connections] and [prepared statements] so that the
   1612 ** application is free to use the same [database connection] or the
   1613 ** same [prepared statement] in different threads at the same time.
   1614 ** ^If SQLite is compiled with
   1615 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1616 ** it is not possible to set the Serialized [threading mode] and
   1617 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1618 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
   1619 **
   1620 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
   1621 ** <dd> ^(This option takes a single argument which is a pointer to an
   1622 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
   1623 ** alternative low-level memory allocation routines to be used in place of
   1624 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
   1625 ** its own private copy of the content of the [sqlite3_mem_methods] structure
   1626 ** before the [sqlite3_config()] call returns.</dd>
   1627 **
   1628 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
   1629 ** <dd> ^(This option takes a single argument which is a pointer to an
   1630 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
   1631 ** structure is filled with the currently defined memory allocation routines.)^
   1632 ** This option can be used to overload the default memory allocation
   1633 ** routines with a wrapper that simulations memory allocation failure or
   1634 ** tracks memory usage, for example. </dd>
   1635 **
   1636 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
   1637 ** <dd> ^This option takes single argument of type int, interpreted as a
   1638 ** boolean, which enables or disables the collection of memory allocation
   1639 ** statistics. ^(When memory allocation statistics are disabled, the
   1640 ** following SQLite interfaces become non-operational:
   1641 **   <ul>
   1642 **   <li> [sqlite3_memory_used()]
   1643 **   <li> [sqlite3_memory_highwater()]
   1644 **   <li> [sqlite3_soft_heap_limit64()]
   1645 **   <li> [sqlite3_status()]
   1646 **   </ul>)^
   1647 ** ^Memory allocation statistics are enabled by default unless SQLite is
   1648 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
   1649 ** allocation statistics are disabled by default.
   1650 ** </dd>
   1651 **
   1652 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
   1653 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1654 ** scratch memory.  There are three arguments:  A pointer an 8-byte
   1655 ** aligned memory buffer from which the scratch allocations will be
   1656 ** drawn, the size of each scratch allocation (sz),
   1657 ** and the maximum number of scratch allocations (N).  The sz
   1658 ** argument must be a multiple of 16.
   1659 ** The first argument must be a pointer to an 8-byte aligned buffer
   1660 ** of at least sz*N bytes of memory.
   1661 ** ^SQLite will use no more than two scratch buffers per thread.  So
   1662 ** N should be set to twice the expected maximum number of threads.
   1663 ** ^SQLite will never require a scratch buffer that is more than 6
   1664 ** times the database page size. ^If SQLite needs needs additional
   1665 ** scratch memory beyond what is provided by this configuration option, then
   1666 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
   1667 **
   1668 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
   1669 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1670 ** the database page cache with the default page cache implementation.
   1671 ** This configuration should not be used if an application-define page
   1672 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
   1673 ** There are three arguments to this option: A pointer to 8-byte aligned
   1674 ** memory, the size of each page buffer (sz), and the number of pages (N).
   1675 ** The sz argument should be the size of the largest database page
   1676 ** (a power of two between 512 and 32768) plus a little extra for each
   1677 ** page header.  ^The page header size is 20 to 40 bytes depending on
   1678 ** the host architecture.  ^It is harmless, apart from the wasted memory,
   1679 ** to make sz a little too large.  The first
   1680 ** argument should point to an allocation of at least sz*N bytes of memory.
   1681 ** ^SQLite will use the memory provided by the first argument to satisfy its
   1682 ** memory needs for the first N pages that it adds to cache.  ^If additional
   1683 ** page cache memory is needed beyond what is provided by this option, then
   1684 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
   1685 ** The pointer in the first argument must
   1686 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
   1687 ** will be undefined.</dd>
   1688 **
   1689 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
   1690 ** <dd> ^This option specifies a static memory buffer that SQLite will use
   1691 ** for all of its dynamic memory allocation needs beyond those provided
   1692 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
   1693 ** There are three arguments: An 8-byte aligned pointer to the memory,
   1694 ** the number of bytes in the memory buffer, and the minimum allocation size.
   1695 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
   1696 ** to using its default memory allocator (the system malloc() implementation),
   1697 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
   1698 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
   1699 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
   1700 ** allocator is engaged to handle all of SQLites memory allocation needs.
   1701 ** The first pointer (the memory pointer) must be aligned to an 8-byte
   1702 ** boundary or subsequent behavior of SQLite will be undefined.
   1703 ** The minimum allocation size is capped at 2**12. Reasonable values
   1704 ** for the minimum allocation size are 2**5 through 2**8.</dd>
   1705 **
   1706 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
   1707 ** <dd> ^(This option takes a single argument which is a pointer to an
   1708 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
   1709 ** alternative low-level mutex routines to be used in place
   1710 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
   1711 ** content of the [sqlite3_mutex_methods] structure before the call to
   1712 ** [sqlite3_config()] returns. ^If SQLite is compiled with
   1713 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1714 ** the entire mutexing subsystem is omitted from the build and hence calls to
   1715 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
   1716 ** return [SQLITE_ERROR].</dd>
   1717 **
   1718 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
   1719 ** <dd> ^(This option takes a single argument which is a pointer to an
   1720 ** instance of the [sqlite3_mutex_methods] structure.  The
   1721 ** [sqlite3_mutex_methods]
   1722 ** structure is filled with the currently defined mutex routines.)^
   1723 ** This option can be used to overload the default mutex allocation
   1724 ** routines with a wrapper used to track mutex usage for performance
   1725 ** profiling or testing, for example.   ^If SQLite is compiled with
   1726 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1727 ** the entire mutexing subsystem is omitted from the build and hence calls to
   1728 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
   1729 ** return [SQLITE_ERROR].</dd>
   1730 **
   1731 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
   1732 ** <dd> ^(This option takes two arguments that determine the default
   1733 ** memory allocation for the lookaside memory allocator on each
   1734 ** [database connection].  The first argument is the
   1735 ** size of each lookaside buffer slot and the second is the number of
   1736 ** slots allocated to each database connection.)^  ^(This option sets the
   1737 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
   1738 ** verb to [sqlite3_db_config()] can be used to change the lookaside
   1739 ** configuration on individual connections.)^ </dd>
   1740 **
   1741 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
   1742 ** <dd> ^(This option takes a single argument which is a pointer to
   1743 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
   1744 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
   1745 ** object and uses it for page cache memory allocations.</dd>
   1746 **
   1747 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
   1748 ** <dd> ^(This option takes a single argument which is a pointer to an
   1749 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
   1750 ** page cache implementation into that object.)^ </dd>
   1751 **
   1752 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
   1753 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
   1754 ** global [error log].
   1755 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
   1756 ** function with a call signature of void(*)(void*,int,const char*),
   1757 ** and a pointer to void. ^If the function pointer is not NULL, it is
   1758 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
   1759 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
   1760 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
   1761 ** passed through as the first parameter to the application-defined logger
   1762 ** function whenever that function is invoked.  ^The second parameter to
   1763 ** the logger function is a copy of the first parameter to the corresponding
   1764 ** [sqlite3_log()] call and is intended to be a [result code] or an
   1765 ** [extended result code].  ^The third parameter passed to the logger is
   1766 ** log message after formatting via [sqlite3_snprintf()].
   1767 ** The SQLite logging interface is not reentrant; the logger function
   1768 ** supplied by the application must not invoke any SQLite interface.
   1769 ** In a multi-threaded application, the application-defined logger
   1770 ** function must be threadsafe. </dd>
   1771 **
   1772 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
   1773 ** <dd>^(This option takes a single argument of type int. If non-zero, then
   1774 ** URI handling is globally enabled. If the parameter is zero, then URI handling
   1775 ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
   1776 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
   1777 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
   1778 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
   1779 ** connection is opened. ^If it is globally disabled, filenames are
   1780 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
   1781 ** database connection is opened. ^(By default, URI handling is globally
   1782 ** disabled. The default value may be changed by compiling with the
   1783 ** [SQLITE_USE_URI] symbol defined.)^
   1784 **
   1785 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
   1786 ** <dd>^This option takes a single integer argument which is interpreted as
   1787 ** a boolean in order to enable or disable the use of covering indices for
   1788 ** full table scans in the query optimizer.  ^The default setting is determined
   1789 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
   1790 ** if that compile-time option is omitted.
   1791 ** The ability to disable the use of covering indices for full table scans
   1792 ** is because some incorrectly coded legacy applications might malfunction
   1793 ** when the optimization is enabled.  Providing the ability to
   1794 ** disable the optimization allows the older, buggy application code to work
   1795 ** without change even with newer versions of SQLite.
   1796 **
   1797 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
   1798 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
   1799 ** <dd> These options are obsolete and should not be used by new code.
   1800 ** They are retained for backwards compatibility but are now no-ops.
   1801 ** </dd>
   1802 **
   1803 ** [[SQLITE_CONFIG_SQLLOG]]
   1804 ** <dt>SQLITE_CONFIG_SQLLOG
   1805 ** <dd>This option is only available if sqlite is compiled with the
   1806 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
   1807 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
   1808 ** The second should be of type (void*). The callback is invoked by the library
   1809 ** in three separate circumstances, identified by the value passed as the
   1810 ** fourth parameter. If the fourth parameter is 0, then the database connection
   1811 ** passed as the second argument has just been opened. The third argument
   1812 ** points to a buffer containing the name of the main database file. If the
   1813 ** fourth parameter is 1, then the SQL statement that the third parameter
   1814 ** points to has just been executed. Or, if the fourth parameter is 2, then
   1815 ** the connection being passed as the second parameter is being closed. The
   1816 ** third parameter is passed NULL In this case.  An example of using this
   1817 ** configuration option can be seen in the "test_sqllog.c" source file in
   1818 ** the canonical SQLite source tree.</dd>
   1819 **
   1820 ** [[SQLITE_CONFIG_MMAP_SIZE]]
   1821 ** <dt>SQLITE_CONFIG_MMAP_SIZE
   1822 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
   1823 ** that are the default mmap size limit (the default setting for
   1824 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
   1825 ** ^The default setting can be overridden by each database connection using
   1826 ** either the [PRAGMA mmap_size] command, or by using the
   1827 ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
   1828 ** cannot be changed at run-time.  Nor may the maximum allowed mmap size
   1829 ** exceed the compile-time maximum mmap size set by the
   1830 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
   1831 ** ^If either argument to this option is negative, then that argument is
   1832 ** changed to its compile-time default.
   1833 **
   1834 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
   1835 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
   1836 ** <dd>^This option is only available if SQLite is compiled for Windows
   1837 ** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
   1838 ** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
   1839 ** that specifies the maximum size of the created heap.
   1840 ** </dl>
   1841 */
   1842 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
   1843 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
   1844 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
   1845 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
   1846 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
   1847 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
   1848 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
   1849 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
   1850 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
   1851 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
   1852 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
   1853 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
   1854 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
   1855 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
   1856 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
   1857 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
   1858 #define SQLITE_CONFIG_URI          17  /* int */
   1859 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
   1860 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
   1861 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
   1862 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
   1863 #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
   1864 #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
   1865 
   1866 /*
   1867 ** CAPI3REF: Database Connection Configuration Options
   1868 **
   1869 ** These constants are the available integer configuration options that
   1870 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
   1871 **
   1872 ** New configuration options may be added in future releases of SQLite.
   1873 ** Existing configuration options might be discontinued.  Applications
   1874 ** should check the return code from [sqlite3_db_config()] to make sure that
   1875 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
   1876 ** non-zero [error code] if a discontinued or unsupported configuration option
   1877 ** is invoked.
   1878 **
   1879 ** <dl>
   1880 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
   1881 ** <dd> ^This option takes three additional arguments that determine the
   1882 ** [lookaside memory allocator] configuration for the [database connection].
   1883 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
   1884 ** pointer to a memory buffer to use for lookaside memory.
   1885 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
   1886 ** may be NULL in which case SQLite will allocate the
   1887 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
   1888 ** size of each lookaside buffer slot.  ^The third argument is the number of
   1889 ** slots.  The size of the buffer in the first argument must be greater than
   1890 ** or equal to the product of the second and third arguments.  The buffer
   1891 ** must be aligned to an 8-byte boundary.  ^If the second argument to
   1892 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
   1893 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
   1894 ** configuration for a database connection can only be changed when that
   1895 ** connection is not currently using lookaside memory, or in other words
   1896 ** when the "current value" returned by
   1897 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
   1898 ** Any attempt to change the lookaside memory configuration when lookaside
   1899 ** memory is in use leaves the configuration unchanged and returns
   1900 ** [SQLITE_BUSY].)^</dd>
   1901 **
   1902 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
   1903 ** <dd> ^This option is used to enable or disable the enforcement of
   1904 ** [foreign key constraints].  There should be two additional arguments.
   1905 ** The first argument is an integer which is 0 to disable FK enforcement,
   1906 ** positive to enable FK enforcement or negative to leave FK enforcement
   1907 ** unchanged.  The second parameter is a pointer to an integer into which
   1908 ** is written 0 or 1 to indicate whether FK enforcement is off or on
   1909 ** following this call.  The second parameter may be a NULL pointer, in
   1910 ** which case the FK enforcement setting is not reported back. </dd>
   1911 **
   1912 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
   1913 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
   1914 ** There should be two additional arguments.
   1915 ** The first argument is an integer which is 0 to disable triggers,
   1916 ** positive to enable triggers or negative to leave the setting unchanged.
   1917 ** The second parameter is a pointer to an integer into which
   1918 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
   1919 ** following this call.  The second parameter may be a NULL pointer, in
   1920 ** which case the trigger setting is not reported back. </dd>
   1921 **
   1922 ** </dl>
   1923 */
   1924 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
   1925 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
   1926 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
   1927 
   1928 
   1929 /*
   1930 ** CAPI3REF: Enable Or Disable Extended Result Codes
   1931 **
   1932 ** ^The sqlite3_extended_result_codes() routine enables or disables the
   1933 ** [extended result codes] feature of SQLite. ^The extended result
   1934 ** codes are disabled by default for historical compatibility.
   1935 */
   1936 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
   1937 
   1938 /*
   1939 ** CAPI3REF: Last Insert Rowid
   1940 **
   1941 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
   1942 ** has a unique 64-bit signed
   1943 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
   1944 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
   1945 ** names are not also used by explicitly declared columns. ^If
   1946 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
   1947 ** is another alias for the rowid.
   1948 **
   1949 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
   1950 ** most recent successful [INSERT] into a rowid table or [virtual table]
   1951 ** on database connection D.
   1952 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
   1953 ** ^If no successful [INSERT]s into rowid tables
   1954 ** have ever occurred on the database connection D,
   1955 ** then sqlite3_last_insert_rowid(D) returns zero.
   1956 **
   1957 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
   1958 ** method, then this routine will return the [rowid] of the inserted
   1959 ** row as long as the trigger or virtual table method is running.
   1960 ** But once the trigger or virtual table method ends, the value returned
   1961 ** by this routine reverts to what it was before the trigger or virtual
   1962 ** table method began.)^
   1963 **
   1964 ** ^An [INSERT] that fails due to a constraint violation is not a
   1965 ** successful [INSERT] and does not change the value returned by this
   1966 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
   1967 ** and INSERT OR ABORT make no changes to the return value of this
   1968 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
   1969 ** encounters a constraint violation, it does not fail.  The
   1970 ** INSERT continues to completion after deleting rows that caused
   1971 ** the constraint problem so INSERT OR REPLACE will always change
   1972 ** the return value of this interface.)^
   1973 **
   1974 ** ^For the purposes of this routine, an [INSERT] is considered to
   1975 ** be successful even if it is subsequently rolled back.
   1976 **
   1977 ** This function is accessible to SQL statements via the
   1978 ** [last_insert_rowid() SQL function].
   1979 **
   1980 ** If a separate thread performs a new [INSERT] on the same
   1981 ** database connection while the [sqlite3_last_insert_rowid()]
   1982 ** function is running and thus changes the last insert [rowid],
   1983 ** then the value returned by [sqlite3_last_insert_rowid()] is
   1984 ** unpredictable and might not equal either the old or the new
   1985 ** last insert [rowid].
   1986 */
   1987 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
   1988 
   1989 /*
   1990 ** CAPI3REF: Count The Number Of Rows Modified
   1991 **
   1992 ** ^This function returns the number of database rows that were changed
   1993 ** or inserted or deleted by the most recently completed SQL statement
   1994 ** on the [database connection] specified by the first parameter.
   1995 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
   1996 ** or [DELETE] statement are counted.  Auxiliary changes caused by
   1997 ** triggers or [foreign key actions] are not counted.)^ Use the
   1998 ** [sqlite3_total_changes()] function to find the total number of changes
   1999 ** including changes caused by triggers and foreign key actions.
   2000 **
   2001 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
   2002 ** are not counted.  Only real table changes are counted.
   2003 **
   2004 ** ^(A "row change" is a change to a single row of a single table
   2005 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
   2006 ** are changed as side effects of [REPLACE] constraint resolution,
   2007 ** rollback, ABORT processing, [DROP TABLE], or by any other
   2008 ** mechanisms do not count as direct row changes.)^
   2009 **
   2010 ** A "trigger context" is a scope of execution that begins and
   2011 ** ends with the script of a [CREATE TRIGGER | trigger].
   2012 ** Most SQL statements are
   2013 ** evaluated outside of any trigger.  This is the "top level"
   2014 ** trigger context.  If a trigger fires from the top level, a
   2015 ** new trigger context is entered for the duration of that one
   2016 ** trigger.  Subtriggers create subcontexts for their duration.
   2017 **
   2018 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
   2019 ** not create a new trigger context.
   2020 **
   2021 ** ^This function returns the number of direct row changes in the
   2022 ** most recent INSERT, UPDATE, or DELETE statement within the same
   2023 ** trigger context.
   2024 **
   2025 ** ^Thus, when called from the top level, this function returns the
   2026 ** number of changes in the most recent INSERT, UPDATE, or DELETE
   2027 ** that also occurred at the top level.  ^(Within the body of a trigger,
   2028 ** the sqlite3_changes() interface can be called to find the number of
   2029 ** changes in the most recently completed INSERT, UPDATE, or DELETE
   2030 ** statement within the body of the same trigger.
   2031 ** However, the number returned does not include changes
   2032 ** caused by subtriggers since those have their own context.)^
   2033 **
   2034 ** See also the [sqlite3_total_changes()] interface, the
   2035 ** [count_changes pragma], and the [changes() SQL function].
   2036 **
   2037 ** If a separate thread makes changes on the same database connection
   2038 ** while [sqlite3_changes()] is running then the value returned
   2039 ** is unpredictable and not meaningful.
   2040 */
   2041 SQLITE_API int sqlite3_changes(sqlite3*);
   2042 
   2043 /*
   2044 ** CAPI3REF: Total Number Of Rows Modified
   2045 **
   2046 ** ^This function returns the number of row changes caused by [INSERT],
   2047 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
   2048 ** ^(The count returned by sqlite3_total_changes() includes all changes
   2049 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
   2050 ** [foreign key actions]. However,
   2051 ** the count does not include changes used to implement [REPLACE] constraints,
   2052 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
   2053 ** count does not include rows of views that fire an [INSTEAD OF trigger],
   2054 ** though if the INSTEAD OF trigger makes changes of its own, those changes
   2055 ** are counted.)^
   2056 ** ^The sqlite3_total_changes() function counts the changes as soon as
   2057 ** the statement that makes them is completed (when the statement handle
   2058 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
   2059 **
   2060 ** See also the [sqlite3_changes()] interface, the
   2061 ** [count_changes pragma], and the [total_changes() SQL function].
   2062 **
   2063 ** If a separate thread makes changes on the same database connection
   2064 ** while [sqlite3_total_changes()] is running then the value
   2065 ** returned is unpredictable and not meaningful.
   2066 */
   2067 SQLITE_API int sqlite3_total_changes(sqlite3*);
   2068 
   2069 /*
   2070 ** CAPI3REF: Interrupt A Long-Running Query
   2071 **
   2072 ** ^This function causes any pending database operation to abort and
   2073 ** return at its earliest opportunity. This routine is typically
   2074 ** called in response to a user action such as pressing "Cancel"
   2075 ** or Ctrl-C where the user wants a long query operation to halt
   2076 ** immediately.
   2077 **
   2078 ** ^It is safe to call this routine from a thread different from the
   2079 ** thread that is currently running the database operation.  But it
   2080 ** is not safe to call this routine with a [database connection] that
   2081 ** is closed or might close before sqlite3_interrupt() returns.
   2082 **
   2083 ** ^If an SQL operation is very nearly finished at the time when
   2084 ** sqlite3_interrupt() is called, then it might not have an opportunity
   2085 ** to be interrupted and might continue to completion.
   2086 **
   2087 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
   2088 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
   2089 ** that is inside an explicit transaction, then the entire transaction
   2090 ** will be rolled back automatically.
   2091 **
   2092 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
   2093 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
   2094 ** that are started after the sqlite3_interrupt() call and before the
   2095 ** running statements reaches zero are interrupted as if they had been
   2096 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
   2097 ** that are started after the running statement count reaches zero are
   2098 ** not effected by the sqlite3_interrupt().
   2099 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
   2100 ** SQL statements is a no-op and has no effect on SQL statements
   2101 ** that are started after the sqlite3_interrupt() call returns.
   2102 **
   2103 ** If the database connection closes while [sqlite3_interrupt()]
   2104 ** is running then bad things will likely happen.
   2105 */
   2106 SQLITE_API void sqlite3_interrupt(sqlite3*);
   2107 
   2108 /*
   2109 ** CAPI3REF: Determine If An SQL Statement Is Complete
   2110 **
   2111 ** These routines are useful during command-line input to determine if the
   2112 ** currently entered text seems to form a complete SQL statement or
   2113 ** if additional input is needed before sending the text into
   2114 ** SQLite for parsing.  ^These routines return 1 if the input string
   2115 ** appears to be a complete SQL statement.  ^A statement is judged to be
   2116 ** complete if it ends with a semicolon token and is not a prefix of a
   2117 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
   2118 ** string literals or quoted identifier names or comments are not
   2119 ** independent tokens (they are part of the token in which they are
   2120 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
   2121 ** and comments that follow the final semicolon are ignored.
   2122 **
   2123 ** ^These routines return 0 if the statement is incomplete.  ^If a
   2124 ** memory allocation fails, then SQLITE_NOMEM is returned.
   2125 **
   2126 ** ^These routines do not parse the SQL statements thus
   2127 ** will not detect syntactically incorrect SQL.
   2128 **
   2129 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
   2130 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
   2131 ** automatically by sqlite3_complete16().  If that initialization fails,
   2132 ** then the return value from sqlite3_complete16() will be non-zero
   2133 ** regardless of whether or not the input SQL is complete.)^
   2134 **
   2135 ** The input to [sqlite3_complete()] must be a zero-terminated
   2136 ** UTF-8 string.
   2137 **
   2138 ** The input to [sqlite3_complete16()] must be a zero-terminated
   2139 ** UTF-16 string in native byte order.
   2140 */
   2141 SQLITE_API int sqlite3_complete(const char *sql);
   2142 SQLITE_API int sqlite3_complete16(const void *sql);
   2143 
   2144 /*
   2145 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
   2146 **
   2147 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
   2148 ** that might be invoked with argument P whenever
   2149 ** an attempt is made to access a database table associated with
   2150 ** [database connection] D when another thread
   2151 ** or process has the table locked.
   2152 ** The sqlite3_busy_handler() interface is used to implement
   2153 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
   2154 **
   2155 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
   2156 ** is returned immediately upon encountering the lock.  ^If the busy callback
   2157 ** is not NULL, then the callback might be invoked with two arguments.
   2158 **
   2159 ** ^The first argument to the busy handler is a copy of the void* pointer which
   2160 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
   2161 ** the busy handler callback is the number of times that the busy handler has
   2162 ** been invoked for the same locking event.  ^If the
   2163 ** busy callback returns 0, then no additional attempts are made to
   2164 ** access the database and [SQLITE_BUSY] is returned
   2165 ** to the application.
   2166 ** ^If the callback returns non-zero, then another attempt
   2167 ** is made to access the database and the cycle repeats.
   2168 **
   2169 ** The presence of a busy handler does not guarantee that it will be invoked
   2170 ** when there is lock contention. ^If SQLite determines that invoking the busy
   2171 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
   2172 ** to the application instead of invoking the
   2173 ** busy handler.
   2174 ** Consider a scenario where one process is holding a read lock that
   2175 ** it is trying to promote to a reserved lock and
   2176 ** a second process is holding a reserved lock that it is trying
   2177 ** to promote to an exclusive lock.  The first process cannot proceed
   2178 ** because it is blocked by the second and the second process cannot
   2179 ** proceed because it is blocked by the first.  If both processes
   2180 ** invoke the busy handlers, neither will make any progress.  Therefore,
   2181 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
   2182 ** will induce the first process to release its read lock and allow
   2183 ** the second process to proceed.
   2184 **
   2185 ** ^The default busy callback is NULL.
   2186 **
   2187 ** ^(There can only be a single busy handler defined for each
   2188 ** [database connection].  Setting a new busy handler clears any
   2189 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
   2190 ** or evaluating [PRAGMA busy_timeout=N] will change the
   2191 ** busy handler and thus clear any previously set busy handler.
   2192 **
   2193 ** The busy callback should not take any actions which modify the
   2194 ** database connection that invoked the busy handler.  In other words,
   2195 ** the busy handler is not reentrant.  Any such actions
   2196 ** result in undefined behavior.
   2197 **
   2198 ** A busy handler must not close the database connection
   2199 ** or [prepared statement] that invoked the busy handler.
   2200 */
   2201 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
   2202 
   2203 /*
   2204 ** CAPI3REF: Set A Busy Timeout
   2205 **
   2206 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
   2207 ** for a specified amount of time when a table is locked.  ^The handler
   2208 ** will sleep multiple times until at least "ms" milliseconds of sleeping
   2209 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
   2210 ** the handler returns 0 which causes [sqlite3_step()] to return
   2211 ** [SQLITE_BUSY].
   2212 **
   2213 ** ^Calling this routine with an argument less than or equal to zero
   2214 ** turns off all busy handlers.
   2215 **
   2216 ** ^(There can only be a single busy handler for a particular
   2217 ** [database connection] any any given moment.  If another busy handler
   2218 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
   2219 ** this routine, that other busy handler is cleared.)^
   2220 **
   2221 ** See also:  [PRAGMA busy_timeout]
   2222 */
   2223 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
   2224 
   2225 /*
   2226 ** CAPI3REF: Convenience Routines For Running Queries
   2227 **
   2228 ** This is a legacy interface that is preserved for backwards compatibility.
   2229 ** Use of this interface is not recommended.
   2230 **
   2231 ** Definition: A <b>result table</b> is memory data structure created by the
   2232 ** [sqlite3_get_table()] interface.  A result table records the
   2233 ** complete query results from one or more queries.
   2234 **
   2235 ** The table conceptually has a number of rows and columns.  But
   2236 ** these numbers are not part of the result table itself.  These
   2237 ** numbers are obtained separately.  Let N be the number of rows
   2238 ** and M be the number of columns.
   2239 **
   2240 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
   2241 ** There are (N+1)*M elements in the array.  The first M pointers point
   2242 ** to zero-terminated strings that  contain the names of the columns.
   2243 ** The remaining entries all point to query results.  NULL values result
   2244 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
   2245 ** string representation as returned by [sqlite3_column_text()].
   2246 **
   2247 ** A result table might consist of one or more memory allocations.
   2248 ** It is not safe to pass a result table directly to [sqlite3_free()].
   2249 ** A result table should be deallocated using [sqlite3_free_table()].
   2250 **
   2251 ** ^(As an example of the result table format, suppose a query result
   2252 ** is as follows:
   2253 **
   2254 ** <blockquote><pre>
   2255 **        Name        | Age
   2256 **        -----------------------
   2257 **        Alice       | 43
   2258 **        Bob         | 28
   2259 **        Cindy       | 21
   2260 ** </pre></blockquote>
   2261 **
   2262 ** There are two column (M==2) and three rows (N==3).  Thus the
   2263 ** result table has 8 entries.  Suppose the result table is stored
   2264 ** in an array names azResult.  Then azResult holds this content:
   2265 **
   2266 ** <blockquote><pre>
   2267 **        azResult&#91;0] = "Name";
   2268 **        azResult&#91;1] = "Age";
   2269 **        azResult&#91;2] = "Alice";
   2270 **        azResult&#91;3] = "43";
   2271 **        azResult&#91;4] = "Bob";
   2272 **        azResult&#91;5] = "28";
   2273 **        azResult&#91;6] = "Cindy";
   2274 **        azResult&#91;7] = "21";
   2275 ** </pre></blockquote>)^
   2276 **
   2277 ** ^The sqlite3_get_table() function evaluates one or more
   2278 ** semicolon-separated SQL statements in the zero-terminated UTF-8
   2279 ** string of its 2nd parameter and returns a result table to the
   2280 ** pointer given in its 3rd parameter.
   2281 **
   2282 ** After the application has finished with the result from sqlite3_get_table(),
   2283 ** it must pass the result table pointer to sqlite3_free_table() in order to
   2284 ** release the memory that was malloced.  Because of the way the
   2285 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
   2286 ** function must not try to call [sqlite3_free()] directly.  Only
   2287 ** [sqlite3_free_table()] is able to release the memory properly and safely.
   2288 **
   2289 ** The sqlite3_get_table() interface is implemented as a wrapper around
   2290 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
   2291 ** to any internal data structures of SQLite.  It uses only the public
   2292 ** interface defined here.  As a consequence, errors that occur in the
   2293 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
   2294 ** reflected in subsequent calls to [sqlite3_errcode()] or
   2295 ** [sqlite3_errmsg()].
   2296 */
   2297 SQLITE_API int sqlite3_get_table(
   2298   sqlite3 *db,          /* An open database */
   2299   const char *zSql,     /* SQL to be evaluated */
   2300   char ***pazResult,    /* Results of the query */
   2301   int *pnRow,           /* Number of result rows written here */
   2302   int *pnColumn,        /* Number of result columns written here */
   2303   char **pzErrmsg       /* Error msg written here */
   2304 );
   2305 SQLITE_API void sqlite3_free_table(char **result);
   2306 
   2307 /*
   2308 ** CAPI3REF: Formatted String Printing Functions
   2309 **
   2310 ** These routines are work-alikes of the "printf()" family of functions
   2311 ** from the standard C library.
   2312 **
   2313 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
   2314 ** results into memory obtained from [sqlite3_malloc()].
   2315 ** The strings returned by these two routines should be
   2316 ** released by [sqlite3_free()].  ^Both routines return a
   2317 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
   2318 ** memory to hold the resulting string.
   2319 **
   2320 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
   2321 ** the standard C library.  The result is written into the
   2322 ** buffer supplied as the second parameter whose size is given by
   2323 ** the first parameter. Note that the order of the
   2324 ** first two parameters is reversed from snprintf().)^  This is an
   2325 ** historical accident that cannot be fixed without breaking
   2326 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
   2327 ** returns a pointer to its buffer instead of the number of
   2328 ** characters actually written into the buffer.)^  We admit that
   2329 ** the number of characters written would be a more useful return
   2330 ** value but we cannot change the implementation of sqlite3_snprintf()
   2331 ** now without breaking compatibility.
   2332 **
   2333 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
   2334 ** guarantees that the buffer is always zero-terminated.  ^The first
   2335 ** parameter "n" is the total size of the buffer, including space for
   2336 ** the zero terminator.  So the longest string that can be completely
   2337 ** written will be n-1 characters.
   2338 **
   2339 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
   2340 **
   2341 ** These routines all implement some additional formatting
   2342 ** options that are useful for constructing SQL statements.
   2343 ** All of the usual printf() formatting options apply.  In addition, there
   2344 ** is are "%q", "%Q", and "%z" options.
   2345 **
   2346 ** ^(The %q option works like %s in that it substitutes a nul-terminated
   2347 ** string from the argument list.  But %q also doubles every '\'' character.
   2348 ** %q is designed for use inside a string literal.)^  By doubling each '\''
   2349 ** character it escapes that character and allows it to be inserted into
   2350 ** the string.
   2351 **
   2352 ** For example, assume the string variable zText contains text as follows:
   2353 **
   2354 ** <blockquote><pre>
   2355 **  char *zText = "It's a happy day!";
   2356 ** </pre></blockquote>
   2357 **
   2358 ** One can use this text in an SQL statement as follows:
   2359 **
   2360 ** <blockquote><pre>
   2361 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
   2362 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2363 **  sqlite3_free(zSQL);
   2364 ** </pre></blockquote>
   2365 **
   2366 ** Because the %q format string is used, the '\'' character in zText
   2367 ** is escaped and the SQL generated is as follows:
   2368 **
   2369 ** <blockquote><pre>
   2370 **  INSERT INTO table1 VALUES('It''s a happy day!')
   2371 ** </pre></blockquote>
   2372 **
   2373 ** This is correct.  Had we used %s instead of %q, the generated SQL
   2374 ** would have looked like this:
   2375 **
   2376 ** <blockquote><pre>
   2377 **  INSERT INTO table1 VALUES('It's a happy day!');
   2378 ** </pre></blockquote>
   2379 **
   2380 ** This second example is an SQL syntax error.  As a general rule you should
   2381 ** always use %q instead of %s when inserting text into a string literal.
   2382 **
   2383 ** ^(The %Q option works like %q except it also adds single quotes around
   2384 ** the outside of the total string.  Additionally, if the parameter in the
   2385 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
   2386 ** single quotes).)^  So, for example, one could say:
   2387 **
   2388 ** <blockquote><pre>
   2389 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
   2390 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2391 **  sqlite3_free(zSQL);
   2392 ** </pre></blockquote>
   2393 **
   2394 ** The code above will render a correct SQL statement in the zSQL
   2395 ** variable even if the zText variable is a NULL pointer.
   2396 **
   2397 ** ^(The "%z" formatting option works like "%s" but with the
   2398 ** addition that after the string has been read and copied into
   2399 ** the result, [sqlite3_free()] is called on the input string.)^
   2400 */
   2401 SQLITE_API char *sqlite3_mprintf(const char*,...);
   2402 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
   2403 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
   2404 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
   2405 
   2406 /*
   2407 ** CAPI3REF: Memory Allocation Subsystem
   2408 **
   2409 ** The SQLite core uses these three routines for all of its own
   2410 ** internal memory allocation needs. "Core" in the previous sentence
   2411 ** does not include operating-system specific VFS implementation.  The
   2412 ** Windows VFS uses native malloc() and free() for some operations.
   2413 **
   2414 ** ^The sqlite3_malloc() routine returns a pointer to a block
   2415 ** of memory at least N bytes in length, where N is the parameter.
   2416 ** ^If sqlite3_malloc() is unable to obtain sufficient free
   2417 ** memory, it returns a NULL pointer.  ^If the parameter N to
   2418 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
   2419 ** a NULL pointer.
   2420 **
   2421 ** ^Calling sqlite3_free() with a pointer previously returned
   2422 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
   2423 ** that it might be reused.  ^The sqlite3_free() routine is
   2424 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
   2425 ** to sqlite3_free() is harmless.  After being freed, memory
   2426 ** should neither be read nor written.  Even reading previously freed
   2427 ** memory might result in a segmentation fault or other severe error.
   2428 ** Memory corruption, a segmentation fault, or other severe error
   2429 ** might result if sqlite3_free() is called with a non-NULL pointer that
   2430 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
   2431 **
   2432 ** ^(The sqlite3_realloc() interface attempts to resize a
   2433 ** prior memory allocation to be at least N bytes, where N is the
   2434 ** second parameter.  The memory allocation to be resized is the first
   2435 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
   2436 ** is a NULL pointer then its behavior is identical to calling
   2437 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
   2438 ** ^If the second parameter to sqlite3_realloc() is zero or
   2439 ** negative then the behavior is exactly the same as calling
   2440 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
   2441 ** ^sqlite3_realloc() returns a pointer to a memory allocation
   2442 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
   2443 ** ^If M is the size of the prior allocation, then min(N,M) bytes
   2444 ** of the prior allocation are copied into the beginning of buffer returned
   2445 ** by sqlite3_realloc() and the prior allocation is freed.
   2446 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
   2447 ** is not freed.
   2448 **
   2449 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
   2450 ** is always aligned to at least an 8 byte boundary, or to a
   2451 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
   2452 ** option is used.
   2453 **
   2454 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
   2455 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
   2456 ** implementation of these routines to be omitted.  That capability
   2457 ** is no longer provided.  Only built-in memory allocators can be used.
   2458 **
   2459 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
   2460 ** the system malloc() and free() directly when converting
   2461 ** filenames between the UTF-8 encoding used by SQLite
   2462 ** and whatever filename encoding is used by the particular Windows
   2463 ** installation.  Memory allocation errors were detected, but
   2464 ** they were reported back as [SQLITE_CANTOPEN] or
   2465 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
   2466 **
   2467 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
   2468 ** must be either NULL or else pointers obtained from a prior
   2469 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
   2470 ** not yet been released.
   2471 **
   2472 ** The application must not read or write any part of
   2473 ** a block of memory after it has been released using
   2474 ** [sqlite3_free()] or [sqlite3_realloc()].
   2475 */
   2476 SQLITE_API void *sqlite3_malloc(int);
   2477 SQLITE_API void *sqlite3_realloc(void*, int);
   2478 SQLITE_API void sqlite3_free(void*);
   2479 
   2480 /*
   2481 ** CAPI3REF: Memory Allocator Statistics
   2482 **
   2483 ** SQLite provides these two interfaces for reporting on the status
   2484 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
   2485 ** routines, which form the built-in memory allocation subsystem.
   2486 **
   2487 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
   2488 ** of memory currently outstanding (malloced but not freed).
   2489 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
   2490 ** value of [sqlite3_memory_used()] since the high-water mark
   2491 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
   2492 ** [sqlite3_memory_highwater()] include any overhead
   2493 ** added by SQLite in its implementation of [sqlite3_malloc()],
   2494 ** but not overhead added by the any underlying system library
   2495 ** routines that [sqlite3_malloc()] may call.
   2496 **
   2497 ** ^The memory high-water mark is reset to the current value of
   2498 ** [sqlite3_memory_used()] if and only if the parameter to
   2499 ** [sqlite3_memory_highwater()] is true.  ^The value returned
   2500 ** by [sqlite3_memory_highwater(1)] is the high-water mark
   2501 ** prior to the reset.
   2502 */
   2503 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
   2504 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
   2505 
   2506 /*
   2507 ** CAPI3REF: Pseudo-Random Number Generator
   2508 **
   2509 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
   2510 ** select random [ROWID | ROWIDs] when inserting new records into a table that
   2511 ** already uses the largest possible [ROWID].  The PRNG is also used for
   2512 ** the build-in random() and randomblob() SQL functions.  This interface allows
   2513 ** applications to access the same PRNG for other purposes.
   2514 **
   2515 ** ^A call to this routine stores N bytes of randomness into buffer P.
   2516 ** ^If N is less than one, then P can be a NULL pointer.
   2517 **
   2518 ** ^If this routine has not been previously called or if the previous
   2519 ** call had N less than one, then the PRNG is seeded using randomness
   2520 ** obtained from the xRandomness method of the default [sqlite3_vfs] object.
   2521 ** ^If the previous call to this routine had an N of 1 or more then
   2522 ** the pseudo-randomness is generated
   2523 ** internally and without recourse to the [sqlite3_vfs] xRandomness
   2524 ** method.
   2525 */
   2526 SQLITE_API void sqlite3_randomness(int N, void *P);
   2527 
   2528 /*
   2529 ** CAPI3REF: Compile-Time Authorization Callbacks
   2530 **
   2531 ** ^This routine registers an authorizer callback with a particular
   2532 ** [database connection], supplied in the first argument.
   2533 ** ^The authorizer callback is invoked as SQL statements are being compiled
   2534 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
   2535 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
   2536 ** points during the compilation process, as logic is being created
   2537 ** to perform various actions, the authorizer callback is invoked to
   2538 ** see if those actions are allowed.  ^The authorizer callback should
   2539 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
   2540 ** specific action but allow the SQL statement to continue to be
   2541 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
   2542 ** rejected with an error.  ^If the authorizer callback returns
   2543 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
   2544 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
   2545 ** the authorizer will fail with an error message.
   2546 **
   2547 ** When the callback returns [SQLITE_OK], that means the operation
   2548 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
   2549 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
   2550 ** authorizer will fail with an error message explaining that
   2551 ** access is denied.
   2552 **
   2553 ** ^The first parameter to the authorizer callback is a copy of the third
   2554 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
   2555 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
   2556 ** the particular action to be authorized. ^The third through sixth parameters
   2557 ** to the callback are zero-terminated strings that contain additional
   2558 ** details about the action to be authorized.
   2559 **
   2560 ** ^If the action code is [SQLITE_READ]
   2561 ** and the callback returns [SQLITE_IGNORE] then the
   2562 ** [prepared statement] statement is constructed to substitute
   2563 ** a NULL value in place of the table column that would have
   2564 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
   2565 ** return can be used to deny an untrusted user access to individual
   2566 ** columns of a table.
   2567 ** ^If the action code is [SQLITE_DELETE] and the callback returns
   2568 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
   2569 ** [truncate optimization] is disabled and all rows are deleted individually.
   2570 **
   2571 ** An authorizer is used when [sqlite3_prepare | preparing]
   2572 ** SQL statements from an untrusted source, to ensure that the SQL statements
   2573 ** do not try to access data they are not allowed to see, or that they do not
   2574 ** try to execute malicious statements that damage the database.  For
   2575 ** example, an application may allow a user to enter arbitrary
   2576 ** SQL queries for evaluation by a database.  But the application does
   2577 ** not want the user to be able to make arbitrary changes to the
   2578 ** database.  An authorizer could then be put in place while the
   2579 ** user-entered SQL is being [sqlite3_prepare | prepared] that
   2580 ** disallows everything except [SELECT] statements.
   2581 **
   2582 ** Applications that need to process SQL from untrusted sources
   2583 ** might also consider lowering resource limits using [sqlite3_limit()]
   2584 ** and limiting database size using the [max_page_count] [PRAGMA]
   2585 ** in addition to using an authorizer.
   2586 **
   2587 ** ^(Only a single authorizer can be in place on a database connection
   2588 ** at a time.  Each call to sqlite3_set_authorizer overrides the
   2589 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
   2590 ** The authorizer is disabled by default.
   2591 **
   2592 ** The authorizer callback must not do anything that will modify
   2593 ** the database connection that invoked the authorizer callback.
   2594 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2595 ** database connections for the meaning of "modify" in this paragraph.
   2596 **
   2597 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
   2598 ** statement might be re-prepared during [sqlite3_step()] due to a
   2599 ** schema change.  Hence, the application should ensure that the
   2600 ** correct authorizer callback remains in place during the [sqlite3_step()].
   2601 **
   2602 ** ^Note that the authorizer callback is invoked only during
   2603 ** [sqlite3_prepare()] or its variants.  Authorization is not
   2604 ** performed during statement evaluation in [sqlite3_step()], unless
   2605 ** as stated in the previous paragraph, sqlite3_step() invokes
   2606 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
   2607 */
   2608 SQLITE_API int sqlite3_set_authorizer(
   2609   sqlite3*,
   2610   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   2611   void *pUserData
   2612 );
   2613 
   2614 /*
   2615 ** CAPI3REF: Authorizer Return Codes
   2616 **
   2617 ** The [sqlite3_set_authorizer | authorizer callback function] must
   2618 ** return either [SQLITE_OK] or one of these two constants in order
   2619 ** to signal SQLite whether or not the action is permitted.  See the
   2620 ** [sqlite3_set_authorizer | authorizer documentation] for additional
   2621 ** information.
   2622 **
   2623 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
   2624 ** returned from the [sqlite3_vtab_on_conflict()] interface.
   2625 */
   2626 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
   2627 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
   2628 
   2629 /*
   2630 ** CAPI3REF: Authorizer Action Codes
   2631 **
   2632 ** The [sqlite3_set_authorizer()] interface registers a callback function
   2633 ** that is invoked to authorize certain SQL statement actions.  The
   2634 ** second parameter to the callback is an integer code that specifies
   2635 ** what action is being authorized.  These are the integer action codes that
   2636 ** the authorizer callback may be passed.
   2637 **
   2638 ** These action code values signify what kind of operation is to be
   2639 ** authorized.  The 3rd and 4th parameters to the authorization
   2640 ** callback function will be parameters or NULL depending on which of these
   2641 ** codes is used as the second parameter.  ^(The 5th parameter to the
   2642 ** authorizer callback is the name of the database ("main", "temp",
   2643 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
   2644 ** is the name of the inner-most trigger or view that is responsible for
   2645 ** the access attempt or NULL if this access attempt is directly from
   2646 ** top-level SQL code.
   2647 */
   2648 /******************************************* 3rd ************ 4th ***********/
   2649 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
   2650 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
   2651 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
   2652 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
   2653 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
   2654 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
   2655 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
   2656 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
   2657 #define SQLITE_DELETE                9   /* Table Name      NULL            */
   2658 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
   2659 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
   2660 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
   2661 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
   2662 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
   2663 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
   2664 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
   2665 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
   2666 #define SQLITE_INSERT               18   /* Table Name      NULL            */
   2667 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
   2668 #define SQLITE_READ                 20   /* Table Name      Column Name     */
   2669 #define SQLITE_SELECT               21   /* NULL            NULL            */
   2670 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
   2671 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
   2672 #define SQLITE_ATTACH               24   /* Filename        NULL            */
   2673 #define SQLITE_DETACH               25   /* Database Name   NULL            */
   2674 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
   2675 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
   2676 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
   2677 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
   2678 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
   2679 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
   2680 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
   2681 #define SQLITE_COPY                  0   /* No longer used */
   2682 #define SQLITE_RECURSIVE            33   /* NULL            NULL            */
   2683 
   2684 /*
   2685 ** CAPI3REF: Tracing And Profiling Functions
   2686 **
   2687 ** These routines register callback functions that can be used for
   2688 ** tracing and profiling the execution of SQL statements.
   2689 **
   2690 ** ^The callback function registered by sqlite3_trace() is invoked at
   2691 ** various times when an SQL statement is being run by [sqlite3_step()].
   2692 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
   2693 ** SQL statement text as the statement first begins executing.
   2694 ** ^(Additional sqlite3_trace() callbacks might occur
   2695 ** as each triggered subprogram is entered.  The callbacks for triggers
   2696 ** contain a UTF-8 SQL comment that identifies the trigger.)^
   2697 **
   2698 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
   2699 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
   2700 **
   2701 ** ^The callback function registered by sqlite3_profile() is invoked
   2702 ** as each SQL statement finishes.  ^The profile callback contains
   2703 ** the original statement text and an estimate of wall-clock time
   2704 ** of how long that statement took to run.  ^The profile callback
   2705 ** time is in units of nanoseconds, however the current implementation
   2706 ** is only capable of millisecond resolution so the six least significant
   2707 ** digits in the time are meaningless.  Future versions of SQLite
   2708 ** might provide greater resolution on the profiler callback.  The
   2709 ** sqlite3_profile() function is considered experimental and is
   2710 ** subject to change in future versions of SQLite.
   2711 */
   2712 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
   2713 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
   2714    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
   2715 
   2716 /*
   2717 ** CAPI3REF: Query Progress Callbacks
   2718 **
   2719 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
   2720 ** function X to be invoked periodically during long running calls to
   2721 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
   2722 ** database connection D.  An example use for this
   2723 ** interface is to keep a GUI updated during a large query.
   2724 **
   2725 ** ^The parameter P is passed through as the only parameter to the
   2726 ** callback function X.  ^The parameter N is the approximate number of
   2727 ** [virtual machine instructions] that are evaluated between successive
   2728 ** invocations of the callback X.  ^If N is less than one then the progress
   2729 ** handler is disabled.
   2730 **
   2731 ** ^Only a single progress handler may be defined at one time per
   2732 ** [database connection]; setting a new progress handler cancels the
   2733 ** old one.  ^Setting parameter X to NULL disables the progress handler.
   2734 ** ^The progress handler is also disabled by setting N to a value less
   2735 ** than 1.
   2736 **
   2737 ** ^If the progress callback returns non-zero, the operation is
   2738 ** interrupted.  This feature can be used to implement a
   2739 ** "Cancel" button on a GUI progress dialog box.
   2740 **
   2741 ** The progress handler callback must not do anything that will modify
   2742 ** the database connection that invoked the progress handler.
   2743 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2744 ** database connections for the meaning of "modify" in this paragraph.
   2745 **
   2746 */
   2747 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
   2748 
   2749 /*
   2750 ** CAPI3REF: Opening A New Database Connection
   2751 **
   2752 ** ^These routines open an SQLite database file as specified by the
   2753 ** filename argument. ^The filename argument is interpreted as UTF-8 for
   2754 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
   2755 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
   2756 ** returned in *ppDb, even if an error occurs.  The only exception is that
   2757 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
   2758 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
   2759 ** object.)^ ^(If the database is opened (and/or created) successfully, then
   2760 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
   2761 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
   2762 ** an English language description of the error following a failure of any
   2763 ** of the sqlite3_open() routines.
   2764 **
   2765 ** ^The default encoding for the database will be UTF-8 if
   2766 ** sqlite3_open() or sqlite3_open_v2() is called and
   2767 ** UTF-16 in the native byte order if sqlite3_open16() is used.
   2768 **
   2769 ** Whether or not an error occurs when it is opened, resources
   2770 ** associated with the [database connection] handle should be released by
   2771 ** passing it to [sqlite3_close()] when it is no longer required.
   2772 **
   2773 ** The sqlite3_open_v2() interface works like sqlite3_open()
   2774 ** except that it accepts two additional parameters for additional control
   2775 ** over the new database connection.  ^(The flags parameter to
   2776 ** sqlite3_open_v2() can take one of
   2777 ** the following three values, optionally combined with the
   2778 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
   2779 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
   2780 **
   2781 ** <dl>
   2782 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
   2783 ** <dd>The database is opened in read-only mode.  If the database does not
   2784 ** already exist, an error is returned.</dd>)^
   2785 **
   2786 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
   2787 ** <dd>The database is opened for reading and writing if possible, or reading
   2788 ** only if the file is write protected by the operating system.  In either
   2789 ** case the database must already exist, otherwise an error is returned.</dd>)^
   2790 **
   2791 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
   2792 ** <dd>The database is opened for reading and writing, and is created if
   2793 ** it does not already exist. This is the behavior that is always used for
   2794 ** sqlite3_open() and sqlite3_open16().</dd>)^
   2795 ** </dl>
   2796 **
   2797 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
   2798 ** combinations shown above optionally combined with other
   2799 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
   2800 ** then the behavior is undefined.
   2801 **
   2802 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
   2803 ** opens in the multi-thread [threading mode] as long as the single-thread
   2804 ** mode has not been set at compile-time or start-time.  ^If the
   2805 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
   2806 ** in the serialized [threading mode] unless single-thread was
   2807 ** previously selected at compile-time or start-time.
   2808 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
   2809 ** eligible to use [shared cache mode], regardless of whether or not shared
   2810 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
   2811 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
   2812 ** participate in [shared cache mode] even if it is enabled.
   2813 **
   2814 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
   2815 ** [sqlite3_vfs] object that defines the operating system interface that
   2816 ** the new database connection should use.  ^If the fourth parameter is
   2817 ** a NULL pointer then the default [sqlite3_vfs] object is used.
   2818 **
   2819 ** ^If the filename is ":memory:", then a private, temporary in-memory database
   2820 ** is created for the connection.  ^This in-memory database will vanish when
   2821 ** the database connection is closed.  Future versions of SQLite might
   2822 ** make use of additional special filenames that begin with the ":" character.
   2823 ** It is recommended that when a database filename actually does begin with
   2824 ** a ":" character you should prefix the filename with a pathname such as
   2825 ** "./" to avoid ambiguity.
   2826 **
   2827 ** ^If the filename is an empty string, then a private, temporary
   2828 ** on-disk database will be created.  ^This private database will be
   2829 ** automatically deleted as soon as the database connection is closed.
   2830 **
   2831 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
   2832 **
   2833 ** ^If [URI filename] interpretation is enabled, and the filename argument
   2834 ** begins with "file:", then the filename is interpreted as a URI. ^URI
   2835 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
   2836 ** set in the fourth argument to sqlite3_open_v2(), or if it has
   2837 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
   2838 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
   2839 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
   2840 ** by default, but future releases of SQLite might enable URI filename
   2841 ** interpretation by default.  See "[URI filenames]" for additional
   2842 ** information.
   2843 **
   2844 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
   2845 ** authority, then it must be either an empty string or the string
   2846 ** "localhost". ^If the authority is not an empty string or "localhost", an
   2847 ** error is returned to the caller. ^The fragment component of a URI, if
   2848 ** present, is ignored.
   2849 **
   2850 ** ^SQLite uses the path component of the URI as the name of the disk file
   2851 ** which contains the database. ^If the path begins with a '/' character,
   2852 ** then it is interpreted as an absolute path. ^If the path does not begin
   2853 ** with a '/' (meaning that the authority section is omitted from the URI)
   2854 ** then the path is interpreted as a relative path.
   2855 ** ^On windows, the first component of an absolute path
   2856 ** is a drive specification (e.g. "C:").
   2857 **
   2858 ** [[core URI query parameters]]
   2859 ** The query component of a URI may contain parameters that are interpreted
   2860 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
   2861 ** SQLite interprets the following three query parameters:
   2862 **
   2863 ** <ul>
   2864 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
   2865 **     a VFS object that provides the operating system interface that should
   2866 **     be used to access the database file on disk. ^If this option is set to
   2867 **     an empty string the default VFS object is used. ^Specifying an unknown
   2868 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
   2869 **     present, then the VFS specified by the option takes precedence over
   2870 **     the value passed as the fourth parameter to sqlite3_open_v2().
   2871 **
   2872 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
   2873 **     "rwc", or "memory". Attempting to set it to any other value is
   2874 **     an error)^.
   2875 **     ^If "ro" is specified, then the database is opened for read-only
   2876 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
   2877 **     third argument to sqlite3_open_v2(). ^If the mode option is set to
   2878 **     "rw", then the database is opened for read-write (but not create)
   2879 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
   2880 **     been set. ^Value "rwc" is equivalent to setting both
   2881 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
   2882 **     set to "memory" then a pure [in-memory database] that never reads
   2883 **     or writes from disk is used. ^It is an error to specify a value for
   2884 **     the mode parameter that is less restrictive than that specified by
   2885 **     the flags passed in the third parameter to sqlite3_open_v2().
   2886 **
   2887 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
   2888 **     "private". ^Setting it to "shared" is equivalent to setting the
   2889 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
   2890 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
   2891 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
   2892 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
   2893 **     a URI filename, its value overrides any behavior requested by setting
   2894 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
   2895 **
   2896 **  <li> <b>psow</b>: ^The psow parameter may be "true" (or "on" or "yes" or
   2897 **     "1") or "false" (or "off" or "no" or "0") to indicate that the
   2898 **     [powersafe overwrite] property does or does not apply to the
   2899 **     storage media on which the database file resides.  ^The psow query
   2900 **     parameter only works for the built-in unix and Windows VFSes.
   2901 **
   2902 **  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
   2903 **     which if set disables file locking in rollback journal modes.  This
   2904 **     is useful for accessing a database on a filesystem that does not
   2905 **     support locking.  Caution:  Database corruption might result if two
   2906 **     or more processes write to the same database and any one of those
   2907 **     processes uses nolock=1.
   2908 **
   2909 **  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
   2910 **     parameter that indicates that the database file is stored on
   2911 **     read-only media.  ^When immutable is set, SQLite assumes that the
   2912 **     database file cannot be changed, even by a process with higher
   2913 **     privilege, and so the database is opened read-only and all locking
   2914 **     and change detection is disabled.  Caution: Setting the immutable
   2915 **     property on a database file that does in fact change can result
   2916 **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
   2917 **     See also: [SQLITE_IOCAP_IMMUTABLE].
   2918 **
   2919 ** </ul>
   2920 **
   2921 ** ^Specifying an unknown parameter in the query component of a URI is not an
   2922 ** error.  Future versions of SQLite might understand additional query
   2923 ** parameters.  See "[query parameters with special meaning to SQLite]" for
   2924 ** additional information.
   2925 **
   2926 ** [[URI filename examples]] <h3>URI filename examples</h3>
   2927 **
   2928 ** <table border="1" align=center cellpadding=5>
   2929 ** <tr><th> URI filenames <th> Results
   2930 ** <tr><td> file:data.db <td>
   2931 **          Open the file "data.db" in the current directory.
   2932 ** <tr><td> file:/home/fred/data.db<br>
   2933 **          file:///home/fred/data.db <br>
   2934 **          file://localhost/home/fred/data.db <br> <td>
   2935 **          Open the database file "/home/fred/data.db".
   2936 ** <tr><td> file://darkstar/home/fred/data.db <td>
   2937 **          An error. "darkstar" is not a recognized authority.
   2938 ** <tr><td style="white-space:nowrap">
   2939 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
   2940 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
   2941 **          C:. Note that the %20 escaping in this example is not strictly
   2942 **          necessary - space characters can be used literally
   2943 **          in URI filenames.
   2944 ** <tr><td> file:data.db?mode=ro&cache=private <td>
   2945 **          Open file "data.db" in the current directory for read-only access.
   2946 **          Regardless of whether or not shared-cache mode is enabled by
   2947 **          default, use a private cache.
   2948 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
   2949 **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
   2950 **          that uses dot-files in place of posix advisory locking.
   2951 ** <tr><td> file:data.db?mode=readonly <td>
   2952 **          An error. "readonly" is not a valid option for the "mode" parameter.
   2953 ** </table>
   2954 **
   2955 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
   2956 ** query components of a URI. A hexadecimal escape sequence consists of a
   2957 ** percent sign - "%" - followed by exactly two hexadecimal digits
   2958 ** specifying an octet value. ^Before the path or query components of a
   2959 ** URI filename are interpreted, they are encoded using UTF-8 and all
   2960 ** hexadecimal escape sequences replaced by a single byte containing the
   2961 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
   2962 ** the results are undefined.
   2963 **
   2964 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
   2965 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
   2966 ** codepage is currently defined.  Filenames containing international
   2967 ** characters must be converted to UTF-8 prior to passing them into
   2968 ** sqlite3_open() or sqlite3_open_v2().
   2969 **
   2970 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
   2971 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
   2972 ** features that require the use of temporary files may fail.
   2973 **
   2974 ** See also: [sqlite3_temp_directory]
   2975 */
   2976 SQLITE_API int sqlite3_open(
   2977   const char *filename,   /* Database filename (UTF-8) */
   2978   sqlite3 **ppDb          /* OUT: SQLite db handle */
   2979 );
   2980 SQLITE_API int sqlite3_open16(
   2981   const void *filename,   /* Database filename (UTF-16) */
   2982   sqlite3 **ppDb          /* OUT: SQLite db handle */
   2983 );
   2984 SQLITE_API int sqlite3_open_v2(
   2985   const char *filename,   /* Database filename (UTF-8) */
   2986   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   2987   int flags,              /* Flags */
   2988   const char *zVfs        /* Name of VFS module to use */
   2989 );
   2990 
   2991 /*
   2992 ** CAPI3REF: Obtain Values For URI Parameters
   2993 **
   2994 ** These are utility routines, useful to VFS implementations, that check
   2995 ** to see if a database file was a URI that contained a specific query
   2996 ** parameter, and if so obtains the value of that query parameter.
   2997 **
   2998 ** If F is the database filename pointer passed into the xOpen() method of
   2999 ** a VFS implementation when the flags parameter to xOpen() has one or
   3000 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
   3001 ** P is the name of the query parameter, then
   3002 ** sqlite3_uri_parameter(F,P) returns the value of the P
   3003 ** parameter if it exists or a NULL pointer if P does not appear as a
   3004 ** query parameter on F.  If P is a query parameter of F
   3005 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
   3006 ** a pointer to an empty string.
   3007 **
   3008 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
   3009 ** parameter and returns true (1) or false (0) according to the value
   3010 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
   3011 ** value of query parameter P is one of "yes", "true", or "on" in any
   3012 ** case or if the value begins with a non-zero number.  The
   3013 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
   3014 ** query parameter P is one of "no", "false", or "off" in any case or
   3015 ** if the value begins with a numeric zero.  If P is not a query
   3016 ** parameter on F or if the value of P is does not match any of the
   3017 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
   3018 **
   3019 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
   3020 ** 64-bit signed integer and returns that integer, or D if P does not
   3021 ** exist.  If the value of P is something other than an integer, then
   3022 ** zero is returned.
   3023 **
   3024 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
   3025 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
   3026 ** is not a database file pathname pointer that SQLite passed into the xOpen
   3027 ** VFS method, then the behavior of this routine is undefined and probably
   3028 ** undesirable.
   3029 */
   3030 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
   3031 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
   3032 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
   3033 
   3034 
   3035 /*
   3036 ** CAPI3REF: Error Codes And Messages
   3037 **
   3038 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
   3039 ** [extended result code] for the most recent failed sqlite3_* API call
   3040 ** associated with a [database connection]. If a prior API call failed
   3041 ** but the most recent API call succeeded, the return value from
   3042 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
   3043 ** interface is the same except that it always returns the
   3044 ** [extended result code] even when extended result codes are
   3045 ** disabled.
   3046 **
   3047 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
   3048 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
   3049 ** ^(Memory to hold the error message string is managed internally.
   3050 ** The application does not need to worry about freeing the result.
   3051 ** However, the error string might be overwritten or deallocated by
   3052 ** subsequent calls to other SQLite interface functions.)^
   3053 **
   3054 ** ^The sqlite3_errstr() interface returns the English-language text
   3055 ** that describes the [result code], as UTF-8.
   3056 ** ^(Memory to hold the error message string is managed internally
   3057 ** and must not be freed by the application)^.
   3058 **
   3059 ** When the serialized [threading mode] is in use, it might be the
   3060 ** case that a second error occurs on a separate thread in between
   3061 ** the time of the first error and the call to these interfaces.
   3062 ** When that happens, the second error will be reported since these
   3063 ** interfaces always report the most recent result.  To avoid
   3064 ** this, each thread can obtain exclusive use of the [database connection] D
   3065 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
   3066 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
   3067 ** all calls to the interfaces listed here are completed.
   3068 **
   3069 ** If an interface fails with SQLITE_MISUSE, that means the interface
   3070 ** was invoked incorrectly by the application.  In that case, the
   3071 ** error code and message may or may not be set.
   3072 */
   3073 SQLITE_API int sqlite3_errcode(sqlite3 *db);
   3074 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
   3075 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
   3076 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
   3077 SQLITE_API const char *sqlite3_errstr(int);
   3078 
   3079 /*
   3080 ** CAPI3REF: SQL Statement Object
   3081 ** KEYWORDS: {prepared statement} {prepared statements}
   3082 **
   3083 ** An instance of this object represents a single SQL statement.
   3084 ** This object is variously known as a "prepared statement" or a
   3085 ** "compiled SQL statement" or simply as a "statement".
   3086 **
   3087 ** The life of a statement object goes something like this:
   3088 **
   3089 ** <ol>
   3090 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
   3091 **      function.
   3092 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
   3093 **      interfaces.
   3094 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
   3095 ** <li> Reset the statement using [sqlite3_reset()] then go back
   3096 **      to step 2.  Do this zero or more times.
   3097 ** <li> Destroy the object using [sqlite3_finalize()].
   3098 ** </ol>
   3099 **
   3100 ** Refer to documentation on individual methods above for additional
   3101 ** information.
   3102 */
   3103 typedef struct sqlite3_stmt sqlite3_stmt;
   3104 
   3105 /*
   3106 ** CAPI3REF: Run-time Limits
   3107 **
   3108 ** ^(This interface allows the size of various constructs to be limited
   3109 ** on a connection by connection basis.  The first parameter is the
   3110 ** [database connection] whose limit is to be set or queried.  The
   3111 ** second parameter is one of the [limit categories] that define a
   3112 ** class of constructs to be size limited.  The third parameter is the
   3113 ** new limit for that construct.)^
   3114 **
   3115 ** ^If the new limit is a negative number, the limit is unchanged.
   3116 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
   3117 ** [limits | hard upper bound]
   3118 ** set at compile-time by a C preprocessor macro called
   3119 ** [limits | SQLITE_MAX_<i>NAME</i>].
   3120 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
   3121 ** ^Attempts to increase a limit above its hard upper bound are
   3122 ** silently truncated to the hard upper bound.
   3123 **
   3124 ** ^Regardless of whether or not the limit was changed, the
   3125 ** [sqlite3_limit()] interface returns the prior value of the limit.
   3126 ** ^Hence, to find the current value of a limit without changing it,
   3127 ** simply invoke this interface with the third parameter set to -1.
   3128 **
   3129 ** Run-time limits are intended for use in applications that manage
   3130 ** both their own internal database and also databases that are controlled
   3131 ** by untrusted external sources.  An example application might be a
   3132 ** web browser that has its own databases for storing history and
   3133 ** separate databases controlled by JavaScript applications downloaded
   3134 ** off the Internet.  The internal databases can be given the
   3135 ** large, default limits.  Databases managed by external sources can
   3136 ** be given much smaller limits designed to prevent a denial of service
   3137 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
   3138 ** interface to further control untrusted SQL.  The size of the database
   3139 ** created by an untrusted script can be contained using the
   3140 ** [max_page_count] [PRAGMA].
   3141 **
   3142 ** New run-time limit categories may be added in future releases.
   3143 */
   3144 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
   3145 
   3146 /*
   3147 ** CAPI3REF: Run-Time Limit Categories
   3148 ** KEYWORDS: {limit category} {*limit categories}
   3149 **
   3150 ** These constants define various performance limits
   3151 ** that can be lowered at run-time using [sqlite3_limit()].
   3152 ** The synopsis of the meanings of the various limits is shown below.
   3153 ** Additional information is available at [limits | Limits in SQLite].
   3154 **
   3155 ** <dl>
   3156 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
   3157 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
   3158 **
   3159 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
   3160 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
   3161 **
   3162 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
   3163 ** <dd>The maximum number of columns in a table definition or in the
   3164 ** result set of a [SELECT] or the maximum number of columns in an index
   3165 ** or in an ORDER BY or GROUP BY clause.</dd>)^
   3166 **
   3167 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
   3168 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
   3169 **
   3170 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
   3171 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
   3172 **
   3173 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
   3174 ** <dd>The maximum number of instructions in a virtual machine program
   3175 ** used to implement an SQL statement.  This limit is not currently
   3176 ** enforced, though that might be added in some future release of
   3177 ** SQLite.</dd>)^
   3178 **
   3179 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
   3180 ** <dd>The maximum number of arguments on a function.</dd>)^
   3181 **
   3182 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
   3183 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
   3184 **
   3185 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
   3186 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
   3187 ** <dd>The maximum length of the pattern argument to the [LIKE] or
   3188 ** [GLOB] operators.</dd>)^
   3189 **
   3190 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
   3191 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
   3192 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
   3193 **
   3194 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
   3195 ** <dd>The maximum depth of recursion for triggers.</dd>)^
   3196 ** </dl>
   3197 */
   3198 #define SQLITE_LIMIT_LENGTH                    0
   3199 #define SQLITE_LIMIT_SQL_LENGTH                1
   3200 #define SQLITE_LIMIT_COLUMN                    2
   3201 #define SQLITE_LIMIT_EXPR_DEPTH                3
   3202 #define SQLITE_LIMIT_COMPOUND_SELECT           4
   3203 #define SQLITE_LIMIT_VDBE_OP                   5
   3204 #define SQLITE_LIMIT_FUNCTION_ARG              6
   3205 #define SQLITE_LIMIT_ATTACHED                  7
   3206 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
   3207 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
   3208 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
   3209 
   3210 /*
   3211 ** CAPI3REF: Compiling An SQL Statement
   3212 ** KEYWORDS: {SQL statement compiler}
   3213 **
   3214 ** To execute an SQL query, it must first be compiled into a byte-code
   3215 ** program using one of these routines.
   3216 **
   3217 ** The first argument, "db", is a [database connection] obtained from a
   3218 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
   3219 ** [sqlite3_open16()].  The database connection must not have been closed.
   3220 **
   3221 ** The second argument, "zSql", is the statement to be compiled, encoded
   3222 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
   3223 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
   3224 ** use UTF-16.
   3225 **
   3226 ** ^If the nByte argument is less than zero, then zSql is read up to the
   3227 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
   3228 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
   3229 ** zSql string ends at either the first '\000' or '\u0000' character or
   3230 ** the nByte-th byte, whichever comes first. If the caller knows
   3231 ** that the supplied string is nul-terminated, then there is a small
   3232 ** performance advantage to be gained by passing an nByte parameter that
   3233 ** is equal to the number of bytes in the input string <i>including</i>
   3234 ** the nul-terminator bytes as this saves SQLite from having to
   3235 ** make a copy of the input string.
   3236 **
   3237 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
   3238 ** past the end of the first SQL statement in zSql.  These routines only
   3239 ** compile the first statement in zSql, so *pzTail is left pointing to
   3240 ** what remains uncompiled.
   3241 **
   3242 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
   3243 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
   3244 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
   3245 ** string or a comment) then *ppStmt is set to NULL.
   3246 ** The calling procedure is responsible for deleting the compiled
   3247 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
   3248 ** ppStmt may not be NULL.
   3249 **
   3250 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
   3251 ** otherwise an [error code] is returned.
   3252 **
   3253 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
   3254 ** recommended for all new programs. The two older interfaces are retained
   3255 ** for backwards compatibility, but their use is discouraged.
   3256 ** ^In the "v2" interfaces, the prepared statement
   3257 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
   3258 ** original SQL text. This causes the [sqlite3_step()] interface to
   3259 ** behave differently in three ways:
   3260 **
   3261 ** <ol>
   3262 ** <li>
   3263 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
   3264 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
   3265 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
   3266 ** retries will occur before sqlite3_step() gives up and returns an error.
   3267 ** </li>
   3268 **
   3269 ** <li>
   3270 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
   3271 ** [error codes] or [extended error codes].  ^The legacy behavior was that
   3272 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
   3273 ** and the application would have to make a second call to [sqlite3_reset()]
   3274 ** in order to find the underlying cause of the problem. With the "v2" prepare
   3275 ** interfaces, the underlying reason for the error is returned immediately.
   3276 ** </li>
   3277 **
   3278 ** <li>
   3279 ** ^If the specific value bound to [parameter | host parameter] in the
   3280 ** WHERE clause might influence the choice of query plan for a statement,
   3281 ** then the statement will be automatically recompiled, as if there had been
   3282 ** a schema change, on the first  [sqlite3_step()] call following any change
   3283 ** to the [sqlite3_bind_text | bindings] of that [parameter].
   3284 ** ^The specific value of WHERE-clause [parameter] might influence the
   3285 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
   3286 ** or [GLOB] operator or if the parameter is compared to an indexed column
   3287 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
   3288 ** </li>
   3289 ** </ol>
   3290 */
   3291 SQLITE_API int sqlite3_prepare(
   3292   sqlite3 *db,            /* Database handle */
   3293   const char *zSql,       /* SQL statement, UTF-8 encoded */
   3294   int nByte,              /* Maximum length of zSql in bytes. */
   3295   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3296   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   3297 );
   3298 SQLITE_API int sqlite3_prepare_v2(
   3299   sqlite3 *db,            /* Database handle */
   3300   const char *zSql,       /* SQL statement, UTF-8 encoded */
   3301   int nByte,              /* Maximum length of zSql in bytes. */
   3302   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3303   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   3304 );
   3305 SQLITE_API int sqlite3_prepare16(
   3306   sqlite3 *db,            /* Database handle */
   3307   const void *zSql,       /* SQL statement, UTF-16 encoded */
   3308   int nByte,              /* Maximum length of zSql in bytes. */
   3309   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3310   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   3311 );
   3312 SQLITE_API int sqlite3_prepare16_v2(
   3313   sqlite3 *db,            /* Database handle */
   3314   const void *zSql,       /* SQL statement, UTF-16 encoded */
   3315   int nByte,              /* Maximum length of zSql in bytes. */
   3316   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3317   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   3318 );
   3319 
   3320 /*
   3321 ** CAPI3REF: Retrieving Statement SQL
   3322 **
   3323 ** ^This interface can be used to retrieve a saved copy of the original
   3324 ** SQL text used to create a [prepared statement] if that statement was
   3325 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
   3326 */
   3327 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
   3328 
   3329 /*
   3330 ** CAPI3REF: Determine If An SQL Statement Writes The Database
   3331 **
   3332 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
   3333 ** and only if the [prepared statement] X makes no direct changes to
   3334 ** the content of the database file.
   3335 **
   3336 ** Note that [application-defined SQL functions] or
   3337 ** [virtual tables] might change the database indirectly as a side effect.
   3338 ** ^(For example, if an application defines a function "eval()" that
   3339 ** calls [sqlite3_exec()], then the following SQL statement would
   3340 ** change the database file through side-effects:
   3341 **
   3342 ** <blockquote><pre>
   3343 **    SELECT eval('DELETE FROM t1') FROM t2;
   3344 ** </pre></blockquote>
   3345 **
   3346 ** But because the [SELECT] statement does not change the database file
   3347 ** directly, sqlite3_stmt_readonly() would still return true.)^
   3348 **
   3349 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
   3350 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
   3351 ** since the statements themselves do not actually modify the database but
   3352 ** rather they control the timing of when other statements modify the
   3353 ** database.  ^The [ATTACH] and [DETACH] statements also cause
   3354 ** sqlite3_stmt_readonly() to return true since, while those statements
   3355 ** change the configuration of a database connection, they do not make
   3356 ** changes to the content of the database files on disk.
   3357 */
   3358 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
   3359 
   3360 /*
   3361 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
   3362 **
   3363 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
   3364 ** [prepared statement] S has been stepped at least once using
   3365 ** [sqlite3_step(S)] but has not run to completion and/or has not
   3366 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
   3367 ** interface returns false if S is a NULL pointer.  If S is not a
   3368 ** NULL pointer and is not a pointer to a valid [prepared statement]
   3369 ** object, then the behavior is undefined and probably undesirable.
   3370 **
   3371 ** This interface can be used in combination [sqlite3_next_stmt()]
   3372 ** to locate all prepared statements associated with a database
   3373 ** connection that are in need of being reset.  This can be used,
   3374 ** for example, in diagnostic routines to search for prepared
   3375 ** statements that are holding a transaction open.
   3376 */
   3377 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
   3378 
   3379 /*
   3380 ** CAPI3REF: Dynamically Typed Value Object
   3381 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
   3382 **
   3383 ** SQLite uses the sqlite3_value object to represent all values
   3384 ** that can be stored in a database table. SQLite uses dynamic typing
   3385 ** for the values it stores.  ^Values stored in sqlite3_value objects
   3386 ** can be integers, floating point values, strings, BLOBs, or NULL.
   3387 **
   3388 ** An sqlite3_value object may be either "protected" or "unprotected".
   3389 ** Some interfaces require a protected sqlite3_value.  Other interfaces
   3390 ** will accept either a protected or an unprotected sqlite3_value.
   3391 ** Every interface that accepts sqlite3_value arguments specifies
   3392 ** whether or not it requires a protected sqlite3_value.
   3393 **
   3394 ** The terms "protected" and "unprotected" refer to whether or not
   3395 ** a mutex is held.  An internal mutex is held for a protected
   3396 ** sqlite3_value object but no mutex is held for an unprotected
   3397 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
   3398 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
   3399 ** or if SQLite is run in one of reduced mutex modes
   3400 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
   3401 ** then there is no distinction between protected and unprotected
   3402 ** sqlite3_value objects and they can be used interchangeably.  However,
   3403 ** for maximum code portability it is recommended that applications
   3404 ** still make the distinction between protected and unprotected
   3405 ** sqlite3_value objects even when not strictly required.
   3406 **
   3407 ** ^The sqlite3_value objects that are passed as parameters into the
   3408 ** implementation of [application-defined SQL functions] are protected.
   3409 ** ^The sqlite3_value object returned by
   3410 ** [sqlite3_column_value()] is unprotected.
   3411 ** Unprotected sqlite3_value objects may only be used with
   3412 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
   3413 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
   3414 ** interfaces require protected sqlite3_value objects.
   3415 */
   3416 typedef struct Mem sqlite3_value;
   3417 
   3418 /*
   3419 ** CAPI3REF: SQL Function Context Object
   3420 **
   3421 ** The context in which an SQL function executes is stored in an
   3422 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
   3423 ** is always first parameter to [application-defined SQL functions].
   3424 ** The application-defined SQL function implementation will pass this
   3425 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
   3426 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
   3427 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
   3428 ** and/or [sqlite3_set_auxdata()].
   3429 */
   3430 typedef struct sqlite3_context sqlite3_context;
   3431 
   3432 /*
   3433 ** CAPI3REF: Binding Values To Prepared Statements
   3434 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
   3435 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
   3436 **
   3437 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
   3438 ** literals may be replaced by a [parameter] that matches one of following
   3439 ** templates:
   3440 **
   3441 ** <ul>
   3442 ** <li>  ?
   3443 ** <li>  ?NNN
   3444 ** <li>  :VVV
   3445 ** <li>  @VVV
   3446 ** <li>  $VVV
   3447 ** </ul>
   3448 **
   3449 ** In the templates above, NNN represents an integer literal,
   3450 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
   3451 ** parameters (also called "host parameter names" or "SQL parameters")
   3452 ** can be set using the sqlite3_bind_*() routines defined here.
   3453 **
   3454 ** ^The first argument to the sqlite3_bind_*() routines is always
   3455 ** a pointer to the [sqlite3_stmt] object returned from
   3456 ** [sqlite3_prepare_v2()] or its variants.
   3457 **
   3458 ** ^The second argument is the index of the SQL parameter to be set.
   3459 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
   3460 ** SQL parameter is used more than once, second and subsequent
   3461 ** occurrences have the same index as the first occurrence.
   3462 ** ^The index for named parameters can be looked up using the
   3463 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
   3464 ** for "?NNN" parameters is the value of NNN.
   3465 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
   3466 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
   3467 **
   3468 ** ^The third argument is the value to bind to the parameter.
   3469 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
   3470 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
   3471 ** is ignored and the end result is the same as sqlite3_bind_null().
   3472 **
   3473 ** ^(In those routines that have a fourth argument, its value is the
   3474 ** number of bytes in the parameter.  To be clear: the value is the
   3475 ** number of <u>bytes</u> in the value, not the number of characters.)^
   3476 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
   3477 ** is negative, then the length of the string is
   3478 ** the number of bytes up to the first zero terminator.
   3479 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
   3480 ** the behavior is undefined.
   3481 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
   3482 ** or sqlite3_bind_text16() then that parameter must be the byte offset
   3483 ** where the NUL terminator would occur assuming the string were NUL
   3484 ** terminated.  If any NUL characters occur at byte offsets less than
   3485 ** the value of the fourth parameter then the resulting string value will
   3486 ** contain embedded NULs.  The result of expressions involving strings
   3487 ** with embedded NULs is undefined.
   3488 **
   3489 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
   3490 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
   3491 ** string after SQLite has finished with it.  ^The destructor is called
   3492 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
   3493 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
   3494 ** ^If the fifth argument is
   3495 ** the special value [SQLITE_STATIC], then SQLite assumes that the
   3496 ** information is in static, unmanaged space and does not need to be freed.
   3497 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
   3498 ** SQLite makes its own private copy of the data immediately, before
   3499 ** the sqlite3_bind_*() routine returns.
   3500 **
   3501 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
   3502 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
   3503 ** (just an integer to hold its size) while it is being processed.
   3504 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
   3505 ** content is later written using
   3506 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
   3507 ** ^A negative value for the zeroblob results in a zero-length BLOB.
   3508 **
   3509 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
   3510 ** for the [prepared statement] or with a prepared statement for which
   3511 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
   3512 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
   3513 ** routine is passed a [prepared statement] that has been finalized, the
   3514 ** result is undefined and probably harmful.
   3515 **
   3516 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
   3517 ** ^Unbound parameters are interpreted as NULL.
   3518 **
   3519 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
   3520 ** [error code] if anything goes wrong.
   3521 ** ^[SQLITE_RANGE] is returned if the parameter
   3522 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
   3523 **
   3524 ** See also: [sqlite3_bind_parameter_count()],
   3525 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
   3526 */
   3527 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
   3528 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
   3529 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
   3530 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
   3531 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
   3532 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
   3533 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
   3534 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
   3535 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
   3536 
   3537 /*
   3538 ** CAPI3REF: Number Of SQL Parameters
   3539 **
   3540 ** ^This routine can be used to find the number of [SQL parameters]
   3541 ** in a [prepared statement].  SQL parameters are tokens of the
   3542 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
   3543 ** placeholders for values that are [sqlite3_bind_blob | bound]
   3544 ** to the parameters at a later time.
   3545 **
   3546 ** ^(This routine actually returns the index of the largest (rightmost)
   3547 ** parameter. For all forms except ?NNN, this will correspond to the
   3548 ** number of unique parameters.  If parameters of the ?NNN form are used,
   3549 ** there may be gaps in the list.)^
   3550 **
   3551 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3552 ** [sqlite3_bind_parameter_name()], and
   3553 ** [sqlite3_bind_parameter_index()].
   3554 */
   3555 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
   3556 
   3557 /*
   3558 ** CAPI3REF: Name Of A Host Parameter
   3559 **
   3560 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
   3561 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
   3562 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3563 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3564 ** respectively.
   3565 ** In other words, the initial ":" or "$" or "@" or "?"
   3566 ** is included as part of the name.)^
   3567 ** ^Parameters of the form "?" without a following integer have no name
   3568 ** and are referred to as "nameless" or "anonymous parameters".
   3569 **
   3570 ** ^The first host parameter has an index of 1, not 0.
   3571 **
   3572 ** ^If the value N is out of range or if the N-th parameter is
   3573 ** nameless, then NULL is returned.  ^The returned string is
   3574 ** always in UTF-8 encoding even if the named parameter was
   3575 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
   3576 ** [sqlite3_prepare16_v2()].
   3577 **
   3578 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3579 ** [sqlite3_bind_parameter_count()], and
   3580 ** [sqlite3_bind_parameter_index()].
   3581 */
   3582 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
   3583 
   3584 /*
   3585 ** CAPI3REF: Index Of A Parameter With A Given Name
   3586 **
   3587 ** ^Return the index of an SQL parameter given its name.  ^The
   3588 ** index value returned is suitable for use as the second
   3589 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
   3590 ** is returned if no matching parameter is found.  ^The parameter
   3591 ** name must be given in UTF-8 even if the original statement
   3592 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
   3593 **
   3594 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3595 ** [sqlite3_bind_parameter_count()], and
   3596 ** [sqlite3_bind_parameter_index()].
   3597 */
   3598 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
   3599 
   3600 /*
   3601 ** CAPI3REF: Reset All Bindings On A Prepared Statement
   3602 **
   3603 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
   3604 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
   3605 ** ^Use this routine to reset all host parameters to NULL.
   3606 */
   3607 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
   3608 
   3609 /*
   3610 ** CAPI3REF: Number Of Columns In A Result Set
   3611 **
   3612 ** ^Return the number of columns in the result set returned by the
   3613 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
   3614 ** statement that does not return data (for example an [UPDATE]).
   3615 **
   3616 ** See also: [sqlite3_data_count()]
   3617 */
   3618 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
   3619 
   3620 /*
   3621 ** CAPI3REF: Column Names In A Result Set
   3622 **
   3623 ** ^These routines return the name assigned to a particular column
   3624 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
   3625 ** interface returns a pointer to a zero-terminated UTF-8 string
   3626 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
   3627 ** UTF-16 string.  ^The first parameter is the [prepared statement]
   3628 ** that implements the [SELECT] statement. ^The second parameter is the
   3629 ** column number.  ^The leftmost column is number 0.
   3630 **
   3631 ** ^The returned string pointer is valid until either the [prepared statement]
   3632 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
   3633 ** reprepared by the first call to [sqlite3_step()] for a particular run
   3634 ** or until the next call to
   3635 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
   3636 **
   3637 ** ^If sqlite3_malloc() fails during the processing of either routine
   3638 ** (for example during a conversion from UTF-8 to UTF-16) then a
   3639 ** NULL pointer is returned.
   3640 **
   3641 ** ^The name of a result column is the value of the "AS" clause for
   3642 ** that column, if there is an AS clause.  If there is no AS clause
   3643 ** then the name of the column is unspecified and may change from
   3644 ** one release of SQLite to the next.
   3645 */
   3646 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
   3647 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
   3648 
   3649 /*
   3650 ** CAPI3REF: Source Of Data In A Query Result
   3651 **
   3652 ** ^These routines provide a means to determine the database, table, and
   3653 ** table column that is the origin of a particular result column in
   3654 ** [SELECT] statement.
   3655 ** ^The name of the database or table or column can be returned as
   3656 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
   3657 ** the database name, the _table_ routines return the table name, and
   3658 ** the origin_ routines return the column name.
   3659 ** ^The returned string is valid until the [prepared statement] is destroyed
   3660 ** using [sqlite3_finalize()] or until the statement is automatically
   3661 ** reprepared by the first call to [sqlite3_step()] for a particular run
   3662 ** or until the same information is requested
   3663 ** again in a different encoding.
   3664 **
   3665 ** ^The names returned are the original un-aliased names of the
   3666 ** database, table, and column.
   3667 **
   3668 ** ^The first argument to these interfaces is a [prepared statement].
   3669 ** ^These functions return information about the Nth result column returned by
   3670 ** the statement, where N is the second function argument.
   3671 ** ^The left-most column is column 0 for these routines.
   3672 **
   3673 ** ^If the Nth column returned by the statement is an expression or
   3674 ** subquery and is not a column value, then all of these functions return
   3675 ** NULL.  ^These routine might also return NULL if a memory allocation error
   3676 ** occurs.  ^Otherwise, they return the name of the attached database, table,
   3677 ** or column that query result column was extracted from.
   3678 **
   3679 ** ^As with all other SQLite APIs, those whose names end with "16" return
   3680 ** UTF-16 encoded strings and the other functions return UTF-8.
   3681 **
   3682 ** ^These APIs are only available if the library was compiled with the
   3683 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
   3684 **
   3685 ** If two or more threads call one or more of these routines against the same
   3686 ** prepared statement and column at the same time then the results are
   3687 ** undefined.
   3688 **
   3689 ** If two or more threads call one or more
   3690 ** [sqlite3_column_database_name | column metadata interfaces]
   3691 ** for the same [prepared statement] and result column
   3692 ** at the same time then the results are undefined.
   3693 */
   3694 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
   3695 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
   3696 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
   3697 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
   3698 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
   3699 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
   3700 
   3701 /*
   3702 ** CAPI3REF: Declared Datatype Of A Query Result
   3703 **
   3704 ** ^(The first parameter is a [prepared statement].
   3705 ** If this statement is a [SELECT] statement and the Nth column of the
   3706 ** returned result set of that [SELECT] is a table column (not an
   3707 ** expression or subquery) then the declared type of the table
   3708 ** column is returned.)^  ^If the Nth column of the result set is an
   3709 ** expression or subquery, then a NULL pointer is returned.
   3710 ** ^The returned string is always UTF-8 encoded.
   3711 **
   3712 ** ^(For example, given the database schema:
   3713 **
   3714 ** CREATE TABLE t1(c1 VARIANT);
   3715 **
   3716 ** and the following statement to be compiled:
   3717 **
   3718 ** SELECT c1 + 1, c1 FROM t1;
   3719 **
   3720 ** this routine would return the string "VARIANT" for the second result
   3721 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
   3722 **
   3723 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
   3724 ** is declared to contain a particular type does not mean that the
   3725 ** data stored in that column is of the declared type.  SQLite is
   3726 ** strongly typed, but the typing is dynamic not static.  ^Type
   3727 ** is associated with individual values, not with the containers
   3728 ** used to hold those values.
   3729 */
   3730 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
   3731 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
   3732 
   3733 /*
   3734 ** CAPI3REF: Evaluate An SQL Statement
   3735 **
   3736 ** After a [prepared statement] has been prepared using either
   3737 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
   3738 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
   3739 ** must be called one or more times to evaluate the statement.
   3740 **
   3741 ** The details of the behavior of the sqlite3_step() interface depend
   3742 ** on whether the statement was prepared using the newer "v2" interface
   3743 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
   3744 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
   3745 ** new "v2" interface is recommended for new applications but the legacy
   3746 ** interface will continue to be supported.
   3747 **
   3748 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
   3749 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
   3750 ** ^With the "v2" interface, any of the other [result codes] or
   3751 ** [extended result codes] might be returned as well.
   3752 **
   3753 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
   3754 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
   3755 ** or occurs outside of an explicit transaction, then you can retry the
   3756 ** statement.  If the statement is not a [COMMIT] and occurs within an
   3757 ** explicit transaction then you should rollback the transaction before
   3758 ** continuing.
   3759 **
   3760 ** ^[SQLITE_DONE] means that the statement has finished executing
   3761 ** successfully.  sqlite3_step() should not be called again on this virtual
   3762 ** machine without first calling [sqlite3_reset()] to reset the virtual
   3763 ** machine back to its initial state.
   3764 **
   3765 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
   3766 ** is returned each time a new row of data is ready for processing by the
   3767 ** caller. The values may be accessed using the [column access functions].
   3768 ** sqlite3_step() is called again to retrieve the next row of data.
   3769 **
   3770 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
   3771 ** violation) has occurred.  sqlite3_step() should not be called again on
   3772 ** the VM. More information may be found by calling [sqlite3_errmsg()].
   3773 ** ^With the legacy interface, a more specific error code (for example,
   3774 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
   3775 ** can be obtained by calling [sqlite3_reset()] on the
   3776 ** [prepared statement].  ^In the "v2" interface,
   3777 ** the more specific error code is returned directly by sqlite3_step().
   3778 **
   3779 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
   3780 ** Perhaps it was called on a [prepared statement] that has
   3781 ** already been [sqlite3_finalize | finalized] or on one that had
   3782 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
   3783 ** be the case that the same database connection is being used by two or
   3784 ** more threads at the same moment in time.
   3785 **
   3786 ** For all versions of SQLite up to and including 3.6.23.1, a call to
   3787 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
   3788 ** other than [SQLITE_ROW] before any subsequent invocation of
   3789 ** sqlite3_step().  Failure to reset the prepared statement using
   3790 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
   3791 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
   3792 ** calling [sqlite3_reset()] automatically in this circumstance rather
   3793 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
   3794 ** break because any application that ever receives an SQLITE_MISUSE error
   3795 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
   3796 ** can be used to restore the legacy behavior.
   3797 **
   3798 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
   3799 ** API always returns a generic error code, [SQLITE_ERROR], following any
   3800 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
   3801 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
   3802 ** specific [error codes] that better describes the error.
   3803 ** We admit that this is a goofy design.  The problem has been fixed
   3804 ** with the "v2" interface.  If you prepare all of your SQL statements
   3805 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
   3806 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
   3807 ** then the more specific [error codes] are returned directly
   3808 ** by sqlite3_step().  The use of the "v2" interface is recommended.
   3809 */
   3810 SQLITE_API int sqlite3_step(sqlite3_stmt*);
   3811 
   3812 /*
   3813 ** CAPI3REF: Number of columns in a result set
   3814 **
   3815 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
   3816 ** current row of the result set of [prepared statement] P.
   3817 ** ^If prepared statement P does not have results ready to return
   3818 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
   3819 ** interfaces) then sqlite3_data_count(P) returns 0.
   3820 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
   3821 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
   3822 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
   3823 ** will return non-zero if previous call to [sqlite3_step](P) returned
   3824 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
   3825 ** where it always returns zero since each step of that multi-step
   3826 ** pragma returns 0 columns of data.
   3827 **
   3828 ** See also: [sqlite3_column_count()]
   3829 */
   3830 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
   3831 
   3832 /*
   3833 ** CAPI3REF: Fundamental Datatypes
   3834 ** KEYWORDS: SQLITE_TEXT
   3835 **
   3836 ** ^(Every value in SQLite has one of five fundamental datatypes:
   3837 **
   3838 ** <ul>
   3839 ** <li> 64-bit signed integer
   3840 ** <li> 64-bit IEEE floating point number
   3841 ** <li> string
   3842 ** <li> BLOB
   3843 ** <li> NULL
   3844 ** </ul>)^
   3845 **
   3846 ** These constants are codes for each of those types.
   3847 **
   3848 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
   3849 ** for a completely different meaning.  Software that links against both
   3850 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
   3851 ** SQLITE_TEXT.
   3852 */
   3853 #define SQLITE_INTEGER  1
   3854 #define SQLITE_FLOAT    2
   3855 #define SQLITE_BLOB     4
   3856 #define SQLITE_NULL     5
   3857 #ifdef SQLITE_TEXT
   3858 # undef SQLITE_TEXT
   3859 #else
   3860 # define SQLITE_TEXT     3
   3861 #endif
   3862 #define SQLITE3_TEXT     3
   3863 
   3864 /*
   3865 ** CAPI3REF: Result Values From A Query
   3866 ** KEYWORDS: {column access functions}
   3867 **
   3868 ** These routines form the "result set" interface.
   3869 **
   3870 ** ^These routines return information about a single column of the current
   3871 ** result row of a query.  ^In every case the first argument is a pointer
   3872 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
   3873 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
   3874 ** and the second argument is the index of the column for which information
   3875 ** should be returned. ^The leftmost column of the result set has the index 0.
   3876 ** ^The number of columns in the result can be determined using
   3877 ** [sqlite3_column_count()].
   3878 **
   3879 ** If the SQL statement does not currently point to a valid row, or if the
   3880 ** column index is out of range, the result is undefined.
   3881 ** These routines may only be called when the most recent call to
   3882 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
   3883 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
   3884 ** If any of these routines are called after [sqlite3_reset()] or
   3885 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
   3886 ** something other than [SQLITE_ROW], the results are undefined.
   3887 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
   3888 ** are called from a different thread while any of these routines
   3889 ** are pending, then the results are undefined.
   3890 **
   3891 ** ^The sqlite3_column_type() routine returns the
   3892 ** [SQLITE_INTEGER | datatype code] for the initial data type
   3893 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
   3894 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
   3895 ** returned by sqlite3_column_type() is only meaningful if no type
   3896 ** conversions have occurred as described below.  After a type conversion,
   3897 ** the value returned by sqlite3_column_type() is undefined.  Future
   3898 ** versions of SQLite may change the behavior of sqlite3_column_type()
   3899 ** following a type conversion.
   3900 **
   3901 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
   3902 ** routine returns the number of bytes in that BLOB or string.
   3903 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
   3904 ** the string to UTF-8 and then returns the number of bytes.
   3905 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
   3906 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
   3907 ** the number of bytes in that string.
   3908 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
   3909 **
   3910 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
   3911 ** routine returns the number of bytes in that BLOB or string.
   3912 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
   3913 ** the string to UTF-16 and then returns the number of bytes.
   3914 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
   3915 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
   3916 ** the number of bytes in that string.
   3917 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
   3918 **
   3919 ** ^The values returned by [sqlite3_column_bytes()] and
   3920 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
   3921 ** of the string.  ^For clarity: the values returned by
   3922 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
   3923 ** bytes in the string, not the number of characters.
   3924 **
   3925 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
   3926 ** even empty strings, are always zero-terminated.  ^The return
   3927 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
   3928 **
   3929 ** ^The object returned by [sqlite3_column_value()] is an
   3930 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
   3931 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
   3932 ** If the [unprotected sqlite3_value] object returned by
   3933 ** [sqlite3_column_value()] is used in any other way, including calls
   3934 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
   3935 ** or [sqlite3_value_bytes()], then the behavior is undefined.
   3936 **
   3937 ** These routines attempt to convert the value where appropriate.  ^For
   3938 ** example, if the internal representation is FLOAT and a text result
   3939 ** is requested, [sqlite3_snprintf()] is used internally to perform the
   3940 ** conversion automatically.  ^(The following table details the conversions
   3941 ** that are applied:
   3942 **
   3943 ** <blockquote>
   3944 ** <table border="1">
   3945 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
   3946 **
   3947 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
   3948 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
   3949 ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
   3950 ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
   3951 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
   3952 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
   3953 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
   3954 ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
   3955 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
   3956 ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
   3957 ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
   3958 ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
   3959 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
   3960 ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
   3961 ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
   3962 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
   3963 ** </table>
   3964 ** </blockquote>)^
   3965 **
   3966 ** The table above makes reference to standard C library functions atoi()
   3967 ** and atof().  SQLite does not really use these functions.  It has its
   3968 ** own equivalent internal routines.  The atoi() and atof() names are
   3969 ** used in the table for brevity and because they are familiar to most
   3970 ** C programmers.
   3971 **
   3972 ** Note that when type conversions occur, pointers returned by prior
   3973 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
   3974 ** sqlite3_column_text16() may be invalidated.
   3975 ** Type conversions and pointer invalidations might occur
   3976 ** in the following cases:
   3977 **
   3978 ** <ul>
   3979 ** <li> The initial content is a BLOB and sqlite3_column_text() or
   3980 **      sqlite3_column_text16() is called.  A zero-terminator might
   3981 **      need to be added to the string.</li>
   3982 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
   3983 **      sqlite3_column_text16() is called.  The content must be converted
   3984 **      to UTF-16.</li>
   3985 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
   3986 **      sqlite3_column_text() is called.  The content must be converted
   3987 **      to UTF-8.</li>
   3988 ** </ul>
   3989 **
   3990 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
   3991 ** not invalidate a prior pointer, though of course the content of the buffer
   3992 ** that the prior pointer references will have been modified.  Other kinds
   3993 ** of conversion are done in place when it is possible, but sometimes they
   3994 ** are not possible and in those cases prior pointers are invalidated.
   3995 **
   3996 ** The safest and easiest to remember policy is to invoke these routines
   3997 ** in one of the following ways:
   3998 **
   3999 ** <ul>
   4000 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
   4001 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
   4002 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
   4003 ** </ul>
   4004 **
   4005 ** In other words, you should call sqlite3_column_text(),
   4006 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
   4007 ** into the desired format, then invoke sqlite3_column_bytes() or
   4008 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
   4009 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
   4010 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
   4011 ** with calls to sqlite3_column_bytes().
   4012 **
   4013 ** ^The pointers returned are valid until a type conversion occurs as
   4014 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
   4015 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
   4016 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
   4017 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
   4018 ** [sqlite3_free()].
   4019 **
   4020 ** ^(If a memory allocation error occurs during the evaluation of any
   4021 ** of these routines, a default value is returned.  The default value
   4022 ** is either the integer 0, the floating point number 0.0, or a NULL
   4023 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
   4024 ** [SQLITE_NOMEM].)^
   4025 */
   4026 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
   4027 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
   4028 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
   4029 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
   4030 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
   4031 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
   4032 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
   4033 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
   4034 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
   4035 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
   4036 
   4037 /*
   4038 ** CAPI3REF: Destroy A Prepared Statement Object
   4039 **
   4040 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
   4041 ** ^If the most recent evaluation of the statement encountered no errors
   4042 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
   4043 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
   4044 ** sqlite3_finalize(S) returns the appropriate [error code] or
   4045 ** [extended error code].
   4046 **
   4047 ** ^The sqlite3_finalize(S) routine can be called at any point during
   4048 ** the life cycle of [prepared statement] S:
   4049 ** before statement S is ever evaluated, after
   4050 ** one or more calls to [sqlite3_reset()], or after any call
   4051 ** to [sqlite3_step()] regardless of whether or not the statement has
   4052 ** completed execution.
   4053 **
   4054 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
   4055 **
   4056 ** The application must finalize every [prepared statement] in order to avoid
   4057 ** resource leaks.  It is a grievous error for the application to try to use
   4058 ** a prepared statement after it has been finalized.  Any use of a prepared
   4059 ** statement after it has been finalized can result in undefined and
   4060 ** undesirable behavior such as segfaults and heap corruption.
   4061 */
   4062 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
   4063 
   4064 /*
   4065 ** CAPI3REF: Reset A Prepared Statement Object
   4066 **
   4067 ** The sqlite3_reset() function is called to reset a [prepared statement]
   4068 ** object back to its initial state, ready to be re-executed.
   4069 ** ^Any SQL statement variables that had values bound to them using
   4070 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
   4071 ** Use [sqlite3_clear_bindings()] to reset the bindings.
   4072 **
   4073 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
   4074 ** back to the beginning of its program.
   4075 **
   4076 ** ^If the most recent call to [sqlite3_step(S)] for the
   4077 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
   4078 ** or if [sqlite3_step(S)] has never before been called on S,
   4079 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
   4080 **
   4081 ** ^If the most recent call to [sqlite3_step(S)] for the
   4082 ** [prepared statement] S indicated an error, then
   4083 ** [sqlite3_reset(S)] returns an appropriate [error code].
   4084 **
   4085 ** ^The [sqlite3_reset(S)] interface does not change the values
   4086 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
   4087 */
   4088 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
   4089 
   4090 /*
   4091 ** CAPI3REF: Create Or Redefine SQL Functions
   4092 ** KEYWORDS: {function creation routines}
   4093 ** KEYWORDS: {application-defined SQL function}
   4094 ** KEYWORDS: {application-defined SQL functions}
   4095 **
   4096 ** ^These functions (collectively known as "function creation routines")
   4097 ** are used to add SQL functions or aggregates or to redefine the behavior
   4098 ** of existing SQL functions or aggregates.  The only differences between
   4099 ** these routines are the text encoding expected for
   4100 ** the second parameter (the name of the function being created)
   4101 ** and the presence or absence of a destructor callback for
   4102 ** the application data pointer.
   4103 **
   4104 ** ^The first parameter is the [database connection] to which the SQL
   4105 ** function is to be added.  ^If an application uses more than one database
   4106 ** connection then application-defined SQL functions must be added
   4107 ** to each database connection separately.
   4108 **
   4109 ** ^The second parameter is the name of the SQL function to be created or
   4110 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
   4111 ** representation, exclusive of the zero-terminator.  ^Note that the name
   4112 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
   4113 ** ^Any attempt to create a function with a longer name
   4114 ** will result in [SQLITE_MISUSE] being returned.
   4115 **
   4116 ** ^The third parameter (nArg)
   4117 ** is the number of arguments that the SQL function or
   4118 ** aggregate takes. ^If this parameter is -1, then the SQL function or
   4119 ** aggregate may take any number of arguments between 0 and the limit
   4120 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
   4121 ** parameter is less than -1 or greater than 127 then the behavior is
   4122 ** undefined.
   4123 **
   4124 ** ^The fourth parameter, eTextRep, specifies what
   4125 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
   4126 ** its parameters.  The application should set this parameter to
   4127 ** [SQLITE_UTF16LE] if the function implementation invokes
   4128 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
   4129 ** implementation invokes [sqlite3_value_text16be()] on an input, or
   4130 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
   4131 ** otherwise.  ^The same SQL function may be registered multiple times using
   4132 ** different preferred text encodings, with different implementations for
   4133 ** each encoding.
   4134 ** ^When multiple implementations of the same function are available, SQLite
   4135 ** will pick the one that involves the least amount of data conversion.
   4136 **
   4137 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
   4138 ** to signal that the function will always return the same result given
   4139 ** the same inputs within a single SQL statement.  Most SQL functions are
   4140 ** deterministic.  The built-in [random()] SQL function is an example of a
   4141 ** function that is not deterministic.  The SQLite query planner is able to
   4142 ** perform additional optimizations on deterministic functions, so use
   4143 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
   4144 **
   4145 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
   4146 ** function can gain access to this pointer using [sqlite3_user_data()].)^
   4147 **
   4148 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
   4149 ** pointers to C-language functions that implement the SQL function or
   4150 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
   4151 ** callback only; NULL pointers must be passed as the xStep and xFinal
   4152 ** parameters. ^An aggregate SQL function requires an implementation of xStep
   4153 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
   4154 ** SQL function or aggregate, pass NULL pointers for all three function
   4155 ** callbacks.
   4156 **
   4157 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
   4158 ** then it is destructor for the application data pointer.
   4159 ** The destructor is invoked when the function is deleted, either by being
   4160 ** overloaded or when the database connection closes.)^
   4161 ** ^The destructor is also invoked if the call to
   4162 ** sqlite3_create_function_v2() fails.
   4163 ** ^When the destructor callback of the tenth parameter is invoked, it
   4164 ** is passed a single argument which is a copy of the application data
   4165 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
   4166 **
   4167 ** ^It is permitted to register multiple implementations of the same
   4168 ** functions with the same name but with either differing numbers of
   4169 ** arguments or differing preferred text encodings.  ^SQLite will use
   4170 ** the implementation that most closely matches the way in which the
   4171 ** SQL function is used.  ^A function implementation with a non-negative
   4172 ** nArg parameter is a better match than a function implementation with
   4173 ** a negative nArg.  ^A function where the preferred text encoding
   4174 ** matches the database encoding is a better
   4175 ** match than a function where the encoding is different.
   4176 ** ^A function where the encoding difference is between UTF16le and UTF16be
   4177 ** is a closer match than a function where the encoding difference is
   4178 ** between UTF8 and UTF16.
   4179 **
   4180 ** ^Built-in functions may be overloaded by new application-defined functions.
   4181 **
   4182 ** ^An application-defined function is permitted to call other
   4183 ** SQLite interfaces.  However, such calls must not
   4184 ** close the database connection nor finalize or reset the prepared
   4185 ** statement in which the function is running.
   4186 */
   4187 SQLITE_API int sqlite3_create_function(
   4188   sqlite3 *db,
   4189   const char *zFunctionName,
   4190   int nArg,
   4191   int eTextRep,
   4192   void *pApp,
   4193   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   4194   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   4195   void (*xFinal)(sqlite3_context*)
   4196 );
   4197 SQLITE_API int sqlite3_create_function16(
   4198   sqlite3 *db,
   4199   const void *zFunctionName,
   4200   int nArg,
   4201   int eTextRep,
   4202   void *pApp,
   4203   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   4204   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   4205   void (*xFinal)(sqlite3_context*)
   4206 );
   4207 SQLITE_API int sqlite3_create_function_v2(
   4208   sqlite3 *db,
   4209   const char *zFunctionName,
   4210   int nArg,
   4211   int eTextRep,
   4212   void *pApp,
   4213   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   4214   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   4215   void (*xFinal)(sqlite3_context*),
   4216   void(*xDestroy)(void*)
   4217 );
   4218 
   4219 /*
   4220 ** CAPI3REF: Text Encodings
   4221 **
   4222 ** These constant define integer codes that represent the various
   4223 ** text encodings supported by SQLite.
   4224 */
   4225 #define SQLITE_UTF8           1
   4226 #define SQLITE_UTF16LE        2
   4227 #define SQLITE_UTF16BE        3
   4228 #define SQLITE_UTF16          4    /* Use native byte order */
   4229 #define SQLITE_ANY            5    /* Deprecated */
   4230 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
   4231 
   4232 /*
   4233 ** CAPI3REF: Function Flags
   4234 **
   4235 ** These constants may be ORed together with the
   4236 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
   4237 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
   4238 ** [sqlite3_create_function_v2()].
   4239 */
   4240 #define SQLITE_DETERMINISTIC    0x800
   4241 
   4242 /*
   4243 ** CAPI3REF: Deprecated Functions
   4244 ** DEPRECATED
   4245 **
   4246 ** These functions are [deprecated].  In order to maintain
   4247 ** backwards compatibility with older code, these functions continue
   4248 ** to be supported.  However, new applications should avoid
   4249 ** the use of these functions.  To help encourage people to avoid
   4250 ** using these functions, we are not going to tell you what they do.
   4251 */
   4252 #ifndef SQLITE_OMIT_DEPRECATED
   4253 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
   4254 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
   4255 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
   4256 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
   4257 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
   4258 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
   4259                       void*,sqlite3_int64);
   4260 #endif
   4261 
   4262 /*
   4263 ** CAPI3REF: Obtaining SQL Function Parameter Values
   4264 **
   4265 ** The C-language implementation of SQL functions and aggregates uses
   4266 ** this set of interface routines to access the parameter values on
   4267 ** the function or aggregate.
   4268 **
   4269 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
   4270 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
   4271 ** define callbacks that implement the SQL functions and aggregates.
   4272 ** The 3rd parameter to these callbacks is an array of pointers to
   4273 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
   4274 ** each parameter to the SQL function.  These routines are used to
   4275 ** extract values from the [sqlite3_value] objects.
   4276 **
   4277 ** These routines work only with [protected sqlite3_value] objects.
   4278 ** Any attempt to use these routines on an [unprotected sqlite3_value]
   4279 ** object results in undefined behavior.
   4280 **
   4281 ** ^These routines work just like the corresponding [column access functions]
   4282 ** except that  these routines take a single [protected sqlite3_value] object
   4283 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
   4284 **
   4285 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
   4286 ** in the native byte-order of the host machine.  ^The
   4287 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
   4288 ** extract UTF-16 strings as big-endian and little-endian respectively.
   4289 **
   4290 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
   4291 ** numeric affinity to the value.  This means that an attempt is
   4292 ** made to convert the value to an integer or floating point.  If
   4293 ** such a conversion is possible without loss of information (in other
   4294 ** words, if the value is a string that looks like a number)
   4295 ** then the conversion is performed.  Otherwise no conversion occurs.
   4296 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
   4297 **
   4298 ** Please pay particular attention to the fact that the pointer returned
   4299 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
   4300 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
   4301 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
   4302 ** or [sqlite3_value_text16()].
   4303 **
   4304 ** These routines must be called from the same thread as
   4305 ** the SQL function that supplied the [sqlite3_value*] parameters.
   4306 */
   4307 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
   4308 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
   4309 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
   4310 SQLITE_API double sqlite3_value_double(sqlite3_value*);
   4311 SQLITE_API int sqlite3_value_int(sqlite3_value*);
   4312 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
   4313 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
   4314 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
   4315 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
   4316 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
   4317 SQLITE_API int sqlite3_value_type(sqlite3_value*);
   4318 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
   4319 
   4320 /*
   4321 ** CAPI3REF: Obtain Aggregate Function Context
   4322 **
   4323 ** Implementations of aggregate SQL functions use this
   4324 ** routine to allocate memory for storing their state.
   4325 **
   4326 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
   4327 ** for a particular aggregate function, SQLite
   4328 ** allocates N of memory, zeroes out that memory, and returns a pointer
   4329 ** to the new memory. ^On second and subsequent calls to
   4330 ** sqlite3_aggregate_context() for the same aggregate function instance,
   4331 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
   4332 ** called once for each invocation of the xStep callback and then one
   4333 ** last time when the xFinal callback is invoked.  ^(When no rows match
   4334 ** an aggregate query, the xStep() callback of the aggregate function
   4335 ** implementation is never called and xFinal() is called exactly once.
   4336 ** In those cases, sqlite3_aggregate_context() might be called for the
   4337 ** first time from within xFinal().)^
   4338 **
   4339 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
   4340 ** when first called if N is less than or equal to zero or if a memory
   4341 ** allocate error occurs.
   4342 **
   4343 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
   4344 ** determined by the N parameter on first successful call.  Changing the
   4345 ** value of N in subsequent call to sqlite3_aggregate_context() within
   4346 ** the same aggregate function instance will not resize the memory
   4347 ** allocation.)^  Within the xFinal callback, it is customary to set
   4348 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
   4349 ** pointless memory allocations occur.
   4350 **
   4351 ** ^SQLite automatically frees the memory allocated by
   4352 ** sqlite3_aggregate_context() when the aggregate query concludes.
   4353 **
   4354 ** The first parameter must be a copy of the
   4355 ** [sqlite3_context | SQL function context] that is the first parameter
   4356 ** to the xStep or xFinal callback routine that implements the aggregate
   4357 ** function.
   4358 **
   4359 ** This routine must be called from the same thread in which
   4360 ** the aggregate SQL function is running.
   4361 */
   4362 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
   4363 
   4364 /*
   4365 ** CAPI3REF: User Data For Functions
   4366 **
   4367 ** ^The sqlite3_user_data() interface returns a copy of
   4368 ** the pointer that was the pUserData parameter (the 5th parameter)
   4369 ** of the [sqlite3_create_function()]
   4370 ** and [sqlite3_create_function16()] routines that originally
   4371 ** registered the application defined function.
   4372 **
   4373 ** This routine must be called from the same thread in which
   4374 ** the application-defined function is running.
   4375 */
   4376 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
   4377 
   4378 /*
   4379 ** CAPI3REF: Database Connection For Functions
   4380 **
   4381 ** ^The sqlite3_context_db_handle() interface returns a copy of
   4382 ** the pointer to the [database connection] (the 1st parameter)
   4383 ** of the [sqlite3_create_function()]
   4384 ** and [sqlite3_create_function16()] routines that originally
   4385 ** registered the application defined function.
   4386 */
   4387 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
   4388 
   4389 /*
   4390 ** CAPI3REF: Function Auxiliary Data
   4391 **
   4392 ** These functions may be used by (non-aggregate) SQL functions to
   4393 ** associate metadata with argument values. If the same value is passed to
   4394 ** multiple invocations of the same SQL function during query execution, under
   4395 ** some circumstances the associated metadata may be preserved.  An example
   4396 ** of where this might be useful is in a regular-expression matching
   4397 ** function. The compiled version of the regular expression can be stored as
   4398 ** metadata associated with the pattern string.
   4399 ** Then as long as the pattern string remains the same,
   4400 ** the compiled regular expression can be reused on multiple
   4401 ** invocations of the same function.
   4402 **
   4403 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
   4404 ** associated by the sqlite3_set_auxdata() function with the Nth argument
   4405 ** value to the application-defined function. ^If there is no metadata
   4406 ** associated with the function argument, this sqlite3_get_auxdata() interface
   4407 ** returns a NULL pointer.
   4408 **
   4409 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
   4410 ** argument of the application-defined function.  ^Subsequent
   4411 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
   4412 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
   4413 ** NULL if the metadata has been discarded.
   4414 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
   4415 ** SQLite will invoke the destructor function X with parameter P exactly
   4416 ** once, when the metadata is discarded.
   4417 ** SQLite is free to discard the metadata at any time, including: <ul>
   4418 ** <li> when the corresponding function parameter changes, or
   4419 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
   4420 **      SQL statement, or
   4421 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
   4422 ** <li> during the original sqlite3_set_auxdata() call when a memory
   4423 **      allocation error occurs. </ul>)^
   4424 **
   4425 ** Note the last bullet in particular.  The destructor X in
   4426 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
   4427 ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
   4428 ** should be called near the end of the function implementation and the
   4429 ** function implementation should not make any use of P after
   4430 ** sqlite3_set_auxdata() has been called.
   4431 **
   4432 ** ^(In practice, metadata is preserved between function calls for
   4433 ** function parameters that are compile-time constants, including literal
   4434 ** values and [parameters] and expressions composed from the same.)^
   4435 **
   4436 ** These routines must be called from the same thread in which
   4437 ** the SQL function is running.
   4438 */
   4439 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
   4440 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
   4441 
   4442 
   4443 /*
   4444 ** CAPI3REF: Constants Defining Special Destructor Behavior
   4445 **
   4446 ** These are special values for the destructor that is passed in as the
   4447 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
   4448 ** argument is SQLITE_STATIC, it means that the content pointer is constant
   4449 ** and will never change.  It does not need to be destroyed.  ^The
   4450 ** SQLITE_TRANSIENT value means that the content will likely change in
   4451 ** the near future and that SQLite should make its own private copy of
   4452 ** the content before returning.
   4453 **
   4454 ** The typedef is necessary to work around problems in certain
   4455 ** C++ compilers.
   4456 */
   4457 typedef void (*sqlite3_destructor_type)(void*);
   4458 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
   4459 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
   4460 
   4461 /*
   4462 ** CAPI3REF: Setting The Result Of An SQL Function
   4463 **
   4464 ** These routines are used by the xFunc or xFinal callbacks that
   4465 ** implement SQL functions and aggregates.  See
   4466 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
   4467 ** for additional information.
   4468 **
   4469 ** These functions work very much like the [parameter binding] family of
   4470 ** functions used to bind values to host parameters in prepared statements.
   4471 ** Refer to the [SQL parameter] documentation for additional information.
   4472 **
   4473 ** ^The sqlite3_result_blob() interface sets the result from
   4474 ** an application-defined function to be the BLOB whose content is pointed
   4475 ** to by the second parameter and which is N bytes long where N is the
   4476 ** third parameter.
   4477 **
   4478 ** ^The sqlite3_result_zeroblob() interfaces set the result of
   4479 ** the application-defined function to be a BLOB containing all zero
   4480 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
   4481 **
   4482 ** ^The sqlite3_result_double() interface sets the result from
   4483 ** an application-defined function to be a floating point value specified
   4484 ** by its 2nd argument.
   4485 **
   4486 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
   4487 ** cause the implemented SQL function to throw an exception.
   4488 ** ^SQLite uses the string pointed to by the
   4489 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
   4490 ** as the text of an error message.  ^SQLite interprets the error
   4491 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
   4492 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
   4493 ** byte order.  ^If the third parameter to sqlite3_result_error()
   4494 ** or sqlite3_result_error16() is negative then SQLite takes as the error
   4495 ** message all text up through the first zero character.
   4496 ** ^If the third parameter to sqlite3_result_error() or
   4497 ** sqlite3_result_error16() is non-negative then SQLite takes that many
   4498 ** bytes (not characters) from the 2nd parameter as the error message.
   4499 ** ^The sqlite3_result_error() and sqlite3_result_error16()
   4500 ** routines make a private copy of the error message text before
   4501 ** they return.  Hence, the calling function can deallocate or
   4502 ** modify the text after they return without harm.
   4503 ** ^The sqlite3_result_error_code() function changes the error code
   4504 ** returned by SQLite as a result of an error in a function.  ^By default,
   4505 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
   4506 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
   4507 **
   4508 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
   4509 ** error indicating that a string or BLOB is too long to represent.
   4510 **
   4511 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
   4512 ** error indicating that a memory allocation failed.
   4513 **
   4514 ** ^The sqlite3_result_int() interface sets the return value
   4515 ** of the application-defined function to be the 32-bit signed integer
   4516 ** value given in the 2nd argument.
   4517 ** ^The sqlite3_result_int64() interface sets the return value
   4518 ** of the application-defined function to be the 64-bit signed integer
   4519 ** value given in the 2nd argument.
   4520 **
   4521 ** ^The sqlite3_result_null() interface sets the return value
   4522 ** of the application-defined function to be NULL.
   4523 **
   4524 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
   4525 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
   4526 ** set the return value of the application-defined function to be
   4527 ** a text string which is represented as UTF-8, UTF-16 native byte order,
   4528 ** UTF-16 little endian, or UTF-16 big endian, respectively.
   4529 ** ^SQLite takes the text result from the application from
   4530 ** the 2nd parameter of the sqlite3_result_text* interfaces.
   4531 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4532 ** is negative, then SQLite takes result text from the 2nd parameter
   4533 ** through the first zero character.
   4534 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4535 ** is non-negative, then as many bytes (not characters) of the text
   4536 ** pointed to by the 2nd parameter are taken as the application-defined
   4537 ** function result.  If the 3rd parameter is non-negative, then it
   4538 ** must be the byte offset into the string where the NUL terminator would
   4539 ** appear if the string where NUL terminated.  If any NUL characters occur
   4540 ** in the string at a byte offset that is less than the value of the 3rd
   4541 ** parameter, then the resulting string will contain embedded NULs and the
   4542 ** result of expressions operating on strings with embedded NULs is undefined.
   4543 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4544 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
   4545 ** function as the destructor on the text or BLOB result when it has
   4546 ** finished using that result.
   4547 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
   4548 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
   4549 ** assumes that the text or BLOB result is in constant space and does not
   4550 ** copy the content of the parameter nor call a destructor on the content
   4551 ** when it has finished using that result.
   4552 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4553 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
   4554 ** then SQLite makes a copy of the result into space obtained from
   4555 ** from [sqlite3_malloc()] before it returns.
   4556 **
   4557 ** ^The sqlite3_result_value() interface sets the result of
   4558 ** the application-defined function to be a copy the
   4559 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
   4560 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
   4561 ** so that the [sqlite3_value] specified in the parameter may change or
   4562 ** be deallocated after sqlite3_result_value() returns without harm.
   4563 ** ^A [protected sqlite3_value] object may always be used where an
   4564 ** [unprotected sqlite3_value] object is required, so either
   4565 ** kind of [sqlite3_value] object can be used with this interface.
   4566 **
   4567 ** If these routines are called from within the different thread
   4568 ** than the one containing the application-defined function that received
   4569 ** the [sqlite3_context] pointer, the results are undefined.
   4570 */
   4571 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
   4572 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
   4573 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
   4574 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
   4575 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
   4576 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
   4577 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
   4578 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
   4579 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
   4580 SQLITE_API void sqlite3_result_null(sqlite3_context*);
   4581 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
   4582 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
   4583 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
   4584 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
   4585 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
   4586 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
   4587 
   4588 /*
   4589 ** CAPI3REF: Define New Collating Sequences
   4590 **
   4591 ** ^These functions add, remove, or modify a [collation] associated
   4592 ** with the [database connection] specified as the first argument.
   4593 **
   4594 ** ^The name of the collation is a UTF-8 string
   4595 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
   4596 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
   4597 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
   4598 ** considered to be the same name.
   4599 **
   4600 ** ^(The third argument (eTextRep) must be one of the constants:
   4601 ** <ul>
   4602 ** <li> [SQLITE_UTF8],
   4603 ** <li> [SQLITE_UTF16LE],
   4604 ** <li> [SQLITE_UTF16BE],
   4605 ** <li> [SQLITE_UTF16], or
   4606 ** <li> [SQLITE_UTF16_ALIGNED].
   4607 ** </ul>)^
   4608 ** ^The eTextRep argument determines the encoding of strings passed
   4609 ** to the collating function callback, xCallback.
   4610 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
   4611 ** force strings to be UTF16 with native byte order.
   4612 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
   4613 ** on an even byte address.
   4614 **
   4615 ** ^The fourth argument, pArg, is an application data pointer that is passed
   4616 ** through as the first argument to the collating function callback.
   4617 **
   4618 ** ^The fifth argument, xCallback, is a pointer to the collating function.
   4619 ** ^Multiple collating functions can be registered using the same name but
   4620 ** with different eTextRep parameters and SQLite will use whichever
   4621 ** function requires the least amount of data transformation.
   4622 ** ^If the xCallback argument is NULL then the collating function is
   4623 ** deleted.  ^When all collating functions having the same name are deleted,
   4624 ** that collation is no longer usable.
   4625 **
   4626 ** ^The collating function callback is invoked with a copy of the pArg
   4627 ** application data pointer and with two strings in the encoding specified
   4628 ** by the eTextRep argument.  The collating function must return an
   4629 ** integer that is negative, zero, or positive
   4630 ** if the first string is less than, equal to, or greater than the second,
   4631 ** respectively.  A collating function must always return the same answer
   4632 ** given the same inputs.  If two or more collating functions are registered
   4633 ** to the same collation name (using different eTextRep values) then all
   4634 ** must give an equivalent answer when invoked with equivalent strings.
   4635 ** The collating function must obey the following properties for all
   4636 ** strings A, B, and C:
   4637 **
   4638 ** <ol>
   4639 ** <li> If A==B then B==A.
   4640 ** <li> If A==B and B==C then A==C.
   4641 ** <li> If A&lt;B THEN B&gt;A.
   4642 ** <li> If A&lt;B and B&lt;C then A&lt;C.
   4643 ** </ol>
   4644 **
   4645 ** If a collating function fails any of the above constraints and that
   4646 ** collating function is  registered and used, then the behavior of SQLite
   4647 ** is undefined.
   4648 **
   4649 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
   4650 ** with the addition that the xDestroy callback is invoked on pArg when
   4651 ** the collating function is deleted.
   4652 ** ^Collating functions are deleted when they are overridden by later
   4653 ** calls to the collation creation functions or when the
   4654 ** [database connection] is closed using [sqlite3_close()].
   4655 **
   4656 ** ^The xDestroy callback is <u>not</u> called if the
   4657 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
   4658 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
   4659 ** check the return code and dispose of the application data pointer
   4660 ** themselves rather than expecting SQLite to deal with it for them.
   4661 ** This is different from every other SQLite interface.  The inconsistency
   4662 ** is unfortunate but cannot be changed without breaking backwards
   4663 ** compatibility.
   4664 **
   4665 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
   4666 */
   4667 SQLITE_API int sqlite3_create_collation(
   4668   sqlite3*,
   4669   const char *zName,
   4670   int eTextRep,
   4671   void *pArg,
   4672   int(*xCompare)(void*,int,const void*,int,const void*)
   4673 );
   4674 SQLITE_API int sqlite3_create_collation_v2(
   4675   sqlite3*,
   4676   const char *zName,
   4677   int eTextRep,
   4678   void *pArg,
   4679   int(*xCompare)(void*,int,const void*,int,const void*),
   4680   void(*xDestroy)(void*)
   4681 );
   4682 SQLITE_API int sqlite3_create_collation16(
   4683   sqlite3*,
   4684   const void *zName,
   4685   int eTextRep,
   4686   void *pArg,
   4687   int(*xCompare)(void*,int,const void*,int,const void*)
   4688 );
   4689 
   4690 /*
   4691 ** CAPI3REF: Collation Needed Callbacks
   4692 **
   4693 ** ^To avoid having to register all collation sequences before a database
   4694 ** can be used, a single callback function may be registered with the
   4695 ** [database connection] to be invoked whenever an undefined collation
   4696 ** sequence is required.
   4697 **
   4698 ** ^If the function is registered using the sqlite3_collation_needed() API,
   4699 ** then it is passed the names of undefined collation sequences as strings
   4700 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
   4701 ** the names are passed as UTF-16 in machine native byte order.
   4702 ** ^A call to either function replaces the existing collation-needed callback.
   4703 **
   4704 ** ^(When the callback is invoked, the first argument passed is a copy
   4705 ** of the second argument to sqlite3_collation_needed() or
   4706 ** sqlite3_collation_needed16().  The second argument is the database
   4707 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
   4708 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
   4709 ** sequence function required.  The fourth parameter is the name of the
   4710 ** required collation sequence.)^
   4711 **
   4712 ** The callback function should register the desired collation using
   4713 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
   4714 ** [sqlite3_create_collation_v2()].
   4715 */
   4716 SQLITE_API int sqlite3_collation_needed(
   4717   sqlite3*,
   4718   void*,
   4719   void(*)(void*,sqlite3*,int eTextRep,const char*)
   4720 );
   4721 SQLITE_API int sqlite3_collation_needed16(
   4722   sqlite3*,
   4723   void*,
   4724   void(*)(void*,sqlite3*,int eTextRep,const void*)
   4725 );
   4726 
   4727 #ifdef SQLITE_HAS_CODEC
   4728 /*
   4729 ** Specify the key for an encrypted database.  This routine should be
   4730 ** called right after sqlite3_open().
   4731 **
   4732 ** The code to implement this API is not available in the public release
   4733 ** of SQLite.
   4734 */
   4735 SQLITE_API int sqlite3_key(
   4736   sqlite3 *db,                   /* Database to be rekeyed */
   4737   const void *pKey, int nKey     /* The key */
   4738 );
   4739 SQLITE_API int sqlite3_key_v2(
   4740   sqlite3 *db,                   /* Database to be rekeyed */
   4741   const char *zDbName,           /* Name of the database */
   4742   const void *pKey, int nKey     /* The key */
   4743 );
   4744 
   4745 /*
   4746 ** Change the key on an open database.  If the current database is not
   4747 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
   4748 ** database is decrypted.
   4749 **
   4750 ** The code to implement this API is not available in the public release
   4751 ** of SQLite.
   4752 */
   4753 SQLITE_API int sqlite3_rekey(
   4754   sqlite3 *db,                   /* Database to be rekeyed */
   4755   const void *pKey, int nKey     /* The new key */
   4756 );
   4757 SQLITE_API int sqlite3_rekey_v2(
   4758   sqlite3 *db,                   /* Database to be rekeyed */
   4759   const char *zDbName,           /* Name of the database */
   4760   const void *pKey, int nKey     /* The new key */
   4761 );
   4762 
   4763 /*
   4764 ** Specify the activation key for a SEE database.  Unless
   4765 ** activated, none of the SEE routines will work.
   4766 */
   4767 SQLITE_API void sqlite3_activate_see(
   4768   const char *zPassPhrase        /* Activation phrase */
   4769 );
   4770 #endif
   4771 
   4772 #ifdef SQLITE_ENABLE_CEROD
   4773 /*
   4774 ** Specify the activation key for a CEROD database.  Unless
   4775 ** activated, none of the CEROD routines will work.
   4776 */
   4777 SQLITE_API void sqlite3_activate_cerod(
   4778   const char *zPassPhrase        /* Activation phrase */
   4779 );
   4780 #endif
   4781 
   4782 /*
   4783 ** CAPI3REF: Suspend Execution For A Short Time
   4784 **
   4785 ** The sqlite3_sleep() function causes the current thread to suspend execution
   4786 ** for at least a number of milliseconds specified in its parameter.
   4787 **
   4788 ** If the operating system does not support sleep requests with
   4789 ** millisecond time resolution, then the time will be rounded up to
   4790 ** the nearest second. The number of milliseconds of sleep actually
   4791 ** requested from the operating system is returned.
   4792 **
   4793 ** ^SQLite implements this interface by calling the xSleep()
   4794 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
   4795 ** of the default VFS is not implemented correctly, or not implemented at
   4796 ** all, then the behavior of sqlite3_sleep() may deviate from the description
   4797 ** in the previous paragraphs.
   4798 */
   4799 SQLITE_API int sqlite3_sleep(int);
   4800 
   4801 /*
   4802 ** CAPI3REF: Name Of The Folder Holding Temporary Files
   4803 **
   4804 ** ^(If this global variable is made to point to a string which is
   4805 ** the name of a folder (a.k.a. directory), then all temporary files
   4806 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
   4807 ** will be placed in that directory.)^  ^If this variable
   4808 ** is a NULL pointer, then SQLite performs a search for an appropriate
   4809 ** temporary file directory.
   4810 **
   4811 ** Applications are strongly discouraged from using this global variable.
   4812 ** It is required to set a temporary folder on Windows Runtime (WinRT).
   4813 ** But for all other platforms, it is highly recommended that applications
   4814 ** neither read nor write this variable.  This global variable is a relic
   4815 ** that exists for backwards compatibility of legacy applications and should
   4816 ** be avoided in new projects.
   4817 **
   4818 ** It is not safe to read or modify this variable in more than one
   4819 ** thread at a time.  It is not safe to read or modify this variable
   4820 ** if a [database connection] is being used at the same time in a separate
   4821 ** thread.
   4822 ** It is intended that this variable be set once
   4823 ** as part of process initialization and before any SQLite interface
   4824 ** routines have been called and that this variable remain unchanged
   4825 ** thereafter.
   4826 **
   4827 ** ^The [temp_store_directory pragma] may modify this variable and cause
   4828 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
   4829 ** the [temp_store_directory pragma] always assumes that any string
   4830 ** that this variable points to is held in memory obtained from
   4831 ** [sqlite3_malloc] and the pragma may attempt to free that memory
   4832 ** using [sqlite3_free].
   4833 ** Hence, if this variable is modified directly, either it should be
   4834 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
   4835 ** or else the use of the [temp_store_directory pragma] should be avoided.
   4836 ** Except when requested by the [temp_store_directory pragma], SQLite
   4837 ** does not free the memory that sqlite3_temp_directory points to.  If
   4838 ** the application wants that memory to be freed, it must do
   4839 ** so itself, taking care to only do so after all [database connection]
   4840 ** objects have been destroyed.
   4841 **
   4842 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
   4843 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
   4844 ** features that require the use of temporary files may fail.  Here is an
   4845 ** example of how to do this using C++ with the Windows Runtime:
   4846 **
   4847 ** <blockquote><pre>
   4848 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
   4849 ** &nbsp;     TemporaryFolder->Path->Data();
   4850 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
   4851 ** memset(zPathBuf, 0, sizeof(zPathBuf));
   4852 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
   4853 ** &nbsp;     NULL, NULL);
   4854 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
   4855 ** </pre></blockquote>
   4856 */
   4857 SQLITE_API char *sqlite3_temp_directory;
   4858 
   4859 /*
   4860 ** CAPI3REF: Name Of The Folder Holding Database Files
   4861 **
   4862 ** ^(If this global variable is made to point to a string which is
   4863 ** the name of a folder (a.k.a. directory), then all database files
   4864 ** specified with a relative pathname and created or accessed by
   4865 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
   4866 ** to be relative to that directory.)^ ^If this variable is a NULL
   4867 ** pointer, then SQLite assumes that all database files specified
   4868 ** with a relative pathname are relative to the current directory
   4869 ** for the process.  Only the windows VFS makes use of this global
   4870 ** variable; it is ignored by the unix VFS.
   4871 **
   4872 ** Changing the value of this variable while a database connection is
   4873 ** open can result in a corrupt database.
   4874 **
   4875 ** It is not safe to read or modify this variable in more than one
   4876 ** thread at a time.  It is not safe to read or modify this variable
   4877 ** if a [database connection] is being used at the same time in a separate
   4878 ** thread.
   4879 ** It is intended that this variable be set once
   4880 ** as part of process initialization and before any SQLite interface
   4881 ** routines have been called and that this variable remain unchanged
   4882 ** thereafter.
   4883 **
   4884 ** ^The [data_store_directory pragma] may modify this variable and cause
   4885 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
   4886 ** the [data_store_directory pragma] always assumes that any string
   4887 ** that this variable points to is held in memory obtained from
   4888 ** [sqlite3_malloc] and the pragma may attempt to free that memory
   4889 ** using [sqlite3_free].
   4890 ** Hence, if this variable is modified directly, either it should be
   4891 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
   4892 ** or else the use of the [data_store_directory pragma] should be avoided.
   4893 */
   4894 SQLITE_API char *sqlite3_data_directory;
   4895 
   4896 /*
   4897 ** CAPI3REF: Test For Auto-Commit Mode
   4898 ** KEYWORDS: {autocommit mode}
   4899 **
   4900 ** ^The sqlite3_get_autocommit() interface returns non-zero or
   4901 ** zero if the given database connection is or is not in autocommit mode,
   4902 ** respectively.  ^Autocommit mode is on by default.
   4903 ** ^Autocommit mode is disabled by a [BEGIN] statement.
   4904 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
   4905 **
   4906 ** If certain kinds of errors occur on a statement within a multi-statement
   4907 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
   4908 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
   4909 ** transaction might be rolled back automatically.  The only way to
   4910 ** find out whether SQLite automatically rolled back the transaction after
   4911 ** an error is to use this function.
   4912 **
   4913 ** If another thread changes the autocommit status of the database
   4914 ** connection while this routine is running, then the return value
   4915 ** is undefined.
   4916 */
   4917 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
   4918 
   4919 /*
   4920 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
   4921 **
   4922 ** ^The sqlite3_db_handle interface returns the [database connection] handle
   4923 ** to which a [prepared statement] belongs.  ^The [database connection]
   4924 ** returned by sqlite3_db_handle is the same [database connection]
   4925 ** that was the first argument
   4926 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
   4927 ** create the statement in the first place.
   4928 */
   4929 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
   4930 
   4931 /*
   4932 ** CAPI3REF: Return The Filename For A Database Connection
   4933 **
   4934 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
   4935 ** associated with database N of connection D.  ^The main database file
   4936 ** has the name "main".  If there is no attached database N on the database
   4937 ** connection D, or if database N is a temporary or in-memory database, then
   4938 ** a NULL pointer is returned.
   4939 **
   4940 ** ^The filename returned by this function is the output of the
   4941 ** xFullPathname method of the [VFS].  ^In other words, the filename
   4942 ** will be an absolute pathname, even if the filename used
   4943 ** to open the database originally was a URI or relative pathname.
   4944 */
   4945 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
   4946 
   4947 /*
   4948 ** CAPI3REF: Determine if a database is read-only
   4949 **
   4950 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
   4951 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
   4952 ** the name of a database on connection D.
   4953 */
   4954 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
   4955 
   4956 /*
   4957 ** CAPI3REF: Find the next prepared statement
   4958 **
   4959 ** ^This interface returns a pointer to the next [prepared statement] after
   4960 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
   4961 ** then this interface returns a pointer to the first prepared statement
   4962 ** associated with the database connection pDb.  ^If no prepared statement
   4963 ** satisfies the conditions of this routine, it returns NULL.
   4964 **
   4965 ** The [database connection] pointer D in a call to
   4966 ** [sqlite3_next_stmt(D,S)] must refer to an open database
   4967 ** connection and in particular must not be a NULL pointer.
   4968 */
   4969 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
   4970 
   4971 /*
   4972 ** CAPI3REF: Commit And Rollback Notification Callbacks
   4973 **
   4974 ** ^The sqlite3_commit_hook() interface registers a callback
   4975 ** function to be invoked whenever a transaction is [COMMIT | committed].
   4976 ** ^Any callback set by a previous call to sqlite3_commit_hook()
   4977 ** for the same database connection is overridden.
   4978 ** ^The sqlite3_rollback_hook() interface registers a callback
   4979 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
   4980 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
   4981 ** for the same database connection is overridden.
   4982 ** ^The pArg argument is passed through to the callback.
   4983 ** ^If the callback on a commit hook function returns non-zero,
   4984 ** then the commit is converted into a rollback.
   4985 **
   4986 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
   4987 ** return the P argument from the previous call of the same function
   4988 ** on the same [database connection] D, or NULL for
   4989 ** the first call for each function on D.
   4990 **
   4991 ** The commit and rollback hook callbacks are not reentrant.
   4992 ** The callback implementation must not do anything that will modify
   4993 ** the database connection that invoked the callback.  Any actions
   4994 ** to modify the database connection must be deferred until after the
   4995 ** completion of the [sqlite3_step()] call that triggered the commit
   4996 ** or rollback hook in the first place.
   4997 ** Note that running any other SQL statements, including SELECT statements,
   4998 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
   4999 ** the database connections for the meaning of "modify" in this paragraph.
   5000 **
   5001 ** ^Registering a NULL function disables the callback.
   5002 **
   5003 ** ^When the commit hook callback routine returns zero, the [COMMIT]
   5004 ** operation is allowed to continue normally.  ^If the commit hook
   5005 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
   5006 ** ^The rollback hook is invoked on a rollback that results from a commit
   5007 ** hook returning non-zero, just as it would be with any other rollback.
   5008 **
   5009 ** ^For the purposes of this API, a transaction is said to have been
   5010 ** rolled back if an explicit "ROLLBACK" statement is executed, or
   5011 ** an error or constraint causes an implicit rollback to occur.
   5012 ** ^The rollback callback is not invoked if a transaction is
   5013 ** automatically rolled back because the database connection is closed.
   5014 **
   5015 ** See also the [sqlite3_update_hook()] interface.
   5016 */
   5017 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
   5018 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
   5019 
   5020 /*
   5021 ** CAPI3REF: Data Change Notification Callbacks
   5022 **
   5023 ** ^The sqlite3_update_hook() interface registers a callback function
   5024 ** with the [database connection] identified by the first argument
   5025 ** to be invoked whenever a row is updated, inserted or deleted in
   5026 ** a rowid table.
   5027 ** ^Any callback set by a previous call to this function
   5028 ** for the same database connection is overridden.
   5029 **
   5030 ** ^The second argument is a pointer to the function to invoke when a
   5031 ** row is updated, inserted or deleted in a rowid table.
   5032 ** ^The first argument to the callback is a copy of the third argument
   5033 ** to sqlite3_update_hook().
   5034 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
   5035 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
   5036 ** to be invoked.
   5037 ** ^The third and fourth arguments to the callback contain pointers to the
   5038 ** database and table name containing the affected row.
   5039 ** ^The final callback parameter is the [rowid] of the row.
   5040 ** ^In the case of an update, this is the [rowid] after the update takes place.
   5041 **
   5042 ** ^(The update hook is not invoked when internal system tables are
   5043 ** modified (i.e. sqlite_master and sqlite_sequence).)^
   5044 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
   5045 **
   5046 ** ^In the current implementation, the update hook
   5047 ** is not invoked when duplication rows are deleted because of an
   5048 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
   5049 ** invoked when rows are deleted using the [truncate optimization].
   5050 ** The exceptions defined in this paragraph might change in a future
   5051 ** release of SQLite.
   5052 **
   5053 ** The update hook implementation must not do anything that will modify
   5054 ** the database connection that invoked the update hook.  Any actions
   5055 ** to modify the database connection must be deferred until after the
   5056 ** completion of the [sqlite3_step()] call that triggered the update hook.
   5057 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   5058 ** database connections for the meaning of "modify" in this paragraph.
   5059 **
   5060 ** ^The sqlite3_update_hook(D,C,P) function
   5061 ** returns the P argument from the previous call
   5062 ** on the same [database connection] D, or NULL for
   5063 ** the first call on D.
   5064 **
   5065 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
   5066 ** interfaces.
   5067 */
   5068 SQLITE_API void *sqlite3_update_hook(
   5069   sqlite3*,
   5070   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   5071   void*
   5072 );
   5073 
   5074 /*
   5075 ** CAPI3REF: Enable Or Disable Shared Pager Cache
   5076 **
   5077 ** ^(This routine enables or disables the sharing of the database cache
   5078 ** and schema data structures between [database connection | connections]
   5079 ** to the same database. Sharing is enabled if the argument is true
   5080 ** and disabled if the argument is false.)^
   5081 **
   5082 ** ^Cache sharing is enabled and disabled for an entire process.
   5083 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
   5084 ** sharing was enabled or disabled for each thread separately.
   5085 **
   5086 ** ^(The cache sharing mode set by this interface effects all subsequent
   5087 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
   5088 ** Existing database connections continue use the sharing mode
   5089 ** that was in effect at the time they were opened.)^
   5090 **
   5091 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
   5092 ** successfully.  An [error code] is returned otherwise.)^
   5093 **
   5094 ** ^Shared cache is disabled by default. But this might change in
   5095 ** future releases of SQLite.  Applications that care about shared
   5096 ** cache setting should set it explicitly.
   5097 **
   5098 ** This interface is threadsafe on processors where writing a
   5099 ** 32-bit integer is atomic.
   5100 **
   5101 ** See Also:  [SQLite Shared-Cache Mode]
   5102 */
   5103 SQLITE_API int sqlite3_enable_shared_cache(int);
   5104 
   5105 /*
   5106 ** CAPI3REF: Attempt To Free Heap Memory
   5107 **
   5108 ** ^The sqlite3_release_memory() interface attempts to free N bytes
   5109 ** of heap memory by deallocating non-essential memory allocations
   5110 ** held by the database library.   Memory used to cache database
   5111 ** pages to improve performance is an example of non-essential memory.
   5112 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
   5113 ** which might be more or less than the amount requested.
   5114 ** ^The sqlite3_release_memory() routine is a no-op returning zero
   5115 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
   5116 **
   5117 ** See also: [sqlite3_db_release_memory()]
   5118 */
   5119 SQLITE_API int sqlite3_release_memory(int);
   5120 
   5121 /*
   5122 ** CAPI3REF: Free Memory Used By A Database Connection
   5123 **
   5124 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
   5125 ** memory as possible from database connection D. Unlike the
   5126 ** [sqlite3_release_memory()] interface, this interface is in effect even
   5127 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
   5128 ** omitted.
   5129 **
   5130 ** See also: [sqlite3_release_memory()]
   5131 */
   5132 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
   5133 
   5134 /*
   5135 ** CAPI3REF: Impose A Limit On Heap Size
   5136 **
   5137 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
   5138 ** soft limit on the amount of heap memory that may be allocated by SQLite.
   5139 ** ^SQLite strives to keep heap memory utilization below the soft heap
   5140 ** limit by reducing the number of pages held in the page cache
   5141 ** as heap memory usages approaches the limit.
   5142 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
   5143 ** below the limit, it will exceed the limit rather than generate
   5144 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
   5145 ** is advisory only.
   5146 **
   5147 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
   5148 ** the soft heap limit prior to the call, or negative in the case of an
   5149 ** error.  ^If the argument N is negative
   5150 ** then no change is made to the soft heap limit.  Hence, the current
   5151 ** size of the soft heap limit can be determined by invoking
   5152 ** sqlite3_soft_heap_limit64() with a negative argument.
   5153 **
   5154 ** ^If the argument N is zero then the soft heap limit is disabled.
   5155 **
   5156 ** ^(The soft heap limit is not enforced in the current implementation
   5157 ** if one or more of following conditions are true:
   5158 **
   5159 ** <ul>
   5160 ** <li> The soft heap limit is set to zero.
   5161 ** <li> Memory accounting is disabled using a combination of the
   5162 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
   5163 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
   5164 ** <li> An alternative page cache implementation is specified using
   5165 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
   5166 ** <li> The page cache allocates from its own memory pool supplied
   5167 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
   5168 **      from the heap.
   5169 ** </ul>)^
   5170 **
   5171 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
   5172 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
   5173 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
   5174 ** the soft heap limit is enforced on every memory allocation.  Without
   5175 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
   5176 ** when memory is allocated by the page cache.  Testing suggests that because
   5177 ** the page cache is the predominate memory user in SQLite, most
   5178 ** applications will achieve adequate soft heap limit enforcement without
   5179 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
   5180 **
   5181 ** The circumstances under which SQLite will enforce the soft heap limit may
   5182 ** changes in future releases of SQLite.
   5183 */
   5184 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
   5185 
   5186 /*
   5187 ** CAPI3REF: Deprecated Soft Heap Limit Interface
   5188 ** DEPRECATED
   5189 **
   5190 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
   5191 ** interface.  This routine is provided for historical compatibility
   5192 ** only.  All new applications should use the
   5193 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
   5194 */
   5195 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
   5196 
   5197 
   5198 /*
   5199 ** CAPI3REF: Extract Metadata About A Column Of A Table
   5200 **
   5201 ** ^This routine returns metadata about a specific column of a specific
   5202 ** database table accessible using the [database connection] handle
   5203 ** passed as the first function argument.
   5204 **
   5205 ** ^The column is identified by the second, third and fourth parameters to
   5206 ** this function. ^The second parameter is either the name of the database
   5207 ** (i.e. "main", "temp", or an attached database) containing the specified
   5208 ** table or NULL. ^If it is NULL, then all attached databases are searched
   5209 ** for the table using the same algorithm used by the database engine to
   5210 ** resolve unqualified table references.
   5211 **
   5212 ** ^The third and fourth parameters to this function are the table and column
   5213 ** name of the desired column, respectively. Neither of these parameters
   5214 ** may be NULL.
   5215 **
   5216 ** ^Metadata is returned by writing to the memory locations passed as the 5th
   5217 ** and subsequent parameters to this function. ^Any of these arguments may be
   5218 ** NULL, in which case the corresponding element of metadata is omitted.
   5219 **
   5220 ** ^(<blockquote>
   5221 ** <table border="1">
   5222 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
   5223 **
   5224 ** <tr><td> 5th <td> const char* <td> Data type
   5225 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
   5226 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
   5227 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
   5228 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
   5229 ** </table>
   5230 ** </blockquote>)^
   5231 **
   5232 ** ^The memory pointed to by the character pointers returned for the
   5233 ** declaration type and collation sequence is valid only until the next
   5234 ** call to any SQLite API function.
   5235 **
   5236 ** ^If the specified table is actually a view, an [error code] is returned.
   5237 **
   5238 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
   5239 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
   5240 ** parameters are set for the explicitly declared column. ^(If there is no
   5241 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
   5242 ** parameters are set as follows:
   5243 **
   5244 ** <pre>
   5245 **     data type: "INTEGER"
   5246 **     collation sequence: "BINARY"
   5247 **     not null: 0
   5248 **     primary key: 1
   5249 **     auto increment: 0
   5250 ** </pre>)^
   5251 **
   5252 ** ^(This function may load one or more schemas from database files. If an
   5253 ** error occurs during this process, or if the requested table or column
   5254 ** cannot be found, an [error code] is returned and an error message left
   5255 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
   5256 **
   5257 ** ^This API is only available if the library was compiled with the
   5258 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
   5259 */
   5260 SQLITE_API int sqlite3_table_column_metadata(
   5261   sqlite3 *db,                /* Connection handle */
   5262   const char *zDbName,        /* Database name or NULL */
   5263   const char *zTableName,     /* Table name */
   5264   const char *zColumnName,    /* Column name */
   5265   char const **pzDataType,    /* OUTPUT: Declared data type */
   5266   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   5267   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   5268   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   5269   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   5270 );
   5271 
   5272 /*
   5273 ** CAPI3REF: Load An Extension
   5274 **
   5275 ** ^This interface loads an SQLite extension library from the named file.
   5276 **
   5277 ** ^The sqlite3_load_extension() interface attempts to load an
   5278 ** [SQLite extension] library contained in the file zFile.  If
   5279 ** the file cannot be loaded directly, attempts are made to load
   5280 ** with various operating-system specific extensions added.
   5281 ** So for example, if "samplelib" cannot be loaded, then names like
   5282 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
   5283 ** be tried also.
   5284 **
   5285 ** ^The entry point is zProc.
   5286 ** ^(zProc may be 0, in which case SQLite will try to come up with an
   5287 ** entry point name on its own.  It first tries "sqlite3_extension_init".
   5288 ** If that does not work, it constructs a name "sqlite3_X_init" where the
   5289 ** X is consists of the lower-case equivalent of all ASCII alphabetic
   5290 ** characters in the filename from the last "/" to the first following
   5291 ** "." and omitting any initial "lib".)^
   5292 ** ^The sqlite3_load_extension() interface returns
   5293 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
   5294 ** ^If an error occurs and pzErrMsg is not 0, then the
   5295 ** [sqlite3_load_extension()] interface shall attempt to
   5296 ** fill *pzErrMsg with error message text stored in memory
   5297 ** obtained from [sqlite3_malloc()]. The calling function
   5298 ** should free this memory by calling [sqlite3_free()].
   5299 **
   5300 ** ^Extension loading must be enabled using
   5301 ** [sqlite3_enable_load_extension()] prior to calling this API,
   5302 ** otherwise an error will be returned.
   5303 **
   5304 ** See also the [load_extension() SQL function].
   5305 */
   5306 SQLITE_API int sqlite3_load_extension(
   5307   sqlite3 *db,          /* Load the extension into this database connection */
   5308   const char *zFile,    /* Name of the shared library containing extension */
   5309   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
   5310   char **pzErrMsg       /* Put error message here if not 0 */
   5311 );
   5312 
   5313 /*
   5314 ** CAPI3REF: Enable Or Disable Extension Loading
   5315 **
   5316 ** ^So as not to open security holes in older applications that are
   5317 ** unprepared to deal with [extension loading], and as a means of disabling
   5318 ** [extension loading] while evaluating user-entered SQL, the following API
   5319 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
   5320 **
   5321 ** ^Extension loading is off by default.
   5322 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
   5323 ** to turn extension loading on and call it with onoff==0 to turn
   5324 ** it back off again.
   5325 */
   5326 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
   5327 
   5328 /*
   5329 ** CAPI3REF: Automatically Load Statically Linked Extensions
   5330 **
   5331 ** ^This interface causes the xEntryPoint() function to be invoked for
   5332 ** each new [database connection] that is created.  The idea here is that
   5333 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
   5334 ** that is to be automatically loaded into all new database connections.
   5335 **
   5336 ** ^(Even though the function prototype shows that xEntryPoint() takes
   5337 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
   5338 ** arguments and expects and integer result as if the signature of the
   5339 ** entry point where as follows:
   5340 **
   5341 ** <blockquote><pre>
   5342 ** &nbsp;  int xEntryPoint(
   5343 ** &nbsp;    sqlite3 *db,
   5344 ** &nbsp;    const char **pzErrMsg,
   5345 ** &nbsp;    const struct sqlite3_api_routines *pThunk
   5346 ** &nbsp;  );
   5347 ** </pre></blockquote>)^
   5348 **
   5349 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
   5350 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
   5351 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
   5352 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
   5353 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
   5354 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
   5355 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
   5356 **
   5357 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
   5358 ** on the list of automatic extensions is a harmless no-op. ^No entry point
   5359 ** will be called more than once for each database connection that is opened.
   5360 **
   5361 ** See also: [sqlite3_reset_auto_extension()]
   5362 ** and [sqlite3_cancel_auto_extension()]
   5363 */
   5364 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
   5365 
   5366 /*
   5367 ** CAPI3REF: Cancel Automatic Extension Loading
   5368 **
   5369 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
   5370 ** initialization routine X that was registered using a prior call to
   5371 ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
   5372 ** routine returns 1 if initialization routine X was successfully
   5373 ** unregistered and it returns 0 if X was not on the list of initialization
   5374 ** routines.
   5375 */
   5376 SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
   5377 
   5378 /*
   5379 ** CAPI3REF: Reset Automatic Extension Loading
   5380 **
   5381 ** ^This interface disables all automatic extensions previously
   5382 ** registered using [sqlite3_auto_extension()].
   5383 */
   5384 SQLITE_API void sqlite3_reset_auto_extension(void);
   5385 
   5386 /*
   5387 ** The interface to the virtual-table mechanism is currently considered
   5388 ** to be experimental.  The interface might change in incompatible ways.
   5389 ** If this is a problem for you, do not use the interface at this time.
   5390 **
   5391 ** When the virtual-table mechanism stabilizes, we will declare the
   5392 ** interface fixed, support it indefinitely, and remove this comment.
   5393 */
   5394 
   5395 /*
   5396 ** Structures used by the virtual table interface
   5397 */
   5398 typedef struct sqlite3_vtab sqlite3_vtab;
   5399 typedef struct sqlite3_index_info sqlite3_index_info;
   5400 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
   5401 typedef struct sqlite3_module sqlite3_module;
   5402 
   5403 /*
   5404 ** CAPI3REF: Virtual Table Object
   5405 ** KEYWORDS: sqlite3_module {virtual table module}
   5406 **
   5407 ** This structure, sometimes called a "virtual table module",
   5408 ** defines the implementation of a [virtual tables].
   5409 ** This structure consists mostly of methods for the module.
   5410 **
   5411 ** ^A virtual table module is created by filling in a persistent
   5412 ** instance of this structure and passing a pointer to that instance
   5413 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
   5414 ** ^The registration remains valid until it is replaced by a different
   5415 ** module or until the [database connection] closes.  The content
   5416 ** of this structure must not change while it is registered with
   5417 ** any database connection.
   5418 */
   5419 struct sqlite3_module {
   5420   int iVersion;
   5421   int (*xCreate)(sqlite3*, void *pAux,
   5422                int argc, const char *const*argv,
   5423                sqlite3_vtab **ppVTab, char**);
   5424   int (*xConnect)(sqlite3*, void *pAux,
   5425                int argc, const char *const*argv,
   5426                sqlite3_vtab **ppVTab, char**);
   5427   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
   5428   int (*xDisconnect)(sqlite3_vtab *pVTab);
   5429   int (*xDestroy)(sqlite3_vtab *pVTab);
   5430   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
   5431   int (*xClose)(sqlite3_vtab_cursor*);
   5432   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
   5433                 int argc, sqlite3_value **argv);
   5434   int (*xNext)(sqlite3_vtab_cursor*);
   5435   int (*xEof)(sqlite3_vtab_cursor*);
   5436   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
   5437   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
   5438   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
   5439   int (*xBegin)(sqlite3_vtab *pVTab);
   5440   int (*xSync)(sqlite3_vtab *pVTab);
   5441   int (*xCommit)(sqlite3_vtab *pVTab);
   5442   int (*xRollback)(sqlite3_vtab *pVTab);
   5443   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
   5444                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
   5445                        void **ppArg);
   5446   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
   5447   /* The methods above are in version 1 of the sqlite_module object. Those
   5448   ** below are for version 2 and greater. */
   5449   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
   5450   int (*xRelease)(sqlite3_vtab *pVTab, int);
   5451   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
   5452 };
   5453 
   5454 /*
   5455 ** CAPI3REF: Virtual Table Indexing Information
   5456 ** KEYWORDS: sqlite3_index_info
   5457 **
   5458 ** The sqlite3_index_info structure and its substructures is used as part
   5459 ** of the [virtual table] interface to
   5460 ** pass information into and receive the reply from the [xBestIndex]
   5461 ** method of a [virtual table module].  The fields under **Inputs** are the
   5462 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
   5463 ** results into the **Outputs** fields.
   5464 **
   5465 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
   5466 **
   5467 ** <blockquote>column OP expr</blockquote>
   5468 **
   5469 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
   5470 ** stored in aConstraint[].op using one of the
   5471 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
   5472 ** ^(The index of the column is stored in
   5473 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
   5474 ** expr on the right-hand side can be evaluated (and thus the constraint
   5475 ** is usable) and false if it cannot.)^
   5476 **
   5477 ** ^The optimizer automatically inverts terms of the form "expr OP column"
   5478 ** and makes other simplifications to the WHERE clause in an attempt to
   5479 ** get as many WHERE clause terms into the form shown above as possible.
   5480 ** ^The aConstraint[] array only reports WHERE clause terms that are
   5481 ** relevant to the particular virtual table being queried.
   5482 **
   5483 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
   5484 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
   5485 **
   5486 ** The [xBestIndex] method must fill aConstraintUsage[] with information
   5487 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
   5488 ** the right-hand side of the corresponding aConstraint[] is evaluated
   5489 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
   5490 ** is true, then the constraint is assumed to be fully handled by the
   5491 ** virtual table and is not checked again by SQLite.)^
   5492 **
   5493 ** ^The idxNum and idxPtr values are recorded and passed into the
   5494 ** [xFilter] method.
   5495 ** ^[sqlite3_free()] is used to free idxPtr if and only if
   5496 ** needToFreeIdxPtr is true.
   5497 **
   5498 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
   5499 ** the correct order to satisfy the ORDER BY clause so that no separate
   5500 ** sorting step is required.
   5501 **
   5502 ** ^The estimatedCost value is an estimate of the cost of a particular
   5503 ** strategy. A cost of N indicates that the cost of the strategy is similar
   5504 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
   5505 ** indicates that the expense of the operation is similar to that of a
   5506 ** binary search on a unique indexed field of an SQLite table with N rows.
   5507 **
   5508 ** ^The estimatedRows value is an estimate of the number of rows that
   5509 ** will be returned by the strategy.
   5510 **
   5511 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
   5512 ** structure for SQLite version 3.8.2. If a virtual table extension is
   5513 ** used with an SQLite version earlier than 3.8.2, the results of attempting
   5514 ** to read or write the estimatedRows field are undefined (but are likely
   5515 ** to included crashing the application). The estimatedRows field should
   5516 ** therefore only be used if [sqlite3_libversion_number()] returns a
   5517 ** value greater than or equal to 3008002.
   5518 */
   5519 struct sqlite3_index_info {
   5520   /* Inputs */
   5521   int nConstraint;           /* Number of entries in aConstraint */
   5522   struct sqlite3_index_constraint {
   5523      int iColumn;              /* Column on left-hand side of constraint */
   5524      unsigned char op;         /* Constraint operator */
   5525      unsigned char usable;     /* True if this constraint is usable */
   5526      int iTermOffset;          /* Used internally - xBestIndex should ignore */
   5527   } *aConstraint;            /* Table of WHERE clause constraints */
   5528   int nOrderBy;              /* Number of terms in the ORDER BY clause */
   5529   struct sqlite3_index_orderby {
   5530      int iColumn;              /* Column number */
   5531      unsigned char desc;       /* True for DESC.  False for ASC. */
   5532   } *aOrderBy;               /* The ORDER BY clause */
   5533   /* Outputs */
   5534   struct sqlite3_index_constraint_usage {
   5535     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
   5536     unsigned char omit;      /* Do not code a test for this constraint */
   5537   } *aConstraintUsage;
   5538   int idxNum;                /* Number used to identify the index */
   5539   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
   5540   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
   5541   int orderByConsumed;       /* True if output is already ordered */
   5542   double estimatedCost;           /* Estimated cost of using this index */
   5543   /* Fields below are only available in SQLite 3.8.2 and later */
   5544   sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
   5545 };
   5546 
   5547 /*
   5548 ** CAPI3REF: Virtual Table Constraint Operator Codes
   5549 **
   5550 ** These macros defined the allowed values for the
   5551 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
   5552 ** an operator that is part of a constraint term in the wHERE clause of
   5553 ** a query that uses a [virtual table].
   5554 */
   5555 #define SQLITE_INDEX_CONSTRAINT_EQ    2
   5556 #define SQLITE_INDEX_CONSTRAINT_GT    4
   5557 #define SQLITE_INDEX_CONSTRAINT_LE    8
   5558 #define SQLITE_INDEX_CONSTRAINT_LT    16
   5559 #define SQLITE_INDEX_CONSTRAINT_GE    32
   5560 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
   5561 
   5562 /*
   5563 ** CAPI3REF: Register A Virtual Table Implementation
   5564 **
   5565 ** ^These routines are used to register a new [virtual table module] name.
   5566 ** ^Module names must be registered before
   5567 ** creating a new [virtual table] using the module and before using a
   5568 ** preexisting [virtual table] for the module.
   5569 **
   5570 ** ^The module name is registered on the [database connection] specified
   5571 ** by the first parameter.  ^The name of the module is given by the
   5572 ** second parameter.  ^The third parameter is a pointer to
   5573 ** the implementation of the [virtual table module].   ^The fourth
   5574 ** parameter is an arbitrary client data pointer that is passed through
   5575 ** into the [xCreate] and [xConnect] methods of the virtual table module
   5576 ** when a new virtual table is be being created or reinitialized.
   5577 **
   5578 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
   5579 ** is a pointer to a destructor for the pClientData.  ^SQLite will
   5580 ** invoke the destructor function (if it is not NULL) when SQLite
   5581 ** no longer needs the pClientData pointer.  ^The destructor will also
   5582 ** be invoked if the call to sqlite3_create_module_v2() fails.
   5583 ** ^The sqlite3_create_module()
   5584 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
   5585 ** destructor.
   5586 */
   5587 SQLITE_API int sqlite3_create_module(
   5588   sqlite3 *db,               /* SQLite connection to register module with */
   5589   const char *zName,         /* Name of the module */
   5590   const sqlite3_module *p,   /* Methods for the module */
   5591   void *pClientData          /* Client data for xCreate/xConnect */
   5592 );
   5593 SQLITE_API int sqlite3_create_module_v2(
   5594   sqlite3 *db,               /* SQLite connection to register module with */
   5595   const char *zName,         /* Name of the module */
   5596   const sqlite3_module *p,   /* Methods for the module */
   5597   void *pClientData,         /* Client data for xCreate/xConnect */
   5598   void(*xDestroy)(void*)     /* Module destructor function */
   5599 );
   5600 
   5601 /*
   5602 ** CAPI3REF: Virtual Table Instance Object
   5603 ** KEYWORDS: sqlite3_vtab
   5604 **
   5605 ** Every [virtual table module] implementation uses a subclass
   5606 ** of this object to describe a particular instance
   5607 ** of the [virtual table].  Each subclass will
   5608 ** be tailored to the specific needs of the module implementation.
   5609 ** The purpose of this superclass is to define certain fields that are
   5610 ** common to all module implementations.
   5611 **
   5612 ** ^Virtual tables methods can set an error message by assigning a
   5613 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
   5614 ** take care that any prior string is freed by a call to [sqlite3_free()]
   5615 ** prior to assigning a new string to zErrMsg.  ^After the error message
   5616 ** is delivered up to the client application, the string will be automatically
   5617 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
   5618 */
   5619 struct sqlite3_vtab {
   5620   const sqlite3_module *pModule;  /* The module for this virtual table */
   5621   int nRef;                       /* NO LONGER USED */
   5622   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
   5623   /* Virtual table implementations will typically add additional fields */
   5624 };
   5625 
   5626 /*
   5627 ** CAPI3REF: Virtual Table Cursor Object
   5628 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
   5629 **
   5630 ** Every [virtual table module] implementation uses a subclass of the
   5631 ** following structure to describe cursors that point into the
   5632 ** [virtual table] and are used
   5633 ** to loop through the virtual table.  Cursors are created using the
   5634 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
   5635 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
   5636 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
   5637 ** of the module.  Each module implementation will define
   5638 ** the content of a cursor structure to suit its own needs.
   5639 **
   5640 ** This superclass exists in order to define fields of the cursor that
   5641 ** are common to all implementations.
   5642 */
   5643 struct sqlite3_vtab_cursor {
   5644   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
   5645   /* Virtual table implementations will typically add additional fields */
   5646 };
   5647 
   5648 /*
   5649 ** CAPI3REF: Declare The Schema Of A Virtual Table
   5650 **
   5651 ** ^The [xCreate] and [xConnect] methods of a
   5652 ** [virtual table module] call this interface
   5653 ** to declare the format (the names and datatypes of the columns) of
   5654 ** the virtual tables they implement.
   5655 */
   5656 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
   5657 
   5658 /*
   5659 ** CAPI3REF: Overload A Function For A Virtual Table
   5660 **
   5661 ** ^(Virtual tables can provide alternative implementations of functions
   5662 ** using the [xFindFunction] method of the [virtual table module].
   5663 ** But global versions of those functions
   5664 ** must exist in order to be overloaded.)^
   5665 **
   5666 ** ^(This API makes sure a global version of a function with a particular
   5667 ** name and number of parameters exists.  If no such function exists
   5668 ** before this API is called, a new function is created.)^  ^The implementation
   5669 ** of the new function always causes an exception to be thrown.  So
   5670 ** the new function is not good for anything by itself.  Its only
   5671 ** purpose is to be a placeholder function that can be overloaded
   5672 ** by a [virtual table].
   5673 */
   5674 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
   5675 
   5676 /*
   5677 ** The interface to the virtual-table mechanism defined above (back up
   5678 ** to a comment remarkably similar to this one) is currently considered
   5679 ** to be experimental.  The interface might change in incompatible ways.
   5680 ** If this is a problem for you, do not use the interface at this time.
   5681 **
   5682 ** When the virtual-table mechanism stabilizes, we will declare the
   5683 ** interface fixed, support it indefinitely, and remove this comment.
   5684 */
   5685 
   5686 /*
   5687 ** CAPI3REF: A Handle To An Open BLOB
   5688 ** KEYWORDS: {BLOB handle} {BLOB handles}
   5689 **
   5690 ** An instance of this object represents an open BLOB on which
   5691 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
   5692 ** ^Objects of this type are created by [sqlite3_blob_open()]
   5693 ** and destroyed by [sqlite3_blob_close()].
   5694 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
   5695 ** can be used to read or write small subsections of the BLOB.
   5696 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
   5697 */
   5698 typedef struct sqlite3_blob sqlite3_blob;
   5699 
   5700 /*
   5701 ** CAPI3REF: Open A BLOB For Incremental I/O
   5702 **
   5703 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
   5704 ** in row iRow, column zColumn, table zTable in database zDb;
   5705 ** in other words, the same BLOB that would be selected by:
   5706 **
   5707 ** <pre>
   5708 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
   5709 ** </pre>)^
   5710 **
   5711 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
   5712 ** and write access. ^If it is zero, the BLOB is opened for read access.
   5713 ** ^It is not possible to open a column that is part of an index or primary
   5714 ** key for writing. ^If [foreign key constraints] are enabled, it is
   5715 ** not possible to open a column that is part of a [child key] for writing.
   5716 **
   5717 ** ^Note that the database name is not the filename that contains
   5718 ** the database but rather the symbolic name of the database that
   5719 ** appears after the AS keyword when the database is connected using [ATTACH].
   5720 ** ^For the main database file, the database name is "main".
   5721 ** ^For TEMP tables, the database name is "temp".
   5722 **
   5723 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
   5724 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
   5725 ** to be a null pointer.)^
   5726 ** ^This function sets the [database connection] error code and message
   5727 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
   5728 ** functions. ^Note that the *ppBlob variable is always initialized in a
   5729 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
   5730 ** regardless of the success or failure of this routine.
   5731 **
   5732 ** ^(If the row that a BLOB handle points to is modified by an
   5733 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
   5734 ** then the BLOB handle is marked as "expired".
   5735 ** This is true if any column of the row is changed, even a column
   5736 ** other than the one the BLOB handle is open on.)^
   5737 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
   5738 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
   5739 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
   5740 ** rolled back by the expiration of the BLOB.  Such changes will eventually
   5741 ** commit if the transaction continues to completion.)^
   5742 **
   5743 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
   5744 ** the opened blob.  ^The size of a blob may not be changed by this
   5745 ** interface.  Use the [UPDATE] SQL command to change the size of a
   5746 ** blob.
   5747 **
   5748 ** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
   5749 ** table.  Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
   5750 **
   5751 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
   5752 ** and the built-in [zeroblob] SQL function can be used, if desired,
   5753 ** to create an empty, zero-filled blob in which to read or write using
   5754 ** this interface.
   5755 **
   5756 ** To avoid a resource leak, every open [BLOB handle] should eventually
   5757 ** be released by a call to [sqlite3_blob_close()].
   5758 */
   5759 SQLITE_API int sqlite3_blob_open(
   5760   sqlite3*,
   5761   const char *zDb,
   5762   const char *zTable,
   5763   const char *zColumn,
   5764   sqlite3_int64 iRow,
   5765   int flags,
   5766   sqlite3_blob **ppBlob
   5767 );
   5768 
   5769 /*
   5770 ** CAPI3REF: Move a BLOB Handle to a New Row
   5771 **
   5772 ** ^This function is used to move an existing blob handle so that it points
   5773 ** to a different row of the same database table. ^The new row is identified
   5774 ** by the rowid value passed as the second argument. Only the row can be
   5775 ** changed. ^The database, table and column on which the blob handle is open
   5776 ** remain the same. Moving an existing blob handle to a new row can be
   5777 ** faster than closing the existing handle and opening a new one.
   5778 **
   5779 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
   5780 ** it must exist and there must be either a blob or text value stored in
   5781 ** the nominated column.)^ ^If the new row is not present in the table, or if
   5782 ** it does not contain a blob or text value, or if another error occurs, an
   5783 ** SQLite error code is returned and the blob handle is considered aborted.
   5784 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
   5785 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
   5786 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
   5787 ** always returns zero.
   5788 **
   5789 ** ^This function sets the database handle error code and message.
   5790 */
   5791 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
   5792 
   5793 /*
   5794 ** CAPI3REF: Close A BLOB Handle
   5795 **
   5796 ** ^Closes an open [BLOB handle].
   5797 **
   5798 ** ^Closing a BLOB shall cause the current transaction to commit
   5799 ** if there are no other BLOBs, no pending prepared statements, and the
   5800 ** database connection is in [autocommit mode].
   5801 ** ^If any writes were made to the BLOB, they might be held in cache
   5802 ** until the close operation if they will fit.
   5803 **
   5804 ** ^(Closing the BLOB often forces the changes
   5805 ** out to disk and so if any I/O errors occur, they will likely occur
   5806 ** at the time when the BLOB is closed.  Any errors that occur during
   5807 ** closing are reported as a non-zero return value.)^
   5808 **
   5809 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
   5810 ** an error code, the BLOB is still closed.)^
   5811 **
   5812 ** ^Calling this routine with a null pointer (such as would be returned
   5813 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
   5814 */
   5815 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
   5816 
   5817 /*
   5818 ** CAPI3REF: Return The Size Of An Open BLOB
   5819 **
   5820 ** ^Returns the size in bytes of the BLOB accessible via the
   5821 ** successfully opened [BLOB handle] in its only argument.  ^The
   5822 ** incremental blob I/O routines can only read or overwriting existing
   5823 ** blob content; they cannot change the size of a blob.
   5824 **
   5825 ** This routine only works on a [BLOB handle] which has been created
   5826 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5827 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5828 ** to this routine results in undefined and probably undesirable behavior.
   5829 */
   5830 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
   5831 
   5832 /*
   5833 ** CAPI3REF: Read Data From A BLOB Incrementally
   5834 **
   5835 ** ^(This function is used to read data from an open [BLOB handle] into a
   5836 ** caller-supplied buffer. N bytes of data are copied into buffer Z
   5837 ** from the open BLOB, starting at offset iOffset.)^
   5838 **
   5839 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5840 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
   5841 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
   5842 ** ^The size of the blob (and hence the maximum value of N+iOffset)
   5843 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5844 **
   5845 ** ^An attempt to read from an expired [BLOB handle] fails with an
   5846 ** error code of [SQLITE_ABORT].
   5847 **
   5848 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
   5849 ** Otherwise, an [error code] or an [extended error code] is returned.)^
   5850 **
   5851 ** This routine only works on a [BLOB handle] which has been created
   5852 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5853 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5854 ** to this routine results in undefined and probably undesirable behavior.
   5855 **
   5856 ** See also: [sqlite3_blob_write()].
   5857 */
   5858 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
   5859 
   5860 /*
   5861 ** CAPI3REF: Write Data Into A BLOB Incrementally
   5862 **
   5863 ** ^This function is used to write data into an open [BLOB handle] from a
   5864 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
   5865 ** into the open BLOB, starting at offset iOffset.
   5866 **
   5867 ** ^If the [BLOB handle] passed as the first argument was not opened for
   5868 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
   5869 ** this function returns [SQLITE_READONLY].
   5870 **
   5871 ** ^This function may only modify the contents of the BLOB; it is
   5872 ** not possible to increase the size of a BLOB using this API.
   5873 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5874 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
   5875 ** less than zero [SQLITE_ERROR] is returned and no data is written.
   5876 ** The size of the BLOB (and hence the maximum value of N+iOffset)
   5877 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5878 **
   5879 ** ^An attempt to write to an expired [BLOB handle] fails with an
   5880 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
   5881 ** before the [BLOB handle] expired are not rolled back by the
   5882 ** expiration of the handle, though of course those changes might
   5883 ** have been overwritten by the statement that expired the BLOB handle
   5884 ** or by other independent statements.
   5885 **
   5886 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
   5887 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
   5888 **
   5889 ** This routine only works on a [BLOB handle] which has been created
   5890 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5891 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5892 ** to this routine results in undefined and probably undesirable behavior.
   5893 **
   5894 ** See also: [sqlite3_blob_read()].
   5895 */
   5896 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
   5897 
   5898 /*
   5899 ** CAPI3REF: Virtual File System Objects
   5900 **
   5901 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
   5902 ** that SQLite uses to interact
   5903 ** with the underlying operating system.  Most SQLite builds come with a
   5904 ** single default VFS that is appropriate for the host computer.
   5905 ** New VFSes can be registered and existing VFSes can be unregistered.
   5906 ** The following interfaces are provided.
   5907 **
   5908 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
   5909 ** ^Names are case sensitive.
   5910 ** ^Names are zero-terminated UTF-8 strings.
   5911 ** ^If there is no match, a NULL pointer is returned.
   5912 ** ^If zVfsName is NULL then the default VFS is returned.
   5913 **
   5914 ** ^New VFSes are registered with sqlite3_vfs_register().
   5915 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
   5916 ** ^The same VFS can be registered multiple times without injury.
   5917 ** ^To make an existing VFS into the default VFS, register it again
   5918 ** with the makeDflt flag set.  If two different VFSes with the
   5919 ** same name are registered, the behavior is undefined.  If a
   5920 ** VFS is registered with a name that is NULL or an empty string,
   5921 ** then the behavior is undefined.
   5922 **
   5923 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
   5924 ** ^(If the default VFS is unregistered, another VFS is chosen as
   5925 ** the default.  The choice for the new VFS is arbitrary.)^
   5926 */
   5927 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
   5928 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
   5929 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
   5930 
   5931 /*
   5932 ** CAPI3REF: Mutexes
   5933 **
   5934 ** The SQLite core uses these routines for thread
   5935 ** synchronization. Though they are intended for internal
   5936 ** use by SQLite, code that links against SQLite is
   5937 ** permitted to use any of these routines.
   5938 **
   5939 ** The SQLite source code contains multiple implementations
   5940 ** of these mutex routines.  An appropriate implementation
   5941 ** is selected automatically at compile-time.  ^(The following
   5942 ** implementations are available in the SQLite core:
   5943 **
   5944 ** <ul>
   5945 ** <li>   SQLITE_MUTEX_PTHREADS
   5946 ** <li>   SQLITE_MUTEX_W32
   5947 ** <li>   SQLITE_MUTEX_NOOP
   5948 ** </ul>)^
   5949 **
   5950 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
   5951 ** that does no real locking and is appropriate for use in
   5952 ** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
   5953 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
   5954 ** and Windows.
   5955 **
   5956 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
   5957 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
   5958 ** implementation is included with the library. In this case the
   5959 ** application must supply a custom mutex implementation using the
   5960 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
   5961 ** before calling sqlite3_initialize() or any other public sqlite3_
   5962 ** function that calls sqlite3_initialize().)^
   5963 **
   5964 ** ^The sqlite3_mutex_alloc() routine allocates a new
   5965 ** mutex and returns a pointer to it. ^If it returns NULL
   5966 ** that means that a mutex could not be allocated.  ^SQLite
   5967 ** will unwind its stack and return an error.  ^(The argument
   5968 ** to sqlite3_mutex_alloc() is one of these integer constants:
   5969 **
   5970 ** <ul>
   5971 ** <li>  SQLITE_MUTEX_FAST
   5972 ** <li>  SQLITE_MUTEX_RECURSIVE
   5973 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   5974 ** <li>  SQLITE_MUTEX_STATIC_MEM
   5975 ** <li>  SQLITE_MUTEX_STATIC_OPEN
   5976 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   5977 ** <li>  SQLITE_MUTEX_STATIC_LRU
   5978 ** <li>  SQLITE_MUTEX_STATIC_PMEM
   5979 ** <li>  SQLITE_MUTEX_STATIC_APP1
   5980 ** <li>  SQLITE_MUTEX_STATIC_APP2
   5981 ** </ul>)^
   5982 **
   5983 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
   5984 ** cause sqlite3_mutex_alloc() to create
   5985 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   5986 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   5987 ** The mutex implementation does not need to make a distinction
   5988 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   5989 ** not want to.  ^SQLite will only request a recursive mutex in
   5990 ** cases where it really needs one.  ^If a faster non-recursive mutex
   5991 ** implementation is available on the host platform, the mutex subsystem
   5992 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   5993 **
   5994 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
   5995 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
   5996 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
   5997 ** used by the current version of SQLite.  Future versions of SQLite
   5998 ** may add additional static mutexes.  Static mutexes are for internal
   5999 ** use by SQLite only.  Applications that use SQLite mutexes should
   6000 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   6001 ** SQLITE_MUTEX_RECURSIVE.
   6002 **
   6003 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   6004 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   6005 ** returns a different mutex on every call.  ^But for the static
   6006 ** mutex types, the same mutex is returned on every call that has
   6007 ** the same type number.
   6008 **
   6009 ** ^The sqlite3_mutex_free() routine deallocates a previously
   6010 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
   6011 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
   6012 ** use when they are deallocated.  Attempting to deallocate a static
   6013 ** mutex results in undefined behavior.  ^SQLite never deallocates
   6014 ** a static mutex.
   6015 **
   6016 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   6017 ** to enter a mutex.  ^If another thread is already within the mutex,
   6018 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   6019 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
   6020 ** upon successful entry.  ^(Mutexes created using
   6021 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
   6022 ** In such cases the,
   6023 ** mutex must be exited an equal number of times before another thread
   6024 ** can enter.)^  ^(If the same thread tries to enter any other
   6025 ** kind of mutex more than once, the behavior is undefined.
   6026 ** SQLite will never exhibit
   6027 ** such behavior in its own use of mutexes.)^
   6028 **
   6029 ** ^(Some systems (for example, Windows 95) do not support the operation
   6030 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
   6031 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
   6032 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
   6033 **
   6034 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
   6035 ** previously entered by the same thread.   ^(The behavior
   6036 ** is undefined if the mutex is not currently entered by the
   6037 ** calling thread or is not currently allocated.  SQLite will
   6038 ** never do either.)^
   6039 **
   6040 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
   6041 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
   6042 ** behave as no-ops.
   6043 **
   6044 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
   6045 */
   6046 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
   6047 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
   6048 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
   6049 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
   6050 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
   6051 
   6052 /*
   6053 ** CAPI3REF: Mutex Methods Object
   6054 **
   6055 ** An instance of this structure defines the low-level routines
   6056 ** used to allocate and use mutexes.
   6057 **
   6058 ** Usually, the default mutex implementations provided by SQLite are
   6059 ** sufficient, however the user has the option of substituting a custom
   6060 ** implementation for specialized deployments or systems for which SQLite
   6061 ** does not provide a suitable implementation. In this case, the user
   6062 ** creates and populates an instance of this structure to pass
   6063 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
   6064 ** Additionally, an instance of this structure can be used as an
   6065 ** output variable when querying the system for the current mutex
   6066 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
   6067 **
   6068 ** ^The xMutexInit method defined by this structure is invoked as
   6069 ** part of system initialization by the sqlite3_initialize() function.
   6070 ** ^The xMutexInit routine is called by SQLite exactly once for each
   6071 ** effective call to [sqlite3_initialize()].
   6072 **
   6073 ** ^The xMutexEnd method defined by this structure is invoked as
   6074 ** part of system shutdown by the sqlite3_shutdown() function. The
   6075 ** implementation of this method is expected to release all outstanding
   6076 ** resources obtained by the mutex methods implementation, especially
   6077 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
   6078 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
   6079 **
   6080 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
   6081 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
   6082 ** xMutexNotheld) implement the following interfaces (respectively):
   6083 **
   6084 ** <ul>
   6085 **   <li>  [sqlite3_mutex_alloc()] </li>
   6086 **   <li>  [sqlite3_mutex_free()] </li>
   6087 **   <li>  [sqlite3_mutex_enter()] </li>
   6088 **   <li>  [sqlite3_mutex_try()] </li>
   6089 **   <li>  [sqlite3_mutex_leave()] </li>
   6090 **   <li>  [sqlite3_mutex_held()] </li>
   6091 **   <li>  [sqlite3_mutex_notheld()] </li>
   6092 ** </ul>)^
   6093 **
   6094 ** The only difference is that the public sqlite3_XXX functions enumerated
   6095 ** above silently ignore any invocations that pass a NULL pointer instead
   6096 ** of a valid mutex handle. The implementations of the methods defined
   6097 ** by this structure are not required to handle this case, the results
   6098 ** of passing a NULL pointer instead of a valid mutex handle are undefined
   6099 ** (i.e. it is acceptable to provide an implementation that segfaults if
   6100 ** it is passed a NULL pointer).
   6101 **
   6102 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
   6103 ** invoke xMutexInit() multiple times within the same process and without
   6104 ** intervening calls to xMutexEnd().  Second and subsequent calls to
   6105 ** xMutexInit() must be no-ops.
   6106 **
   6107 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
   6108 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
   6109 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
   6110 ** memory allocation for a fast or recursive mutex.
   6111 **
   6112 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
   6113 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
   6114 ** If xMutexInit fails in any way, it is expected to clean up after itself
   6115 ** prior to returning.
   6116 */
   6117 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
   6118 struct sqlite3_mutex_methods {
   6119   int (*xMutexInit)(void);
   6120   int (*xMutexEnd)(void);
   6121   sqlite3_mutex *(*xMutexAlloc)(int);
   6122   void (*xMutexFree)(sqlite3_mutex *);
   6123   void (*xMutexEnter)(sqlite3_mutex *);
   6124   int (*xMutexTry)(sqlite3_mutex *);
   6125   void (*xMutexLeave)(sqlite3_mutex *);
   6126   int (*xMutexHeld)(sqlite3_mutex *);
   6127   int (*xMutexNotheld)(sqlite3_mutex *);
   6128 };
   6129 
   6130 /*
   6131 ** CAPI3REF: Mutex Verification Routines
   6132 **
   6133 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
   6134 ** are intended for use inside assert() statements.  ^The SQLite core
   6135 ** never uses these routines except inside an assert() and applications
   6136 ** are advised to follow the lead of the core.  ^The SQLite core only
   6137 ** provides implementations for these routines when it is compiled
   6138 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
   6139 ** are only required to provide these routines if SQLITE_DEBUG is
   6140 ** defined and if NDEBUG is not defined.
   6141 **
   6142 ** ^These routines should return true if the mutex in their argument
   6143 ** is held or not held, respectively, by the calling thread.
   6144 **
   6145 ** ^The implementation is not required to provide versions of these
   6146 ** routines that actually work. If the implementation does not provide working
   6147 ** versions of these routines, it should at least provide stubs that always
   6148 ** return true so that one does not get spurious assertion failures.
   6149 **
   6150 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
   6151 ** the routine should return 1.   This seems counter-intuitive since
   6152 ** clearly the mutex cannot be held if it does not exist.  But
   6153 ** the reason the mutex does not exist is because the build is not
   6154 ** using mutexes.  And we do not want the assert() containing the
   6155 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
   6156 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
   6157 ** interface should also return 1 when given a NULL pointer.
   6158 */
   6159 #ifndef NDEBUG
   6160 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
   6161 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
   6162 #endif
   6163 
   6164 /*
   6165 ** CAPI3REF: Mutex Types
   6166 **
   6167 ** The [sqlite3_mutex_alloc()] interface takes a single argument
   6168 ** which is one of these integer constants.
   6169 **
   6170 ** The set of static mutexes may change from one SQLite release to the
   6171 ** next.  Applications that override the built-in mutex logic must be
   6172 ** prepared to accommodate additional static mutexes.
   6173 */
   6174 #define SQLITE_MUTEX_FAST             0
   6175 #define SQLITE_MUTEX_RECURSIVE        1
   6176 #define SQLITE_MUTEX_STATIC_MASTER    2
   6177 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
   6178 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
   6179 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
   6180 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
   6181 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
   6182 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
   6183 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
   6184 #define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
   6185 #define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
   6186 #define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
   6187 
   6188 /*
   6189 ** CAPI3REF: Retrieve the mutex for a database connection
   6190 **
   6191 ** ^This interface returns a pointer the [sqlite3_mutex] object that
   6192 ** serializes access to the [database connection] given in the argument
   6193 ** when the [threading mode] is Serialized.
   6194 ** ^If the [threading mode] is Single-thread or Multi-thread then this
   6195 ** routine returns a NULL pointer.
   6196 */
   6197 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
   6198 
   6199 /*
   6200 ** CAPI3REF: Low-Level Control Of Database Files
   6201 **
   6202 ** ^The [sqlite3_file_control()] interface makes a direct call to the
   6203 ** xFileControl method for the [sqlite3_io_methods] object associated
   6204 ** with a particular database identified by the second argument. ^The
   6205 ** name of the database is "main" for the main database or "temp" for the
   6206 ** TEMP database, or the name that appears after the AS keyword for
   6207 ** databases that are added using the [ATTACH] SQL command.
   6208 ** ^A NULL pointer can be used in place of "main" to refer to the
   6209 ** main database file.
   6210 ** ^The third and fourth parameters to this routine
   6211 ** are passed directly through to the second and third parameters of
   6212 ** the xFileControl method.  ^The return value of the xFileControl
   6213 ** method becomes the return value of this routine.
   6214 **
   6215 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
   6216 ** a pointer to the underlying [sqlite3_file] object to be written into
   6217 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
   6218 ** case is a short-circuit path which does not actually invoke the
   6219 ** underlying sqlite3_io_methods.xFileControl method.
   6220 **
   6221 ** ^If the second parameter (zDbName) does not match the name of any
   6222 ** open database file, then SQLITE_ERROR is returned.  ^This error
   6223 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
   6224 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
   6225 ** also return SQLITE_ERROR.  There is no way to distinguish between
   6226 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
   6227 ** xFileControl method.
   6228 **
   6229 ** See also: [SQLITE_FCNTL_LOCKSTATE]
   6230 */
   6231 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
   6232 
   6233 /*
   6234 ** CAPI3REF: Testing Interface
   6235 **
   6236 ** ^The sqlite3_test_control() interface is used to read out internal
   6237 ** state of SQLite and to inject faults into SQLite for testing
   6238 ** purposes.  ^The first parameter is an operation code that determines
   6239 ** the number, meaning, and operation of all subsequent parameters.
   6240 **
   6241 ** This interface is not for use by applications.  It exists solely
   6242 ** for verifying the correct operation of the SQLite library.  Depending
   6243 ** on how the SQLite library is compiled, this interface might not exist.
   6244 **
   6245 ** The details of the operation codes, their meanings, the parameters
   6246 ** they take, and what they do are all subject to change without notice.
   6247 ** Unlike most of the SQLite API, this function is not guaranteed to
   6248 ** operate consistently from one release to the next.
   6249 */
   6250 SQLITE_API int sqlite3_test_control(int op, ...);
   6251 
   6252 /*
   6253 ** CAPI3REF: Testing Interface Operation Codes
   6254 **
   6255 ** These constants are the valid operation code parameters used
   6256 ** as the first argument to [sqlite3_test_control()].
   6257 **
   6258 ** These parameters and their meanings are subject to change
   6259 ** without notice.  These values are for testing purposes only.
   6260 ** Applications should not use any of these parameters or the
   6261 ** [sqlite3_test_control()] interface.
   6262 */
   6263 #define SQLITE_TESTCTRL_FIRST                    5
   6264 #define SQLITE_TESTCTRL_PRNG_SAVE                5
   6265 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
   6266 #define SQLITE_TESTCTRL_PRNG_RESET               7
   6267 #define SQLITE_TESTCTRL_BITVEC_TEST              8
   6268 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
   6269 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
   6270 #define SQLITE_TESTCTRL_PENDING_BYTE            11
   6271 #define SQLITE_TESTCTRL_ASSERT                  12
   6272 #define SQLITE_TESTCTRL_ALWAYS                  13
   6273 #define SQLITE_TESTCTRL_RESERVE                 14
   6274 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
   6275 #define SQLITE_TESTCTRL_ISKEYWORD               16
   6276 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
   6277 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
   6278 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
   6279 #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
   6280 #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
   6281 #define SQLITE_TESTCTRL_BYTEORDER               22
   6282 #define SQLITE_TESTCTRL_ISINIT                  23
   6283 #define SQLITE_TESTCTRL_LAST                    23
   6284 
   6285 /*
   6286 ** CAPI3REF: SQLite Runtime Status
   6287 **
   6288 ** ^This interface is used to retrieve runtime status information
   6289 ** about the performance of SQLite, and optionally to reset various
   6290 ** highwater marks.  ^The first argument is an integer code for
   6291 ** the specific parameter to measure.  ^(Recognized integer codes
   6292 ** are of the form [status parameters | SQLITE_STATUS_...].)^
   6293 ** ^The current value of the parameter is returned into *pCurrent.
   6294 ** ^The highest recorded value is returned in *pHighwater.  ^If the
   6295 ** resetFlag is true, then the highest record value is reset after
   6296 ** *pHighwater is written.  ^(Some parameters do not record the highest
   6297 ** value.  For those parameters
   6298 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
   6299 ** ^(Other parameters record only the highwater mark and not the current
   6300 ** value.  For these latter parameters nothing is written into *pCurrent.)^
   6301 **
   6302 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
   6303 ** non-zero [error code] on failure.
   6304 **
   6305 ** This routine is threadsafe but is not atomic.  This routine can be
   6306 ** called while other threads are running the same or different SQLite
   6307 ** interfaces.  However the values returned in *pCurrent and
   6308 ** *pHighwater reflect the status of SQLite at different points in time
   6309 ** and it is possible that another thread might change the parameter
   6310 ** in between the times when *pCurrent and *pHighwater are written.
   6311 **
   6312 ** See also: [sqlite3_db_status()]
   6313 */
   6314 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
   6315 
   6316 
   6317 /*
   6318 ** CAPI3REF: Status Parameters
   6319 ** KEYWORDS: {status parameters}
   6320 **
   6321 ** These integer constants designate various run-time status parameters
   6322 ** that can be returned by [sqlite3_status()].
   6323 **
   6324 ** <dl>
   6325 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
   6326 ** <dd>This parameter is the current amount of memory checked out
   6327 ** using [sqlite3_malloc()], either directly or indirectly.  The
   6328 ** figure includes calls made to [sqlite3_malloc()] by the application
   6329 ** and internal memory usage by the SQLite library.  Scratch memory
   6330 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
   6331 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
   6332 ** this parameter.  The amount returned is the sum of the allocation
   6333 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
   6334 **
   6335 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
   6336 ** <dd>This parameter records the largest memory allocation request
   6337 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
   6338 ** internal equivalents).  Only the value returned in the
   6339 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   6340 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   6341 **
   6342 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
   6343 ** <dd>This parameter records the number of separate memory allocations
   6344 ** currently checked out.</dd>)^
   6345 **
   6346 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
   6347 ** <dd>This parameter returns the number of pages used out of the
   6348 ** [pagecache memory allocator] that was configured using
   6349 ** [SQLITE_CONFIG_PAGECACHE].  The
   6350 ** value returned is in pages, not in bytes.</dd>)^
   6351 **
   6352 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
   6353 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
   6354 ** <dd>This parameter returns the number of bytes of page cache
   6355 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
   6356 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
   6357 ** returned value includes allocations that overflowed because they
   6358 ** where too large (they were larger than the "sz" parameter to
   6359 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
   6360 ** no space was left in the page cache.</dd>)^
   6361 **
   6362 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
   6363 ** <dd>This parameter records the largest memory allocation request
   6364 ** handed to [pagecache memory allocator].  Only the value returned in the
   6365 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   6366 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   6367 **
   6368 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
   6369 ** <dd>This parameter returns the number of allocations used out of the
   6370 ** [scratch memory allocator] configured using
   6371 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
   6372 ** in bytes.  Since a single thread may only have one scratch allocation
   6373 ** outstanding at time, this parameter also reports the number of threads
   6374 ** using scratch memory at the same time.</dd>)^
   6375 **
   6376 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
   6377 ** <dd>This parameter returns the number of bytes of scratch memory
   6378 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
   6379 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
   6380 ** returned include overflows because the requested allocation was too
   6381 ** larger (that is, because the requested allocation was larger than the
   6382 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
   6383 ** slots were available.
   6384 ** </dd>)^
   6385 **
   6386 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
   6387 ** <dd>This parameter records the largest memory allocation request
   6388 ** handed to [scratch memory allocator].  Only the value returned in the
   6389 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   6390 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   6391 **
   6392 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
   6393 ** <dd>This parameter records the deepest parser stack.  It is only
   6394 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
   6395 ** </dl>
   6396 **
   6397 ** New status parameters may be added from time to time.
   6398 */
   6399 #define SQLITE_STATUS_MEMORY_USED          0
   6400 #define SQLITE_STATUS_PAGECACHE_USED       1
   6401 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
   6402 #define SQLITE_STATUS_SCRATCH_USED         3
   6403 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
   6404 #define SQLITE_STATUS_MALLOC_SIZE          5
   6405 #define SQLITE_STATUS_PARSER_STACK         6
   6406 #define SQLITE_STATUS_PAGECACHE_SIZE       7
   6407 #define SQLITE_STATUS_SCRATCH_SIZE         8
   6408 #define SQLITE_STATUS_MALLOC_COUNT         9
   6409 
   6410 /*
   6411 ** CAPI3REF: Database Connection Status
   6412 **
   6413 ** ^This interface is used to retrieve runtime status information
   6414 ** about a single [database connection].  ^The first argument is the
   6415 ** database connection object to be interrogated.  ^The second argument
   6416 ** is an integer constant, taken from the set of
   6417 ** [SQLITE_DBSTATUS options], that
   6418 ** determines the parameter to interrogate.  The set of
   6419 ** [SQLITE_DBSTATUS options] is likely
   6420 ** to grow in future releases of SQLite.
   6421 **
   6422 ** ^The current value of the requested parameter is written into *pCur
   6423 ** and the highest instantaneous value is written into *pHiwtr.  ^If
   6424 ** the resetFlg is true, then the highest instantaneous value is
   6425 ** reset back down to the current value.
   6426 **
   6427 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
   6428 ** non-zero [error code] on failure.
   6429 **
   6430 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
   6431 */
   6432 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
   6433 
   6434 /*
   6435 ** CAPI3REF: Status Parameters for database connections
   6436 ** KEYWORDS: {SQLITE_DBSTATUS options}
   6437 **
   6438 ** These constants are the available integer "verbs" that can be passed as
   6439 ** the second argument to the [sqlite3_db_status()] interface.
   6440 **
   6441 ** New verbs may be added in future releases of SQLite. Existing verbs
   6442 ** might be discontinued. Applications should check the return code from
   6443 ** [sqlite3_db_status()] to make sure that the call worked.
   6444 ** The [sqlite3_db_status()] interface will return a non-zero error code
   6445 ** if a discontinued or unsupported verb is invoked.
   6446 **
   6447 ** <dl>
   6448 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
   6449 ** <dd>This parameter returns the number of lookaside memory slots currently
   6450 ** checked out.</dd>)^
   6451 **
   6452 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
   6453 ** <dd>This parameter returns the number malloc attempts that were
   6454 ** satisfied using lookaside memory. Only the high-water value is meaningful;
   6455 ** the current value is always zero.)^
   6456 **
   6457 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
   6458 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
   6459 ** <dd>This parameter returns the number malloc attempts that might have
   6460 ** been satisfied using lookaside memory but failed due to the amount of
   6461 ** memory requested being larger than the lookaside slot size.
   6462 ** Only the high-water value is meaningful;
   6463 ** the current value is always zero.)^
   6464 **
   6465 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
   6466 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
   6467 ** <dd>This parameter returns the number malloc attempts that might have
   6468 ** been satisfied using lookaside memory but failed due to all lookaside
   6469 ** memory already being in use.
   6470 ** Only the high-water value is meaningful;
   6471 ** the current value is always zero.)^
   6472 **
   6473 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
   6474 ** <dd>This parameter returns the approximate number of of bytes of heap
   6475 ** memory used by all pager caches associated with the database connection.)^
   6476 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
   6477 **
   6478 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
   6479 ** <dd>This parameter returns the approximate number of of bytes of heap
   6480 ** memory used to store the schema for all databases associated
   6481 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
   6482 ** ^The full amount of memory used by the schemas is reported, even if the
   6483 ** schema memory is shared with other database connections due to
   6484 ** [shared cache mode] being enabled.
   6485 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
   6486 **
   6487 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
   6488 ** <dd>This parameter returns the approximate number of of bytes of heap
   6489 ** and lookaside memory used by all prepared statements associated with
   6490 ** the database connection.)^
   6491 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
   6492 ** </dd>
   6493 **
   6494 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
   6495 ** <dd>This parameter returns the number of pager cache hits that have
   6496 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
   6497 ** is always 0.
   6498 ** </dd>
   6499 **
   6500 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
   6501 ** <dd>This parameter returns the number of pager cache misses that have
   6502 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
   6503 ** is always 0.
   6504 ** </dd>
   6505 **
   6506 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
   6507 ** <dd>This parameter returns the number of dirty cache entries that have
   6508 ** been written to disk. Specifically, the number of pages written to the
   6509 ** wal file in wal mode databases, or the number of pages written to the
   6510 ** database file in rollback mode databases. Any pages written as part of
   6511 ** transaction rollback or database recovery operations are not included.
   6512 ** If an IO or other error occurs while writing a page to disk, the effect
   6513 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
   6514 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
   6515 ** </dd>
   6516 **
   6517 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
   6518 ** <dd>This parameter returns zero for the current value if and only if
   6519 ** all foreign key constraints (deferred or immediate) have been
   6520 ** resolved.)^  ^The highwater mark is always 0.
   6521 ** </dd>
   6522 ** </dl>
   6523 */
   6524 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
   6525 #define SQLITE_DBSTATUS_CACHE_USED           1
   6526 #define SQLITE_DBSTATUS_SCHEMA_USED          2
   6527 #define SQLITE_DBSTATUS_STMT_USED            3
   6528 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
   6529 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
   6530 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
   6531 #define SQLITE_DBSTATUS_CACHE_HIT            7
   6532 #define SQLITE_DBSTATUS_CACHE_MISS           8
   6533 #define SQLITE_DBSTATUS_CACHE_WRITE          9
   6534 #define SQLITE_DBSTATUS_DEFERRED_FKS        10
   6535 #define SQLITE_DBSTATUS_MAX                 10   /* Largest defined DBSTATUS */
   6536 
   6537 
   6538 /*
   6539 ** CAPI3REF: Prepared Statement Status
   6540 **
   6541 ** ^(Each prepared statement maintains various
   6542 ** [SQLITE_STMTSTATUS counters] that measure the number
   6543 ** of times it has performed specific operations.)^  These counters can
   6544 ** be used to monitor the performance characteristics of the prepared
   6545 ** statements.  For example, if the number of table steps greatly exceeds
   6546 ** the number of table searches or result rows, that would tend to indicate
   6547 ** that the prepared statement is using a full table scan rather than
   6548 ** an index.
   6549 **
   6550 ** ^(This interface is used to retrieve and reset counter values from
   6551 ** a [prepared statement].  The first argument is the prepared statement
   6552 ** object to be interrogated.  The second argument
   6553 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
   6554 ** to be interrogated.)^
   6555 ** ^The current value of the requested counter is returned.
   6556 ** ^If the resetFlg is true, then the counter is reset to zero after this
   6557 ** interface call returns.
   6558 **
   6559 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
   6560 */
   6561 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
   6562 
   6563 /*
   6564 ** CAPI3REF: Status Parameters for prepared statements
   6565 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
   6566 **
   6567 ** These preprocessor macros define integer codes that name counter
   6568 ** values associated with the [sqlite3_stmt_status()] interface.
   6569 ** The meanings of the various counters are as follows:
   6570 **
   6571 ** <dl>
   6572 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
   6573 ** <dd>^This is the number of times that SQLite has stepped forward in
   6574 ** a table as part of a full table scan.  Large numbers for this counter
   6575 ** may indicate opportunities for performance improvement through
   6576 ** careful use of indices.</dd>
   6577 **
   6578 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
   6579 ** <dd>^This is the number of sort operations that have occurred.
   6580 ** A non-zero value in this counter may indicate an opportunity to
   6581 ** improvement performance through careful use of indices.</dd>
   6582 **
   6583 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
   6584 ** <dd>^This is the number of rows inserted into transient indices that
   6585 ** were created automatically in order to help joins run faster.
   6586 ** A non-zero value in this counter may indicate an opportunity to
   6587 ** improvement performance by adding permanent indices that do not
   6588 ** need to be reinitialized each time the statement is run.</dd>
   6589 **
   6590 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
   6591 ** <dd>^This is the number of virtual machine operations executed
   6592 ** by the prepared statement if that number is less than or equal
   6593 ** to 2147483647.  The number of virtual machine operations can be
   6594 ** used as a proxy for the total work done by the prepared statement.
   6595 ** If the number of virtual machine operations exceeds 2147483647
   6596 ** then the value returned by this statement status code is undefined.
   6597 ** </dd>
   6598 ** </dl>
   6599 */
   6600 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
   6601 #define SQLITE_STMTSTATUS_SORT              2
   6602 #define SQLITE_STMTSTATUS_AUTOINDEX         3
   6603 #define SQLITE_STMTSTATUS_VM_STEP           4
   6604 
   6605 /*
   6606 ** CAPI3REF: Custom Page Cache Object
   6607 **
   6608 ** The sqlite3_pcache type is opaque.  It is implemented by
   6609 ** the pluggable module.  The SQLite core has no knowledge of
   6610 ** its size or internal structure and never deals with the
   6611 ** sqlite3_pcache object except by holding and passing pointers
   6612 ** to the object.
   6613 **
   6614 ** See [sqlite3_pcache_methods2] for additional information.
   6615 */
   6616 typedef struct sqlite3_pcache sqlite3_pcache;
   6617 
   6618 /*
   6619 ** CAPI3REF: Custom Page Cache Object
   6620 **
   6621 ** The sqlite3_pcache_page object represents a single page in the
   6622 ** page cache.  The page cache will allocate instances of this
   6623 ** object.  Various methods of the page cache use pointers to instances
   6624 ** of this object as parameters or as their return value.
   6625 **
   6626 ** See [sqlite3_pcache_methods2] for additional information.
   6627 */
   6628 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
   6629 struct sqlite3_pcache_page {
   6630   void *pBuf;        /* The content of the page */
   6631   void *pExtra;      /* Extra information associated with the page */
   6632 };
   6633 
   6634 /*
   6635 ** CAPI3REF: Application Defined Page Cache.
   6636 ** KEYWORDS: {page cache}
   6637 **
   6638 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
   6639 ** register an alternative page cache implementation by passing in an
   6640 ** instance of the sqlite3_pcache_methods2 structure.)^
   6641 ** In many applications, most of the heap memory allocated by
   6642 ** SQLite is used for the page cache.
   6643 ** By implementing a
   6644 ** custom page cache using this API, an application can better control
   6645 ** the amount of memory consumed by SQLite, the way in which
   6646 ** that memory is allocated and released, and the policies used to
   6647 ** determine exactly which parts of a database file are cached and for
   6648 ** how long.
   6649 **
   6650 ** The alternative page cache mechanism is an
   6651 ** extreme measure that is only needed by the most demanding applications.
   6652 ** The built-in page cache is recommended for most uses.
   6653 **
   6654 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
   6655 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
   6656 ** the application may discard the parameter after the call to
   6657 ** [sqlite3_config()] returns.)^
   6658 **
   6659 ** [[the xInit() page cache method]]
   6660 ** ^(The xInit() method is called once for each effective
   6661 ** call to [sqlite3_initialize()])^
   6662 ** (usually only once during the lifetime of the process). ^(The xInit()
   6663 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
   6664 ** The intent of the xInit() method is to set up global data structures
   6665 ** required by the custom page cache implementation.
   6666 ** ^(If the xInit() method is NULL, then the
   6667 ** built-in default page cache is used instead of the application defined
   6668 ** page cache.)^
   6669 **
   6670 ** [[the xShutdown() page cache method]]
   6671 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
   6672 ** It can be used to clean up
   6673 ** any outstanding resources before process shutdown, if required.
   6674 ** ^The xShutdown() method may be NULL.
   6675 **
   6676 ** ^SQLite automatically serializes calls to the xInit method,
   6677 ** so the xInit method need not be threadsafe.  ^The
   6678 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   6679 ** not need to be threadsafe either.  All other methods must be threadsafe
   6680 ** in multithreaded applications.
   6681 **
   6682 ** ^SQLite will never invoke xInit() more than once without an intervening
   6683 ** call to xShutdown().
   6684 **
   6685 ** [[the xCreate() page cache methods]]
   6686 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
   6687 ** SQLite will typically create one cache instance for each open database file,
   6688 ** though this is not guaranteed. ^The
   6689 ** first parameter, szPage, is the size in bytes of the pages that must
   6690 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
   6691 ** second parameter szExtra is a number of bytes of extra storage
   6692 ** associated with each page cache entry.  ^The szExtra parameter will
   6693 ** a number less than 250.  SQLite will use the
   6694 ** extra szExtra bytes on each page to store metadata about the underlying
   6695 ** database page on disk.  The value passed into szExtra depends
   6696 ** on the SQLite version, the target platform, and how SQLite was compiled.
   6697 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
   6698 ** created will be used to cache database pages of a file stored on disk, or
   6699 ** false if it is used for an in-memory database. The cache implementation
   6700 ** does not have to do anything special based with the value of bPurgeable;
   6701 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
   6702 ** never invoke xUnpin() except to deliberately delete a page.
   6703 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
   6704 ** false will always have the "discard" flag set to true.
   6705 ** ^Hence, a cache created with bPurgeable false will
   6706 ** never contain any unpinned pages.
   6707 **
   6708 ** [[the xCachesize() page cache method]]
   6709 ** ^(The xCachesize() method may be called at any time by SQLite to set the
   6710 ** suggested maximum cache-size (number of pages stored by) the cache
   6711 ** instance passed as the first argument. This is the value configured using
   6712 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
   6713 ** parameter, the implementation is not required to do anything with this
   6714 ** value; it is advisory only.
   6715 **
   6716 ** [[the xPagecount() page cache methods]]
   6717 ** The xPagecount() method must return the number of pages currently
   6718 ** stored in the cache, both pinned and unpinned.
   6719 **
   6720 ** [[the xFetch() page cache methods]]
   6721 ** The xFetch() method locates a page in the cache and returns a pointer to
   6722 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
   6723 ** The pBuf element of the returned sqlite3_pcache_page object will be a
   6724 ** pointer to a buffer of szPage bytes used to store the content of a
   6725 ** single database page.  The pExtra element of sqlite3_pcache_page will be
   6726 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
   6727 ** for each entry in the page cache.
   6728 **
   6729 ** The page to be fetched is determined by the key. ^The minimum key value
   6730 ** is 1.  After it has been retrieved using xFetch, the page is considered
   6731 ** to be "pinned".
   6732 **
   6733 ** If the requested page is already in the page cache, then the page cache
   6734 ** implementation must return a pointer to the page buffer with its content
   6735 ** intact.  If the requested page is not already in the cache, then the
   6736 ** cache implementation should use the value of the createFlag
   6737 ** parameter to help it determined what action to take:
   6738 **
   6739 ** <table border=1 width=85% align=center>
   6740 ** <tr><th> createFlag <th> Behavior when page is not already in cache
   6741 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
   6742 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
   6743 **                 Otherwise return NULL.
   6744 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
   6745 **                 NULL if allocating a new page is effectively impossible.
   6746 ** </table>
   6747 **
   6748 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
   6749 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
   6750 ** failed.)^  In between the to xFetch() calls, SQLite may
   6751 ** attempt to unpin one or more cache pages by spilling the content of
   6752 ** pinned pages to disk and synching the operating system disk cache.
   6753 **
   6754 ** [[the xUnpin() page cache method]]
   6755 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
   6756 ** as its second argument.  If the third parameter, discard, is non-zero,
   6757 ** then the page must be evicted from the cache.
   6758 ** ^If the discard parameter is
   6759 ** zero, then the page may be discarded or retained at the discretion of
   6760 ** page cache implementation. ^The page cache implementation
   6761 ** may choose to evict unpinned pages at any time.
   6762 **
   6763 ** The cache must not perform any reference counting. A single
   6764 ** call to xUnpin() unpins the page regardless of the number of prior calls
   6765 ** to xFetch().
   6766 **
   6767 ** [[the xRekey() page cache methods]]
   6768 ** The xRekey() method is used to change the key value associated with the
   6769 ** page passed as the second argument. If the cache
   6770 ** previously contains an entry associated with newKey, it must be
   6771 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
   6772 ** to be pinned.
   6773 **
   6774 ** When SQLite calls the xTruncate() method, the cache must discard all
   6775 ** existing cache entries with page numbers (keys) greater than or equal
   6776 ** to the value of the iLimit parameter passed to xTruncate(). If any
   6777 ** of these pages are pinned, they are implicitly unpinned, meaning that
   6778 ** they can be safely discarded.
   6779 **
   6780 ** [[the xDestroy() page cache method]]
   6781 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
   6782 ** All resources associated with the specified cache should be freed. ^After
   6783 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
   6784 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
   6785 ** functions.
   6786 **
   6787 ** [[the xShrink() page cache method]]
   6788 ** ^SQLite invokes the xShrink() method when it wants the page cache to
   6789 ** free up as much of heap memory as possible.  The page cache implementation
   6790 ** is not obligated to free any memory, but well-behaved implementations should
   6791 ** do their best.
   6792 */
   6793 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
   6794 struct sqlite3_pcache_methods2 {
   6795   int iVersion;
   6796   void *pArg;
   6797   int (*xInit)(void*);
   6798   void (*xShutdown)(void*);
   6799   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
   6800   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   6801   int (*xPagecount)(sqlite3_pcache*);
   6802   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   6803   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
   6804   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
   6805       unsigned oldKey, unsigned newKey);
   6806   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   6807   void (*xDestroy)(sqlite3_pcache*);
   6808   void (*xShrink)(sqlite3_pcache*);
   6809 };
   6810 
   6811 /*
   6812 ** This is the obsolete pcache_methods object that has now been replaced
   6813 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
   6814 ** retained in the header file for backwards compatibility only.
   6815 */
   6816 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
   6817 struct sqlite3_pcache_methods {
   6818   void *pArg;
   6819   int (*xInit)(void*);
   6820   void (*xShutdown)(void*);
   6821   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
   6822   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   6823   int (*xPagecount)(sqlite3_pcache*);
   6824   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   6825   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
   6826   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
   6827   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   6828   void (*xDestroy)(sqlite3_pcache*);
   6829 };
   6830 
   6831 
   6832 /*
   6833 ** CAPI3REF: Online Backup Object
   6834 **
   6835 ** The sqlite3_backup object records state information about an ongoing
   6836 ** online backup operation.  ^The sqlite3_backup object is created by
   6837 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
   6838 ** [sqlite3_backup_finish()].
   6839 **
   6840 ** See Also: [Using the SQLite Online Backup API]
   6841 */
   6842 typedef struct sqlite3_backup sqlite3_backup;
   6843 
   6844 /*
   6845 ** CAPI3REF: Online Backup API.
   6846 **
   6847 ** The backup API copies the content of one database into another.
   6848 ** It is useful either for creating backups of databases or
   6849 ** for copying in-memory databases to or from persistent files.
   6850 **
   6851 ** See Also: [Using the SQLite Online Backup API]
   6852 **
   6853 ** ^SQLite holds a write transaction open on the destination database file
   6854 ** for the duration of the backup operation.
   6855 ** ^The source database is read-locked only while it is being read;
   6856 ** it is not locked continuously for the entire backup operation.
   6857 ** ^Thus, the backup may be performed on a live source database without
   6858 ** preventing other database connections from
   6859 ** reading or writing to the source database while the backup is underway.
   6860 **
   6861 ** ^(To perform a backup operation:
   6862 **   <ol>
   6863 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
   6864 **         backup,
   6865 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
   6866 **         the data between the two databases, and finally
   6867 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
   6868 **         associated with the backup operation.
   6869 **   </ol>)^
   6870 ** There should be exactly one call to sqlite3_backup_finish() for each
   6871 ** successful call to sqlite3_backup_init().
   6872 **
   6873 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
   6874 **
   6875 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
   6876 ** [database connection] associated with the destination database
   6877 ** and the database name, respectively.
   6878 ** ^The database name is "main" for the main database, "temp" for the
   6879 ** temporary database, or the name specified after the AS keyword in
   6880 ** an [ATTACH] statement for an attached database.
   6881 ** ^The S and M arguments passed to
   6882 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
   6883 ** and database name of the source database, respectively.
   6884 ** ^The source and destination [database connections] (parameters S and D)
   6885 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
   6886 ** an error.
   6887 **
   6888 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
   6889 ** returned and an error code and error message are stored in the
   6890 ** destination [database connection] D.
   6891 ** ^The error code and message for the failed call to sqlite3_backup_init()
   6892 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
   6893 ** [sqlite3_errmsg16()] functions.
   6894 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
   6895 ** [sqlite3_backup] object.
   6896 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
   6897 ** sqlite3_backup_finish() functions to perform the specified backup
   6898 ** operation.
   6899 **
   6900 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
   6901 **
   6902 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
   6903 ** the source and destination databases specified by [sqlite3_backup] object B.
   6904 ** ^If N is negative, all remaining source pages are copied.
   6905 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
   6906 ** are still more pages to be copied, then the function returns [SQLITE_OK].
   6907 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
   6908 ** from source to destination, then it returns [SQLITE_DONE].
   6909 ** ^If an error occurs while running sqlite3_backup_step(B,N),
   6910 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
   6911 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
   6912 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
   6913 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
   6914 **
   6915 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
   6916 ** <ol>
   6917 ** <li> the destination database was opened read-only, or
   6918 ** <li> the destination database is using write-ahead-log journaling
   6919 ** and the destination and source page sizes differ, or
   6920 ** <li> the destination database is an in-memory database and the
   6921 ** destination and source page sizes differ.
   6922 ** </ol>)^
   6923 **
   6924 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
   6925 ** the [sqlite3_busy_handler | busy-handler function]
   6926 ** is invoked (if one is specified). ^If the
   6927 ** busy-handler returns non-zero before the lock is available, then
   6928 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
   6929 ** sqlite3_backup_step() can be retried later. ^If the source
   6930 ** [database connection]
   6931 ** is being used to write to the source database when sqlite3_backup_step()
   6932 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
   6933 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
   6934 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
   6935 ** [SQLITE_READONLY] is returned, then
   6936 ** there is no point in retrying the call to sqlite3_backup_step(). These
   6937 ** errors are considered fatal.)^  The application must accept
   6938 ** that the backup operation has failed and pass the backup operation handle
   6939 ** to the sqlite3_backup_finish() to release associated resources.
   6940 **
   6941 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
   6942 ** on the destination file. ^The exclusive lock is not released until either
   6943 ** sqlite3_backup_finish() is called or the backup operation is complete
   6944 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
   6945 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
   6946 ** lasts for the duration of the sqlite3_backup_step() call.
   6947 ** ^Because the source database is not locked between calls to
   6948 ** sqlite3_backup_step(), the source database may be modified mid-way
   6949 ** through the backup process.  ^If the source database is modified by an
   6950 ** external process or via a database connection other than the one being
   6951 ** used by the backup operation, then the backup will be automatically
   6952 ** restarted by the next call to sqlite3_backup_step(). ^If the source
   6953 ** database is modified by the using the same database connection as is used
   6954 ** by the backup operation, then the backup database is automatically
   6955 ** updated at the same time.
   6956 **
   6957 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
   6958 **
   6959 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
   6960 ** application wishes to abandon the backup operation, the application
   6961 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
   6962 ** ^The sqlite3_backup_finish() interfaces releases all
   6963 ** resources associated with the [sqlite3_backup] object.
   6964 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
   6965 ** active write-transaction on the destination database is rolled back.
   6966 ** The [sqlite3_backup] object is invalid
   6967 ** and may not be used following a call to sqlite3_backup_finish().
   6968 **
   6969 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
   6970 ** sqlite3_backup_step() errors occurred, regardless or whether or not
   6971 ** sqlite3_backup_step() completed.
   6972 ** ^If an out-of-memory condition or IO error occurred during any prior
   6973 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
   6974 ** sqlite3_backup_finish() returns the corresponding [error code].
   6975 **
   6976 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
   6977 ** is not a permanent error and does not affect the return value of
   6978 ** sqlite3_backup_finish().
   6979 **
   6980 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
   6981 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
   6982 **
   6983 ** ^Each call to sqlite3_backup_step() sets two values inside
   6984 ** the [sqlite3_backup] object: the number of pages still to be backed
   6985 ** up and the total number of pages in the source database file.
   6986 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
   6987 ** retrieve these two values, respectively.
   6988 **
   6989 ** ^The values returned by these functions are only updated by
   6990 ** sqlite3_backup_step(). ^If the source database is modified during a backup
   6991 ** operation, then the values are not updated to account for any extra
   6992 ** pages that need to be updated or the size of the source database file
   6993 ** changing.
   6994 **
   6995 ** <b>Concurrent Usage of Database Handles</b>
   6996 **
   6997 ** ^The source [database connection] may be used by the application for other
   6998 ** purposes while a backup operation is underway or being initialized.
   6999 ** ^If SQLite is compiled and configured to support threadsafe database
   7000 ** connections, then the source database connection may be used concurrently
   7001 ** from within other threads.
   7002 **
   7003 ** However, the application must guarantee that the destination
   7004 ** [database connection] is not passed to any other API (by any thread) after
   7005 ** sqlite3_backup_init() is called and before the corresponding call to
   7006 ** sqlite3_backup_finish().  SQLite does not currently check to see
   7007 ** if the application incorrectly accesses the destination [database connection]
   7008 ** and so no error code is reported, but the operations may malfunction
   7009 ** nevertheless.  Use of the destination database connection while a
   7010 ** backup is in progress might also also cause a mutex deadlock.
   7011 **
   7012 ** If running in [shared cache mode], the application must
   7013 ** guarantee that the shared cache used by the destination database
   7014 ** is not accessed while the backup is running. In practice this means
   7015 ** that the application must guarantee that the disk file being
   7016 ** backed up to is not accessed by any connection within the process,
   7017 ** not just the specific connection that was passed to sqlite3_backup_init().
   7018 **
   7019 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
   7020 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
   7021 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
   7022 ** APIs are not strictly speaking threadsafe. If they are invoked at the
   7023 ** same time as another thread is invoking sqlite3_backup_step() it is
   7024 ** possible that they return invalid values.
   7025 */
   7026 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   7027   sqlite3 *pDest,                        /* Destination database handle */
   7028   const char *zDestName,                 /* Destination database name */
   7029   sqlite3 *pSource,                      /* Source database handle */
   7030   const char *zSourceName                /* Source database name */
   7031 );
   7032 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
   7033 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
   7034 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
   7035 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
   7036 
   7037 /*
   7038 ** CAPI3REF: Unlock Notification
   7039 **
   7040 ** ^When running in shared-cache mode, a database operation may fail with
   7041 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
   7042 ** individual tables within the shared-cache cannot be obtained. See
   7043 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
   7044 ** ^This API may be used to register a callback that SQLite will invoke
   7045 ** when the connection currently holding the required lock relinquishes it.
   7046 ** ^This API is only available if the library was compiled with the
   7047 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
   7048 **
   7049 ** See Also: [Using the SQLite Unlock Notification Feature].
   7050 **
   7051 ** ^Shared-cache locks are released when a database connection concludes
   7052 ** its current transaction, either by committing it or rolling it back.
   7053 **
   7054 ** ^When a connection (known as the blocked connection) fails to obtain a
   7055 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
   7056 ** identity of the database connection (the blocking connection) that
   7057 ** has locked the required resource is stored internally. ^After an
   7058 ** application receives an SQLITE_LOCKED error, it may call the
   7059 ** sqlite3_unlock_notify() method with the blocked connection handle as
   7060 ** the first argument to register for a callback that will be invoked
   7061 ** when the blocking connections current transaction is concluded. ^The
   7062 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
   7063 ** call that concludes the blocking connections transaction.
   7064 **
   7065 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
   7066 ** there is a chance that the blocking connection will have already
   7067 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
   7068 ** If this happens, then the specified callback is invoked immediately,
   7069 ** from within the call to sqlite3_unlock_notify().)^
   7070 **
   7071 ** ^If the blocked connection is attempting to obtain a write-lock on a
   7072 ** shared-cache table, and more than one other connection currently holds
   7073 ** a read-lock on the same table, then SQLite arbitrarily selects one of
   7074 ** the other connections to use as the blocking connection.
   7075 **
   7076 ** ^(There may be at most one unlock-notify callback registered by a
   7077 ** blocked connection. If sqlite3_unlock_notify() is called when the
   7078 ** blocked connection already has a registered unlock-notify callback,
   7079 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
   7080 ** called with a NULL pointer as its second argument, then any existing
   7081 ** unlock-notify callback is canceled. ^The blocked connections
   7082 ** unlock-notify callback may also be canceled by closing the blocked
   7083 ** connection using [sqlite3_close()].
   7084 **
   7085 ** The unlock-notify callback is not reentrant. If an application invokes
   7086 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
   7087 ** crash or deadlock may be the result.
   7088 **
   7089 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
   7090 ** returns SQLITE_OK.
   7091 **
   7092 ** <b>Callback Invocation Details</b>
   7093 **
   7094 ** When an unlock-notify callback is registered, the application provides a
   7095 ** single void* pointer that is passed to the callback when it is invoked.
   7096 ** However, the signature of the callback function allows SQLite to pass
   7097 ** it an array of void* context pointers. The first argument passed to
   7098 ** an unlock-notify callback is a pointer to an array of void* pointers,
   7099 ** and the second is the number of entries in the array.
   7100 **
   7101 ** When a blocking connections transaction is concluded, there may be
   7102 ** more than one blocked connection that has registered for an unlock-notify
   7103 ** callback. ^If two or more such blocked connections have specified the
   7104 ** same callback function, then instead of invoking the callback function
   7105 ** multiple times, it is invoked once with the set of void* context pointers
   7106 ** specified by the blocked connections bundled together into an array.
   7107 ** This gives the application an opportunity to prioritize any actions
   7108 ** related to the set of unblocked database connections.
   7109 **
   7110 ** <b>Deadlock Detection</b>
   7111 **
   7112 ** Assuming that after registering for an unlock-notify callback a
   7113 ** database waits for the callback to be issued before taking any further
   7114 ** action (a reasonable assumption), then using this API may cause the
   7115 ** application to deadlock. For example, if connection X is waiting for
   7116 ** connection Y's transaction to be concluded, and similarly connection
   7117 ** Y is waiting on connection X's transaction, then neither connection
   7118 ** will proceed and the system may remain deadlocked indefinitely.
   7119 **
   7120 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
   7121 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
   7122 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
   7123 ** unlock-notify callback is registered. The system is said to be in
   7124 ** a deadlocked state if connection A has registered for an unlock-notify
   7125 ** callback on the conclusion of connection B's transaction, and connection
   7126 ** B has itself registered for an unlock-notify callback when connection
   7127 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
   7128 ** the system is also considered to be deadlocked if connection B has
   7129 ** registered for an unlock-notify callback on the conclusion of connection
   7130 ** C's transaction, where connection C is waiting on connection A. ^Any
   7131 ** number of levels of indirection are allowed.
   7132 **
   7133 ** <b>The "DROP TABLE" Exception</b>
   7134 **
   7135 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
   7136 ** always appropriate to call sqlite3_unlock_notify(). There is however,
   7137 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
   7138 ** SQLite checks if there are any currently executing SELECT statements
   7139 ** that belong to the same connection. If there are, SQLITE_LOCKED is
   7140 ** returned. In this case there is no "blocking connection", so invoking
   7141 ** sqlite3_unlock_notify() results in the unlock-notify callback being
   7142 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
   7143 ** or "DROP INDEX" query, an infinite loop might be the result.
   7144 **
   7145 ** One way around this problem is to check the extended error code returned
   7146 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
   7147 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
   7148 ** the special "DROP TABLE/INDEX" case, the extended error code is just
   7149 ** SQLITE_LOCKED.)^
   7150 */
   7151 SQLITE_API int sqlite3_unlock_notify(
   7152   sqlite3 *pBlocked,                          /* Waiting connection */
   7153   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
   7154   void *pNotifyArg                            /* Argument to pass to xNotify */
   7155 );
   7156 
   7157 
   7158 /*
   7159 ** CAPI3REF: String Comparison
   7160 **
   7161 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
   7162 ** and extensions to compare the contents of two buffers containing UTF-8
   7163 ** strings in a case-independent fashion, using the same definition of "case
   7164 ** independence" that SQLite uses internally when comparing identifiers.
   7165 */
   7166 SQLITE_API int sqlite3_stricmp(const char *, const char *);
   7167 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
   7168 
   7169 /*
   7170 ** CAPI3REF: String Globbing
   7171 *
   7172 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
   7173 ** the glob pattern P, and it returns non-zero if string X does not match
   7174 ** the glob pattern P.  ^The definition of glob pattern matching used in
   7175 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
   7176 ** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
   7177 ** sensitive.
   7178 **
   7179 ** Note that this routine returns zero on a match and non-zero if the strings
   7180 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
   7181 */
   7182 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
   7183 
   7184 /*
   7185 ** CAPI3REF: Error Logging Interface
   7186 **
   7187 ** ^The [sqlite3_log()] interface writes a message into the [error log]
   7188 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
   7189 ** ^If logging is enabled, the zFormat string and subsequent arguments are
   7190 ** used with [sqlite3_snprintf()] to generate the final output string.
   7191 **
   7192 ** The sqlite3_log() interface is intended for use by extensions such as
   7193 ** virtual tables, collating functions, and SQL functions.  While there is
   7194 ** nothing to prevent an application from calling sqlite3_log(), doing so
   7195 ** is considered bad form.
   7196 **
   7197 ** The zFormat string must not be NULL.
   7198 **
   7199 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
   7200 ** will not use dynamically allocated memory.  The log message is stored in
   7201 ** a fixed-length buffer on the stack.  If the log message is longer than
   7202 ** a few hundred characters, it will be truncated to the length of the
   7203 ** buffer.
   7204 */
   7205 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
   7206 
   7207 /*
   7208 ** CAPI3REF: Write-Ahead Log Commit Hook
   7209 **
   7210 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
   7211 ** will be invoked each time a database connection commits data to a
   7212 ** [write-ahead log] (i.e. whenever a transaction is committed in
   7213 ** [journal_mode | journal_mode=WAL mode]).
   7214 **
   7215 ** ^The callback is invoked by SQLite after the commit has taken place and
   7216 ** the associated write-lock on the database released, so the implementation
   7217 ** may read, write or [checkpoint] the database as required.
   7218 **
   7219 ** ^The first parameter passed to the callback function when it is invoked
   7220 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
   7221 ** registering the callback. ^The second is a copy of the database handle.
   7222 ** ^The third parameter is the name of the database that was written to -
   7223 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
   7224 ** is the number of pages currently in the write-ahead log file,
   7225 ** including those that were just committed.
   7226 **
   7227 ** The callback function should normally return [SQLITE_OK].  ^If an error
   7228 ** code is returned, that error will propagate back up through the
   7229 ** SQLite code base to cause the statement that provoked the callback
   7230 ** to report an error, though the commit will have still occurred. If the
   7231 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
   7232 ** that does not correspond to any valid SQLite error code, the results
   7233 ** are undefined.
   7234 **
   7235 ** A single database handle may have at most a single write-ahead log callback
   7236 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
   7237 ** previously registered write-ahead log callback. ^Note that the
   7238 ** [sqlite3_wal_autocheckpoint()] interface and the
   7239 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
   7240 ** those overwrite any prior [sqlite3_wal_hook()] settings.
   7241 */
   7242 SQLITE_API void *sqlite3_wal_hook(
   7243   sqlite3*,
   7244   int(*)(void *,sqlite3*,const char*,int),
   7245   void*
   7246 );
   7247 
   7248 /*
   7249 ** CAPI3REF: Configure an auto-checkpoint
   7250 **
   7251 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
   7252 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
   7253 ** to automatically [checkpoint]
   7254 ** after committing a transaction if there are N or
   7255 ** more frames in the [write-ahead log] file.  ^Passing zero or
   7256 ** a negative value as the nFrame parameter disables automatic
   7257 ** checkpoints entirely.
   7258 **
   7259 ** ^The callback registered by this function replaces any existing callback
   7260 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
   7261 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
   7262 ** configured by this function.
   7263 **
   7264 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
   7265 ** from SQL.
   7266 **
   7267 ** ^Checkpoints initiated by this mechanism are
   7268 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
   7269 **
   7270 ** ^Every new [database connection] defaults to having the auto-checkpoint
   7271 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
   7272 ** pages.  The use of this interface
   7273 ** is only necessary if the default setting is found to be suboptimal
   7274 ** for a particular application.
   7275 */
   7276 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
   7277 
   7278 /*
   7279 ** CAPI3REF: Checkpoint a database
   7280 **
   7281 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
   7282 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
   7283 ** empty string, then a checkpoint is run on all databases of
   7284 ** connection D.  ^If the database connection D is not in
   7285 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
   7286 ** ^The [sqlite3_wal_checkpoint(D,X)] interface initiates a
   7287 ** [sqlite3_wal_checkpoint_v2|PASSIVE] checkpoint.
   7288 ** Use the [sqlite3_wal_checkpoint_v2()] interface to get a FULL
   7289 ** or RESET checkpoint.
   7290 **
   7291 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
   7292 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
   7293 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
   7294 ** run whenever the WAL reaches a certain size threshold.
   7295 **
   7296 ** See also: [sqlite3_wal_checkpoint_v2()]
   7297 */
   7298 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
   7299 
   7300 /*
   7301 ** CAPI3REF: Checkpoint a database
   7302 **
   7303 ** Run a checkpoint operation on WAL database zDb attached to database
   7304 ** handle db. The specific operation is determined by the value of the
   7305 ** eMode parameter:
   7306 **
   7307 ** <dl>
   7308 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
   7309 **   Checkpoint as many frames as possible without waiting for any database
   7310 **   readers or writers to finish. Sync the db file if all frames in the log
   7311 **   are checkpointed. This mode is the same as calling
   7312 **   sqlite3_wal_checkpoint(). The [sqlite3_busy_handler|busy-handler callback]
   7313 **   is never invoked.
   7314 **
   7315 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
   7316 **   This mode blocks (it invokes the
   7317 **   [sqlite3_busy_handler|busy-handler callback]) until there is no
   7318 **   database writer and all readers are reading from the most recent database
   7319 **   snapshot. It then checkpoints all frames in the log file and syncs the
   7320 **   database file. This call blocks database writers while it is running,
   7321 **   but not database readers.
   7322 **
   7323 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
   7324 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
   7325 **   checkpointing the log file it blocks (calls the
   7326 **   [sqlite3_busy_handler|busy-handler callback])
   7327 **   until all readers are reading from the database file only. This ensures
   7328 **   that the next client to write to the database file restarts the log file
   7329 **   from the beginning. This call blocks database writers while it is running,
   7330 **   but not database readers.
   7331 ** </dl>
   7332 **
   7333 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
   7334 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
   7335 ** the total number of checkpointed frames (including any that were already
   7336 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
   7337 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
   7338 ** If no values are available because of an error, they are both set to -1
   7339 ** before returning to communicate this to the caller.
   7340 **
   7341 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
   7342 ** any other process is running a checkpoint operation at the same time, the
   7343 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
   7344 ** busy-handler configured, it will not be invoked in this case.
   7345 **
   7346 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
   7347 ** "writer" lock on the database file. If the writer lock cannot be obtained
   7348 ** immediately, and a busy-handler is configured, it is invoked and the writer
   7349 ** lock retried until either the busy-handler returns 0 or the lock is
   7350 ** successfully obtained. The busy-handler is also invoked while waiting for
   7351 ** database readers as described above. If the busy-handler returns 0 before
   7352 ** the writer lock is obtained or while waiting for database readers, the
   7353 ** checkpoint operation proceeds from that point in the same way as
   7354 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
   7355 ** without blocking any further. SQLITE_BUSY is returned in this case.
   7356 **
   7357 ** If parameter zDb is NULL or points to a zero length string, then the
   7358 ** specified operation is attempted on all WAL databases. In this case the
   7359 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
   7360 ** an SQLITE_BUSY error is encountered when processing one or more of the
   7361 ** attached WAL databases, the operation is still attempted on any remaining
   7362 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
   7363 ** error occurs while processing an attached database, processing is abandoned
   7364 ** and the error code returned to the caller immediately. If no error
   7365 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
   7366 ** databases, SQLITE_OK is returned.
   7367 **
   7368 ** If database zDb is the name of an attached database that is not in WAL
   7369 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
   7370 ** zDb is not NULL (or a zero length string) and is not the name of any
   7371 ** attached database, SQLITE_ERROR is returned to the caller.
   7372 */
   7373 SQLITE_API int sqlite3_wal_checkpoint_v2(
   7374   sqlite3 *db,                    /* Database handle */
   7375   const char *zDb,                /* Name of attached database (or NULL) */
   7376   int eMode,                      /* SQLITE_CHECKPOINT_* value */
   7377   int *pnLog,                     /* OUT: Size of WAL log in frames */
   7378   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
   7379 );
   7380 
   7381 /*
   7382 ** CAPI3REF: Checkpoint operation parameters
   7383 **
   7384 ** These constants can be used as the 3rd parameter to
   7385 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
   7386 ** documentation for additional information about the meaning and use of
   7387 ** each of these values.
   7388 */
   7389 #define SQLITE_CHECKPOINT_PASSIVE 0
   7390 #define SQLITE_CHECKPOINT_FULL    1
   7391 #define SQLITE_CHECKPOINT_RESTART 2
   7392 
   7393 /*
   7394 ** CAPI3REF: Virtual Table Interface Configuration
   7395 **
   7396 ** This function may be called by either the [xConnect] or [xCreate] method
   7397 ** of a [virtual table] implementation to configure
   7398 ** various facets of the virtual table interface.
   7399 **
   7400 ** If this interface is invoked outside the context of an xConnect or
   7401 ** xCreate virtual table method then the behavior is undefined.
   7402 **
   7403 ** At present, there is only one option that may be configured using
   7404 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
   7405 ** may be added in the future.
   7406 */
   7407 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
   7408 
   7409 /*
   7410 ** CAPI3REF: Virtual Table Configuration Options
   7411 **
   7412 ** These macros define the various options to the
   7413 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
   7414 ** can use to customize and optimize their behavior.
   7415 **
   7416 ** <dl>
   7417 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
   7418 ** <dd>Calls of the form
   7419 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
   7420 ** where X is an integer.  If X is zero, then the [virtual table] whose
   7421 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
   7422 ** support constraints.  In this configuration (which is the default) if
   7423 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
   7424 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
   7425 ** specified as part of the users SQL statement, regardless of the actual
   7426 ** ON CONFLICT mode specified.
   7427 **
   7428 ** If X is non-zero, then the virtual table implementation guarantees
   7429 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
   7430 ** any modifications to internal or persistent data structures have been made.
   7431 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
   7432 ** is able to roll back a statement or database transaction, and abandon
   7433 ** or continue processing the current SQL statement as appropriate.
   7434 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
   7435 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
   7436 ** had been ABORT.
   7437 **
   7438 ** Virtual table implementations that are required to handle OR REPLACE
   7439 ** must do so within the [xUpdate] method. If a call to the
   7440 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
   7441 ** CONFLICT policy is REPLACE, the virtual table implementation should
   7442 ** silently replace the appropriate rows within the xUpdate callback and
   7443 ** return SQLITE_OK. Or, if this is not possible, it may return
   7444 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
   7445 ** constraint handling.
   7446 ** </dl>
   7447 */
   7448 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
   7449 
   7450 /*
   7451 ** CAPI3REF: Determine The Virtual Table Conflict Policy
   7452 **
   7453 ** This function may only be called from within a call to the [xUpdate] method
   7454 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
   7455 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
   7456 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
   7457 ** of the SQL statement that triggered the call to the [xUpdate] method of the
   7458 ** [virtual table].
   7459 */
   7460 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
   7461 
   7462 /*
   7463 ** CAPI3REF: Conflict resolution modes
   7464 ** KEYWORDS: {conflict resolution mode}
   7465 **
   7466 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
   7467 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
   7468 ** is for the SQL statement being evaluated.
   7469 **
   7470 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
   7471 ** return value from the [sqlite3_set_authorizer()] callback and that
   7472 ** [SQLITE_ABORT] is also a [result code].
   7473 */
   7474 #define SQLITE_ROLLBACK 1
   7475 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
   7476 #define SQLITE_FAIL     3
   7477 /* #define SQLITE_ABORT 4  // Also an error code */
   7478 #define SQLITE_REPLACE  5
   7479 
   7480 
   7481 
   7482 /*
   7483 ** Undo the hack that converts floating point types to integer for
   7484 ** builds on processors without floating point support.
   7485 */
   7486 #ifdef SQLITE_OMIT_FLOATING_POINT
   7487 # undef double
   7488 #endif
   7489 
   7490 #if 0
   7491 }  /* End of the 'extern "C"' block */
   7492 #endif
   7493 #endif /* _SQLITE3_H_ */
   7494 
   7495 /*
   7496 ** 2010 August 30
   7497 **
   7498 ** The author disclaims copyright to this source code.  In place of
   7499 ** a legal notice, here is a blessing:
   7500 **
   7501 **    May you do good and not evil.
   7502 **    May you find forgiveness for yourself and forgive others.
   7503 **    May you share freely, never taking more than you give.
   7504 **
   7505 *************************************************************************
   7506 */
   7507 
   7508 #ifndef _SQLITE3RTREE_H_
   7509 #define _SQLITE3RTREE_H_
   7510 
   7511 
   7512 #if 0
   7513 extern "C" {
   7514 #endif
   7515 
   7516 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
   7517 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
   7518 
   7519 /* The double-precision datatype used by RTree depends on the
   7520 ** SQLITE_RTREE_INT_ONLY compile-time option.
   7521 */
   7522 #ifdef SQLITE_RTREE_INT_ONLY
   7523   typedef sqlite3_int64 sqlite3_rtree_dbl;
   7524 #else
   7525   typedef double sqlite3_rtree_dbl;
   7526 #endif
   7527 
   7528 /*
   7529 ** Register a geometry callback named zGeom that can be used as part of an
   7530 ** R-Tree geometry query as follows:
   7531 **
   7532 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
   7533 */
   7534 SQLITE_API int sqlite3_rtree_geometry_callback(
   7535   sqlite3 *db,
   7536   const char *zGeom,
   7537   int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
   7538   void *pContext
   7539 );
   7540 
   7541 
   7542 /*
   7543 ** A pointer to a structure of the following type is passed as the first
   7544 ** argument to callbacks registered using rtree_geometry_callback().
   7545 */
   7546 struct sqlite3_rtree_geometry {
   7547   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
   7548   int nParam;                     /* Size of array aParam[] */
   7549   sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
   7550   void *pUser;                    /* Callback implementation user data */
   7551   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
   7552 };
   7553 
   7554 /*
   7555 ** Register a 2nd-generation geometry callback named zScore that can be
   7556 ** used as part of an R-Tree geometry query as follows:
   7557 **
   7558 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
   7559 */
   7560 SQLITE_API int sqlite3_rtree_query_callback(
   7561   sqlite3 *db,
   7562   const char *zQueryFunc,
   7563   int (*xQueryFunc)(sqlite3_rtree_query_info*),
   7564   void *pContext,
   7565   void (*xDestructor)(void*)
   7566 );
   7567 
   7568 
   7569 /*
   7570 ** A pointer to a structure of the following type is passed as the
   7571 ** argument to scored geometry callback registered using
   7572 ** sqlite3_rtree_query_callback().
   7573 **
   7574 ** Note that the first 5 fields of this structure are identical to
   7575 ** sqlite3_rtree_geometry.  This structure is a subclass of
   7576 ** sqlite3_rtree_geometry.
   7577 */
   7578 struct sqlite3_rtree_query_info {
   7579   void *pContext;                   /* pContext from when function registered */
   7580   int nParam;                       /* Number of function parameters */
   7581   sqlite3_rtree_dbl *aParam;        /* value of function parameters */
   7582   void *pUser;                      /* callback can use this, if desired */
   7583   void (*xDelUser)(void*);          /* function to free pUser */
   7584   sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
   7585   unsigned int *anQueue;            /* Number of pending entries in the queue */
   7586   int nCoord;                       /* Number of coordinates */
   7587   int iLevel;                       /* Level of current node or entry */
   7588   int mxLevel;                      /* The largest iLevel value in the tree */
   7589   sqlite3_int64 iRowid;             /* Rowid for current entry */
   7590   sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
   7591   int eParentWithin;                /* Visibility of parent node */
   7592   int eWithin;                      /* OUT: Visiblity */
   7593   sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
   7594 };
   7595 
   7596 /*
   7597 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
   7598 */
   7599 #define NOT_WITHIN       0   /* Object completely outside of query region */
   7600 #define PARTLY_WITHIN    1   /* Object partially overlaps query region */
   7601 #define FULLY_WITHIN     2   /* Object fully contained within query region */
   7602 
   7603 
   7604 #if 0
   7605 }  /* end of the 'extern "C"' block */
   7606 #endif
   7607 
   7608 #endif  /* ifndef _SQLITE3RTREE_H_ */
   7609 
   7610 
   7611 /************** End of sqlite3.h *********************************************/
   7612 /************** Continuing where we left off in sqliteInt.h ******************/
   7613 
   7614 /*
   7615 ** Include the configuration header output by 'configure' if we're using the
   7616 ** autoconf-based build
   7617 */
   7618 #ifdef _HAVE_SQLITE_CONFIG_H
   7619 #include "config.h"
   7620 #endif
   7621 
   7622 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
   7623 /************** Begin file sqliteLimit.h *************************************/
   7624 /*
   7625 ** 2007 May 7
   7626 **
   7627 ** The author disclaims copyright to this source code.  In place of
   7628 ** a legal notice, here is a blessing:
   7629 **
   7630 **    May you do good and not evil.
   7631 **    May you find forgiveness for yourself and forgive others.
   7632 **    May you share freely, never taking more than you give.
   7633 **
   7634 *************************************************************************
   7635 **
   7636 ** This file defines various limits of what SQLite can process.
   7637 */
   7638 
   7639 /*
   7640 ** The maximum length of a TEXT or BLOB in bytes.   This also
   7641 ** limits the size of a row in a table or index.
   7642 **
   7643 ** The hard limit is the ability of a 32-bit signed integer
   7644 ** to count the size: 2^31-1 or 2147483647.
   7645 */
   7646 #ifndef SQLITE_MAX_LENGTH
   7647 # define SQLITE_MAX_LENGTH 1000000000
   7648 #endif
   7649 
   7650 /*
   7651 ** This is the maximum number of
   7652 **
   7653 **    * Columns in a table
   7654 **    * Columns in an index
   7655 **    * Columns in a view
   7656 **    * Terms in the SET clause of an UPDATE statement
   7657 **    * Terms in the result set of a SELECT statement
   7658 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
   7659 **    * Terms in the VALUES clause of an INSERT statement
   7660 **
   7661 ** The hard upper limit here is 32676.  Most database people will
   7662 ** tell you that in a well-normalized database, you usually should
   7663 ** not have more than a dozen or so columns in any table.  And if
   7664 ** that is the case, there is no point in having more than a few
   7665 ** dozen values in any of the other situations described above.
   7666 */
   7667 #ifndef SQLITE_MAX_COLUMN
   7668 # define SQLITE_MAX_COLUMN 2000
   7669 #endif
   7670 
   7671 /*
   7672 ** The maximum length of a single SQL statement in bytes.
   7673 **
   7674 ** It used to be the case that setting this value to zero would
   7675 ** turn the limit off.  That is no longer true.  It is not possible
   7676 ** to turn this limit off.
   7677 */
   7678 #ifndef SQLITE_MAX_SQL_LENGTH
   7679 # define SQLITE_MAX_SQL_LENGTH 1000000000
   7680 #endif
   7681 
   7682 /*
   7683 ** The maximum depth of an expression tree. This is limited to
   7684 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
   7685 ** want to place more severe limits on the complexity of an
   7686 ** expression.
   7687 **
   7688 ** A value of 0 used to mean that the limit was not enforced.
   7689 ** But that is no longer true.  The limit is now strictly enforced
   7690 ** at all times.
   7691 */
   7692 #ifndef SQLITE_MAX_EXPR_DEPTH
   7693 # define SQLITE_MAX_EXPR_DEPTH 1000
   7694 #endif
   7695 
   7696 /*
   7697 ** The maximum number of terms in a compound SELECT statement.
   7698 ** The code generator for compound SELECT statements does one
   7699 ** level of recursion for each term.  A stack overflow can result
   7700 ** if the number of terms is too large.  In practice, most SQL
   7701 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
   7702 ** any limit on the number of terms in a compount SELECT.
   7703 */
   7704 #ifndef SQLITE_MAX_COMPOUND_SELECT
   7705 # define SQLITE_MAX_COMPOUND_SELECT 500
   7706 #endif
   7707 
   7708 /*
   7709 ** The maximum number of opcodes in a VDBE program.
   7710 ** Not currently enforced.
   7711 */
   7712 #ifndef SQLITE_MAX_VDBE_OP
   7713 # define SQLITE_MAX_VDBE_OP 25000
   7714 #endif
   7715 
   7716 /*
   7717 ** The maximum number of arguments to an SQL function.
   7718 */
   7719 #ifndef SQLITE_MAX_FUNCTION_ARG
   7720 # define SQLITE_MAX_FUNCTION_ARG 127
   7721 #endif
   7722 
   7723 /*
   7724 ** The maximum number of in-memory pages to use for the main database
   7725 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
   7726 */
   7727 #ifndef SQLITE_DEFAULT_CACHE_SIZE
   7728 # define SQLITE_DEFAULT_CACHE_SIZE  2000
   7729 #endif
   7730 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
   7731 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
   7732 #endif
   7733 
   7734 /*
   7735 ** The default number of frames to accumulate in the log file before
   7736 ** checkpointing the database in WAL mode.
   7737 */
   7738 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
   7739 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
   7740 #endif
   7741 
   7742 /*
   7743 ** The maximum number of attached databases.  This must be between 0
   7744 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
   7745 ** is used internally to track attached databases.
   7746 */
   7747 #ifndef SQLITE_MAX_ATTACHED
   7748 # define SQLITE_MAX_ATTACHED 10
   7749 #endif
   7750 
   7751 
   7752 /*
   7753 ** The maximum value of a ?nnn wildcard that the parser will accept.
   7754 */
   7755 #ifndef SQLITE_MAX_VARIABLE_NUMBER
   7756 # define SQLITE_MAX_VARIABLE_NUMBER 999
   7757 #endif
   7758 
   7759 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
   7760 ** imposed by the use of 16-bit offsets within each page.
   7761 **
   7762 ** Earlier versions of SQLite allowed the user to change this value at
   7763 ** compile time. This is no longer permitted, on the grounds that it creates
   7764 ** a library that is technically incompatible with an SQLite library
   7765 ** compiled with a different limit. If a process operating on a database
   7766 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
   7767 ** compiled with the default page-size limit will not be able to rollback
   7768 ** the aborted transaction. This could lead to database corruption.
   7769 */
   7770 #ifdef SQLITE_MAX_PAGE_SIZE
   7771 # undef SQLITE_MAX_PAGE_SIZE
   7772 #endif
   7773 #define SQLITE_MAX_PAGE_SIZE 65536
   7774 
   7775 
   7776 /*
   7777 ** The default size of a database page.
   7778 */
   7779 #ifndef SQLITE_DEFAULT_PAGE_SIZE
   7780 # define SQLITE_DEFAULT_PAGE_SIZE 1024
   7781 #endif
   7782 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
   7783 # undef SQLITE_DEFAULT_PAGE_SIZE
   7784 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
   7785 #endif
   7786 
   7787 /*
   7788 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
   7789 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
   7790 ** device characteristics (sector-size and atomic write() support),
   7791 ** SQLite may choose a larger value. This constant is the maximum value
   7792 ** SQLite will choose on its own.
   7793 */
   7794 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
   7795 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
   7796 #endif
   7797 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
   7798 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
   7799 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
   7800 #endif
   7801 
   7802 
   7803 /*
   7804 ** Maximum number of pages in one database file.
   7805 **
   7806 ** This is really just the default value for the max_page_count pragma.
   7807 ** This value can be lowered (or raised) at run-time using that the
   7808 ** max_page_count macro.
   7809 */
   7810 #ifndef SQLITE_MAX_PAGE_COUNT
   7811 # define SQLITE_MAX_PAGE_COUNT 1073741823
   7812 #endif
   7813 
   7814 /*
   7815 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   7816 ** operator.
   7817 */
   7818 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   7819 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   7820 #endif
   7821 
   7822 /*
   7823 ** Maximum depth of recursion for triggers.
   7824 **
   7825 ** A value of 1 means that a trigger program will not be able to itself
   7826 ** fire any triggers. A value of 0 means that no trigger programs at all
   7827 ** may be executed.
   7828 */
   7829 #ifndef SQLITE_MAX_TRIGGER_DEPTH
   7830 # define SQLITE_MAX_TRIGGER_DEPTH 1000
   7831 #endif
   7832 
   7833 /************** End of sqliteLimit.h *****************************************/
   7834 /************** Continuing where we left off in sqliteInt.h ******************/
   7835 
   7836 /* Disable nuisance warnings on Borland compilers */
   7837 #if defined(__BORLANDC__)
   7838 #pragma warn -rch /* unreachable code */
   7839 #pragma warn -ccc /* Condition is always true or false */
   7840 #pragma warn -aus /* Assigned value is never used */
   7841 #pragma warn -csu /* Comparing signed and unsigned */
   7842 #pragma warn -spa /* Suspicious pointer arithmetic */
   7843 #endif
   7844 
   7845 /* Needed for various definitions... */
   7846 #ifndef _GNU_SOURCE
   7847 # define _GNU_SOURCE
   7848 #endif
   7849 
   7850 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
   7851 # define _BSD_SOURCE
   7852 #endif
   7853 
   7854 /*
   7855 ** Include standard header files as necessary
   7856 */
   7857 #ifdef HAVE_STDINT_H
   7858 #include <stdint.h>
   7859 #endif
   7860 #ifdef HAVE_INTTYPES_H
   7861 #include <inttypes.h>
   7862 #endif
   7863 
   7864 /*
   7865 ** The following macros are used to cast pointers to integers and
   7866 ** integers to pointers.  The way you do this varies from one compiler
   7867 ** to the next, so we have developed the following set of #if statements
   7868 ** to generate appropriate macros for a wide range of compilers.
   7869 **
   7870 ** The correct "ANSI" way to do this is to use the intptr_t type.
   7871 ** Unfortunately, that typedef is not available on all compilers, or
   7872 ** if it is available, it requires an #include of specific headers
   7873 ** that vary from one machine to the next.
   7874 **
   7875 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
   7876 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
   7877 ** So we have to define the macros in different ways depending on the
   7878 ** compiler.
   7879 */
   7880 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
   7881 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
   7882 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
   7883 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
   7884 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
   7885 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
   7886 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
   7887 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
   7888 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
   7889 #else                          /* Generates a warning - but it always works */
   7890 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
   7891 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
   7892 #endif
   7893 
   7894 /*
   7895 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
   7896 ** 0 means mutexes are permanently disable and the library is never
   7897 ** threadsafe.  1 means the library is serialized which is the highest
   7898 ** level of threadsafety.  2 means the library is multithreaded - multiple
   7899 ** threads can use SQLite as long as no two threads try to use the same
   7900 ** database connection at the same time.
   7901 **
   7902 ** Older versions of SQLite used an optional THREADSAFE macro.
   7903 ** We support that for legacy.
   7904 */
   7905 #if !defined(SQLITE_THREADSAFE)
   7906 # if defined(THREADSAFE)
   7907 #   define SQLITE_THREADSAFE THREADSAFE
   7908 # else
   7909 #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
   7910 # endif
   7911 #endif
   7912 
   7913 /*
   7914 ** Powersafe overwrite is on by default.  But can be turned off using
   7915 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
   7916 */
   7917 #ifndef SQLITE_POWERSAFE_OVERWRITE
   7918 # define SQLITE_POWERSAFE_OVERWRITE 1
   7919 #endif
   7920 
   7921 /*
   7922 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
   7923 ** It determines whether or not the features related to
   7924 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
   7925 ** be overridden at runtime using the sqlite3_config() API.
   7926 */
   7927 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
   7928 # define SQLITE_DEFAULT_MEMSTATUS 1
   7929 #endif
   7930 
   7931 /*
   7932 ** Exactly one of the following macros must be defined in order to
   7933 ** specify which memory allocation subsystem to use.
   7934 **
   7935 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
   7936 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
   7937 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
   7938 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
   7939 **
   7940 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
   7941 ** assert() macro is enabled, each call into the Win32 native heap subsystem
   7942 ** will cause HeapValidate to be called.  If heap validation should fail, an
   7943 ** assertion will be triggered.
   7944 **
   7945 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
   7946 ** the default.
   7947 */
   7948 #if defined(SQLITE_SYSTEM_MALLOC) \
   7949   + defined(SQLITE_WIN32_MALLOC) \
   7950   + defined(SQLITE_ZERO_MALLOC) \
   7951   + defined(SQLITE_MEMDEBUG)>1
   7952 # error "Two or more of the following compile-time configuration options\
   7953  are defined but at most one is allowed:\
   7954  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
   7955  SQLITE_ZERO_MALLOC"
   7956 #endif
   7957 #if defined(SQLITE_SYSTEM_MALLOC) \
   7958   + defined(SQLITE_WIN32_MALLOC) \
   7959   + defined(SQLITE_ZERO_MALLOC) \
   7960   + defined(SQLITE_MEMDEBUG)==0
   7961 # define SQLITE_SYSTEM_MALLOC 1
   7962 #endif
   7963 
   7964 /*
   7965 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
   7966 ** sizes of memory allocations below this value where possible.
   7967 */
   7968 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
   7969 # define SQLITE_MALLOC_SOFT_LIMIT 1024
   7970 #endif
   7971 
   7972 /*
   7973 ** We need to define _XOPEN_SOURCE as follows in order to enable
   7974 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
   7975 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
   7976 ** it.
   7977 */
   7978 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
   7979 #  define _XOPEN_SOURCE 600
   7980 #endif
   7981 
   7982 /*
   7983 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
   7984 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
   7985 ** make it true by defining or undefining NDEBUG.
   7986 **
   7987 ** Setting NDEBUG makes the code smaller and faster by disabling the
   7988 ** assert() statements in the code.  So we want the default action
   7989 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
   7990 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
   7991 ** feature.
   7992 */
   7993 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   7994 # define NDEBUG 1
   7995 #endif
   7996 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
   7997 # undef NDEBUG
   7998 #endif
   7999 
   8000 /*
   8001 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
   8002 */
   8003 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
   8004 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
   8005 #endif
   8006 
   8007 /*
   8008 ** The testcase() macro is used to aid in coverage testing.  When
   8009 ** doing coverage testing, the condition inside the argument to
   8010 ** testcase() must be evaluated both true and false in order to
   8011 ** get full branch coverage.  The testcase() macro is inserted
   8012 ** to help ensure adequate test coverage in places where simple
   8013 ** condition/decision coverage is inadequate.  For example, testcase()
   8014 ** can be used to make sure boundary values are tested.  For
   8015 ** bitmask tests, testcase() can be used to make sure each bit
   8016 ** is significant and used at least once.  On switch statements
   8017 ** where multiple cases go to the same block of code, testcase()
   8018 ** can insure that all cases are evaluated.
   8019 **
   8020 */
   8021 #ifdef SQLITE_COVERAGE_TEST
   8022 SQLITE_PRIVATE   void sqlite3Coverage(int);
   8023 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
   8024 #else
   8025 # define testcase(X)
   8026 #endif
   8027 
   8028 /*
   8029 ** The TESTONLY macro is used to enclose variable declarations or
   8030 ** other bits of code that are needed to support the arguments
   8031 ** within testcase() and assert() macros.
   8032 */
   8033 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
   8034 # define TESTONLY(X)  X
   8035 #else
   8036 # define TESTONLY(X)
   8037 #endif
   8038 
   8039 /*
   8040 ** Sometimes we need a small amount of code such as a variable initialization
   8041 ** to setup for a later assert() statement.  We do not want this code to
   8042 ** appear when assert() is disabled.  The following macro is therefore
   8043 ** used to contain that setup code.  The "VVA" acronym stands for
   8044 ** "Verification, Validation, and Accreditation".  In other words, the
   8045 ** code within VVA_ONLY() will only run during verification processes.
   8046 */
   8047 #ifndef NDEBUG
   8048 # define VVA_ONLY(X)  X
   8049 #else
   8050 # define VVA_ONLY(X)
   8051 #endif
   8052 
   8053 /*
   8054 ** The ALWAYS and NEVER macros surround boolean expressions which
   8055 ** are intended to always be true or false, respectively.  Such
   8056 ** expressions could be omitted from the code completely.  But they
   8057 ** are included in a few cases in order to enhance the resilience
   8058 ** of SQLite to unexpected behavior - to make the code "self-healing"
   8059 ** or "ductile" rather than being "brittle" and crashing at the first
   8060 ** hint of unplanned behavior.
   8061 **
   8062 ** In other words, ALWAYS and NEVER are added for defensive code.
   8063 **
   8064 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
   8065 ** be true and false so that the unreachable code they specify will
   8066 ** not be counted as untested code.
   8067 */
   8068 #if defined(SQLITE_COVERAGE_TEST)
   8069 # define ALWAYS(X)      (1)
   8070 # define NEVER(X)       (0)
   8071 #elif !defined(NDEBUG)
   8072 # define ALWAYS(X)      ((X)?1:(assert(0),0))
   8073 # define NEVER(X)       ((X)?(assert(0),1):0)
   8074 #else
   8075 # define ALWAYS(X)      (X)
   8076 # define NEVER(X)       (X)
   8077 #endif
   8078 
   8079 /*
   8080 ** Return true (non-zero) if the input is a integer that is too large
   8081 ** to fit in 32-bits.  This macro is used inside of various testcase()
   8082 ** macros to verify that we have tested SQLite for large-file support.
   8083 */
   8084 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
   8085 
   8086 /*
   8087 ** The macro unlikely() is a hint that surrounds a boolean
   8088 ** expression that is usually false.  Macro likely() surrounds
   8089 ** a boolean expression that is usually true.  These hints could,
   8090 ** in theory, be used by the compiler to generate better code, but
   8091 ** currently they are just comments for human readers.
   8092 */
   8093 #define likely(X)    (X)
   8094 #define unlikely(X)  (X)
   8095 
   8096 /************** Include hash.h in the middle of sqliteInt.h ******************/
   8097 /************** Begin file hash.h ********************************************/
   8098 /*
   8099 ** 2001 September 22
   8100 **
   8101 ** The author disclaims copyright to this source code.  In place of
   8102 ** a legal notice, here is a blessing:
   8103 **
   8104 **    May you do good and not evil.
   8105 **    May you find forgiveness for yourself and forgive others.
   8106 **    May you share freely, never taking more than you give.
   8107 **
   8108 *************************************************************************
   8109 ** This is the header file for the generic hash-table implementation
   8110 ** used in SQLite.
   8111 */
   8112 #ifndef _SQLITE_HASH_H_
   8113 #define _SQLITE_HASH_H_
   8114 
   8115 /* Forward declarations of structures. */
   8116 typedef struct Hash Hash;
   8117 typedef struct HashElem HashElem;
   8118 
   8119 /* A complete hash table is an instance of the following structure.
   8120 ** The internals of this structure are intended to be opaque -- client
   8121 ** code should not attempt to access or modify the fields of this structure
   8122 ** directly.  Change this structure only by using the routines below.
   8123 ** However, some of the "procedures" and "functions" for modifying and
   8124 ** accessing this structure are really macros, so we can't really make
   8125 ** this structure opaque.
   8126 **
   8127 ** All elements of the hash table are on a single doubly-linked list.
   8128 ** Hash.first points to the head of this list.
   8129 **
   8130 ** There are Hash.htsize buckets.  Each bucket points to a spot in
   8131 ** the global doubly-linked list.  The contents of the bucket are the
   8132 ** element pointed to plus the next _ht.count-1 elements in the list.
   8133 **
   8134 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
   8135 ** by a linear search of the global list.  For small tables, the
   8136 ** Hash.ht table is never allocated because if there are few elements
   8137 ** in the table, it is faster to do a linear search than to manage
   8138 ** the hash table.
   8139 */
   8140 struct Hash {
   8141   unsigned int htsize;      /* Number of buckets in the hash table */
   8142   unsigned int count;       /* Number of entries in this table */
   8143   HashElem *first;          /* The first element of the array */
   8144   struct _ht {              /* the hash table */
   8145     int count;                 /* Number of entries with this hash */
   8146     HashElem *chain;           /* Pointer to first entry with this hash */
   8147   } *ht;
   8148 };
   8149 
   8150 /* Each element in the hash table is an instance of the following
   8151 ** structure.  All elements are stored on a single doubly-linked list.
   8152 **
   8153 ** Again, this structure is intended to be opaque, but it can't really
   8154 ** be opaque because it is used by macros.
   8155 */
   8156 struct HashElem {
   8157   HashElem *next, *prev;       /* Next and previous elements in the table */
   8158   void *data;                  /* Data associated with this element */
   8159   const char *pKey; int nKey;  /* Key associated with this element */
   8160 };
   8161 
   8162 /*
   8163 ** Access routines.  To delete, insert a NULL pointer.
   8164 */
   8165 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
   8166 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
   8167 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
   8168 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
   8169 
   8170 /*
   8171 ** Macros for looping over all elements of a hash table.  The idiom is
   8172 ** like this:
   8173 **
   8174 **   Hash h;
   8175 **   HashElem *p;
   8176 **   ...
   8177 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
   8178 **     SomeStructure *pData = sqliteHashData(p);
   8179 **     // do something with pData
   8180 **   }
   8181 */
   8182 #define sqliteHashFirst(H)  ((H)->first)
   8183 #define sqliteHashNext(E)   ((E)->next)
   8184 #define sqliteHashData(E)   ((E)->data)
   8185 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
   8186 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
   8187 
   8188 /*
   8189 ** Number of entries in a hash table
   8190 */
   8191 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
   8192 
   8193 #endif /* _SQLITE_HASH_H_ */
   8194 
   8195 /************** End of hash.h ************************************************/
   8196 /************** Continuing where we left off in sqliteInt.h ******************/
   8197 /************** Include parse.h in the middle of sqliteInt.h *****************/
   8198 /************** Begin file parse.h *******************************************/
   8199 #define TK_SEMI                             1
   8200 #define TK_EXPLAIN                          2
   8201 #define TK_QUERY                            3
   8202 #define TK_PLAN                             4
   8203 #define TK_BEGIN                            5
   8204 #define TK_TRANSACTION                      6
   8205 #define TK_DEFERRED                         7
   8206 #define TK_IMMEDIATE                        8
   8207 #define TK_EXCLUSIVE                        9
   8208 #define TK_COMMIT                          10
   8209 #define TK_END                             11
   8210 #define TK_ROLLBACK                        12
   8211 #define TK_SAVEPOINT                       13
   8212 #define TK_RELEASE                         14
   8213 #define TK_TO                              15
   8214 #define TK_TABLE                           16
   8215 #define TK_CREATE                          17
   8216 #define TK_IF                              18
   8217 #define TK_NOT                             19
   8218 #define TK_EXISTS                          20
   8219 #define TK_TEMP                            21
   8220 #define TK_LP                              22
   8221 #define TK_RP                              23
   8222 #define TK_AS                              24
   8223 #define TK_WITHOUT                         25
   8224 #define TK_COMMA                           26
   8225 #define TK_ID                              27
   8226 #define TK_INDEXED                         28
   8227 #define TK_ABORT                           29
   8228 #define TK_ACTION                          30
   8229 #define TK_AFTER                           31
   8230 #define TK_ANALYZE                         32
   8231 #define TK_ASC                             33
   8232 #define TK_ATTACH                          34
   8233 #define TK_BEFORE                          35
   8234 #define TK_BY                              36
   8235 #define TK_CASCADE                         37
   8236 #define TK_CAST                            38
   8237 #define TK_COLUMNKW                        39
   8238 #define TK_CONFLICT                        40
   8239 #define TK_DATABASE                        41
   8240 #define TK_DESC                            42
   8241 #define TK_DETACH                          43
   8242 #define TK_EACH                            44
   8243 #define TK_FAIL                            45
   8244 #define TK_FOR                             46
   8245 #define TK_IGNORE                          47
   8246 #define TK_INITIALLY                       48
   8247 #define TK_INSTEAD                         49
   8248 #define TK_LIKE_KW                         50
   8249 #define TK_MATCH                           51
   8250 #define TK_NO                              52
   8251 #define TK_KEY                             53
   8252 #define TK_OF                              54
   8253 #define TK_OFFSET                          55
   8254 #define TK_PRAGMA                          56
   8255 #define TK_RAISE                           57
   8256 #define TK_RECURSIVE                       58
   8257 #define TK_REPLACE                         59
   8258 #define TK_RESTRICT                        60
   8259 #define TK_ROW                             61
   8260 #define TK_TRIGGER                         62
   8261 #define TK_VACUUM                          63
   8262 #define TK_VIEW                            64
   8263 #define TK_VIRTUAL                         65
   8264 #define TK_WITH                            66
   8265 #define TK_REINDEX                         67
   8266 #define TK_RENAME                          68
   8267 #define TK_CTIME_KW                        69
   8268 #define TK_ANY                             70
   8269 #define TK_OR                              71
   8270 #define TK_AND                             72
   8271 #define TK_IS                              73
   8272 #define TK_BETWEEN                         74
   8273 #define TK_IN                              75
   8274 #define TK_ISNULL                          76
   8275 #define TK_NOTNULL                         77
   8276 #define TK_NE                              78
   8277 #define TK_EQ                              79
   8278 #define TK_GT                              80
   8279 #define TK_LE                              81
   8280 #define TK_LT                              82
   8281 #define TK_GE                              83
   8282 #define TK_ESCAPE                          84
   8283 #define TK_BITAND                          85
   8284 #define TK_BITOR                           86
   8285 #define TK_LSHIFT                          87
   8286 #define TK_RSHIFT                          88
   8287 #define TK_PLUS                            89
   8288 #define TK_MINUS                           90
   8289 #define TK_STAR                            91
   8290 #define TK_SLASH                           92
   8291 #define TK_REM                             93
   8292 #define TK_CONCAT                          94
   8293 #define TK_COLLATE                         95
   8294 #define TK_BITNOT                          96
   8295 #define TK_STRING                          97
   8296 #define TK_JOIN_KW                         98
   8297 #define TK_CONSTRAINT                      99
   8298 #define TK_DEFAULT                        100
   8299 #define TK_NULL                           101
   8300 #define TK_PRIMARY                        102
   8301 #define TK_UNIQUE                         103
   8302 #define TK_CHECK                          104
   8303 #define TK_REFERENCES                     105
   8304 #define TK_AUTOINCR                       106
   8305 #define TK_ON                             107
   8306 #define TK_INSERT                         108
   8307 #define TK_DELETE                         109
   8308 #define TK_UPDATE                         110
   8309 #define TK_SET                            111
   8310 #define TK_DEFERRABLE                     112
   8311 #define TK_FOREIGN                        113
   8312 #define TK_DROP                           114
   8313 #define TK_UNION                          115
   8314 #define TK_ALL                            116
   8315 #define TK_EXCEPT                         117
   8316 #define TK_INTERSECT                      118
   8317 #define TK_SELECT                         119
   8318 #define TK_VALUES                         120
   8319 #define TK_DISTINCT                       121
   8320 #define TK_DOT                            122
   8321 #define TK_FROM                           123
   8322 #define TK_JOIN                           124
   8323 #define TK_USING                          125
   8324 #define TK_ORDER                          126
   8325 #define TK_GROUP                          127
   8326 #define TK_HAVING                         128
   8327 #define TK_LIMIT                          129
   8328 #define TK_WHERE                          130
   8329 #define TK_INTO                           131
   8330 #define TK_INTEGER                        132
   8331 #define TK_FLOAT                          133
   8332 #define TK_BLOB                           134
   8333 #define TK_VARIABLE                       135
   8334 #define TK_CASE                           136
   8335 #define TK_WHEN                           137
   8336 #define TK_THEN                           138
   8337 #define TK_ELSE                           139
   8338 #define TK_INDEX                          140
   8339 #define TK_ALTER                          141
   8340 #define TK_ADD                            142
   8341 #define TK_TO_TEXT                        143
   8342 #define TK_TO_BLOB                        144
   8343 #define TK_TO_NUMERIC                     145
   8344 #define TK_TO_INT                         146
   8345 #define TK_TO_REAL                        147
   8346 #define TK_ISNOT                          148
   8347 #define TK_END_OF_FILE                    149
   8348 #define TK_ILLEGAL                        150
   8349 #define TK_SPACE                          151
   8350 #define TK_UNCLOSED_STRING                152
   8351 #define TK_FUNCTION                       153
   8352 #define TK_COLUMN                         154
   8353 #define TK_AGG_FUNCTION                   155
   8354 #define TK_AGG_COLUMN                     156
   8355 #define TK_UMINUS                         157
   8356 #define TK_UPLUS                          158
   8357 #define TK_REGISTER                       159
   8358 
   8359 /************** End of parse.h ***********************************************/
   8360 /************** Continuing where we left off in sqliteInt.h ******************/
   8361 #include <stdio.h>
   8362 #include <stdlib.h>
   8363 #include <string.h>
   8364 #include <assert.h>
   8365 #include <stddef.h>
   8366 
   8367 /*
   8368 ** If compiling for a processor that lacks floating point support,
   8369 ** substitute integer for floating-point
   8370 */
   8371 #ifdef SQLITE_OMIT_FLOATING_POINT
   8372 # define double sqlite_int64
   8373 # define float sqlite_int64
   8374 # define LONGDOUBLE_TYPE sqlite_int64
   8375 # ifndef SQLITE_BIG_DBL
   8376 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
   8377 # endif
   8378 # define SQLITE_OMIT_DATETIME_FUNCS 1
   8379 # define SQLITE_OMIT_TRACE 1
   8380 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   8381 # undef SQLITE_HAVE_ISNAN
   8382 #endif
   8383 #ifndef SQLITE_BIG_DBL
   8384 # define SQLITE_BIG_DBL (1e99)
   8385 #endif
   8386 
   8387 /*
   8388 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
   8389 ** afterward. Having this macro allows us to cause the C compiler
   8390 ** to omit code used by TEMP tables without messy #ifndef statements.
   8391 */
   8392 #ifdef SQLITE_OMIT_TEMPDB
   8393 #define OMIT_TEMPDB 1
   8394 #else
   8395 #define OMIT_TEMPDB 0
   8396 #endif
   8397 
   8398 /*
   8399 ** The "file format" number is an integer that is incremented whenever
   8400 ** the VDBE-level file format changes.  The following macros define the
   8401 ** the default file format for new databases and the maximum file format
   8402 ** that the library can read.
   8403 */
   8404 #define SQLITE_MAX_FILE_FORMAT 4
   8405 #ifndef SQLITE_DEFAULT_FILE_FORMAT
   8406 # define SQLITE_DEFAULT_FILE_FORMAT 4
   8407 #endif
   8408 
   8409 /*
   8410 ** Determine whether triggers are recursive by default.  This can be
   8411 ** changed at run-time using a pragma.
   8412 */
   8413 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   8414 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
   8415 #endif
   8416 
   8417 /*
   8418 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
   8419 ** on the command-line
   8420 */
   8421 #ifndef SQLITE_TEMP_STORE
   8422 # define SQLITE_TEMP_STORE 1
   8423 # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
   8424 #endif
   8425 
   8426 /*
   8427 ** GCC does not define the offsetof() macro so we'll have to do it
   8428 ** ourselves.
   8429 */
   8430 #ifndef offsetof
   8431 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
   8432 #endif
   8433 
   8434 /*
   8435 ** Macros to compute minimum and maximum of two numbers.
   8436 */
   8437 #define MIN(A,B) ((A)<(B)?(A):(B))
   8438 #define MAX(A,B) ((A)>(B)?(A):(B))
   8439 
   8440 /*
   8441 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
   8442 ** not, there are still machines out there that use EBCDIC.)
   8443 */
   8444 #if 'A' == '\301'
   8445 # define SQLITE_EBCDIC 1
   8446 #else
   8447 # define SQLITE_ASCII 1
   8448 #endif
   8449 
   8450 /*
   8451 ** Integers of known sizes.  These typedefs might change for architectures
   8452 ** where the sizes very.  Preprocessor macros are available so that the
   8453 ** types can be conveniently redefined at compile-type.  Like this:
   8454 **
   8455 **         cc '-DUINTPTR_TYPE=long long int' ...
   8456 */
   8457 #ifndef UINT32_TYPE
   8458 # ifdef HAVE_UINT32_T
   8459 #  define UINT32_TYPE uint32_t
   8460 # else
   8461 #  define UINT32_TYPE unsigned int
   8462 # endif
   8463 #endif
   8464 #ifndef UINT16_TYPE
   8465 # ifdef HAVE_UINT16_T
   8466 #  define UINT16_TYPE uint16_t
   8467 # else
   8468 #  define UINT16_TYPE unsigned short int
   8469 # endif
   8470 #endif
   8471 #ifndef INT16_TYPE
   8472 # ifdef HAVE_INT16_T
   8473 #  define INT16_TYPE int16_t
   8474 # else
   8475 #  define INT16_TYPE short int
   8476 # endif
   8477 #endif
   8478 #ifndef UINT8_TYPE
   8479 # ifdef HAVE_UINT8_T
   8480 #  define UINT8_TYPE uint8_t
   8481 # else
   8482 #  define UINT8_TYPE unsigned char
   8483 # endif
   8484 #endif
   8485 #ifndef INT8_TYPE
   8486 # ifdef HAVE_INT8_T
   8487 #  define INT8_TYPE int8_t
   8488 # else
   8489 #  define INT8_TYPE signed char
   8490 # endif
   8491 #endif
   8492 #ifndef LONGDOUBLE_TYPE
   8493 # define LONGDOUBLE_TYPE long double
   8494 #endif
   8495 typedef sqlite_int64 i64;          /* 8-byte signed integer */
   8496 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
   8497 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
   8498 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
   8499 typedef INT16_TYPE i16;            /* 2-byte signed integer */
   8500 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
   8501 typedef INT8_TYPE i8;              /* 1-byte signed integer */
   8502 
   8503 /*
   8504 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
   8505 ** that can be stored in a u32 without loss of data.  The value
   8506 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
   8507 ** have to specify the value in the less intuitive manner shown:
   8508 */
   8509 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
   8510 
   8511 /*
   8512 ** The datatype used to store estimates of the number of rows in a
   8513 ** table or index.  This is an unsigned integer type.  For 99.9% of
   8514 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
   8515 ** can be used at compile-time if desired.
   8516 */
   8517 #ifdef SQLITE_64BIT_STATS
   8518  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
   8519 #else
   8520  typedef u32 tRowcnt;    /* 32-bit is the default */
   8521 #endif
   8522 
   8523 /*
   8524 ** Estimated quantities used for query planning are stored as 16-bit
   8525 ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
   8526 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
   8527 ** But the allowed values are "grainy".  Not every value is representable.
   8528 ** For example, quantities 16 and 17 are both represented by a LogEst
   8529 ** of 40.  However, since LogEst quantaties are suppose to be estimates,
   8530 ** not exact values, this imprecision is not a problem.
   8531 **
   8532 ** "LogEst" is short for "Logarithmic Estimate".
   8533 **
   8534 ** Examples:
   8535 **      1 -> 0              20 -> 43          10000 -> 132
   8536 **      2 -> 10             25 -> 46          25000 -> 146
   8537 **      3 -> 16            100 -> 66        1000000 -> 199
   8538 **      4 -> 20           1000 -> 99        1048576 -> 200
   8539 **     10 -> 33           1024 -> 100    4294967296 -> 320
   8540 **
   8541 ** The LogEst can be negative to indicate fractional values.
   8542 ** Examples:
   8543 **
   8544 **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
   8545 */
   8546 typedef INT16_TYPE LogEst;
   8547 
   8548 /*
   8549 ** Macros to determine whether the machine is big or little endian,
   8550 ** and whether or not that determination is run-time or compile-time.
   8551 **
   8552 ** For best performance, an attempt is made to guess at the byte-order
   8553 ** using C-preprocessor macros.  If that is unsuccessful, or if
   8554 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
   8555 ** at run-time.
   8556 */
   8557 #ifdef SQLITE_AMALGAMATION
   8558 SQLITE_PRIVATE const int sqlite3one = 1;
   8559 #else
   8560 SQLITE_PRIVATE const int sqlite3one;
   8561 #endif
   8562 #if (defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
   8563      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
   8564      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
   8565      defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
   8566 # define SQLITE_BYTEORDER    1234
   8567 # define SQLITE_BIGENDIAN    0
   8568 # define SQLITE_LITTLEENDIAN 1
   8569 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
   8570 #endif
   8571 #if (defined(sparc)    || defined(__ppc__))  \
   8572     && !defined(SQLITE_RUNTIME_BYTEORDER)
   8573 # define SQLITE_BYTEORDER    4321
   8574 # define SQLITE_BIGENDIAN    1
   8575 # define SQLITE_LITTLEENDIAN 0
   8576 # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
   8577 #endif
   8578 #if !defined(SQLITE_BYTEORDER)
   8579 # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
   8580 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
   8581 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
   8582 # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
   8583 #endif
   8584 
   8585 /*
   8586 ** Constants for the largest and smallest possible 64-bit signed integers.
   8587 ** These macros are designed to work correctly on both 32-bit and 64-bit
   8588 ** compilers.
   8589 */
   8590 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
   8591 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
   8592 
   8593 /*
   8594 ** Round up a number to the next larger multiple of 8.  This is used
   8595 ** to force 8-byte alignment on 64-bit architectures.
   8596 */
   8597 #define ROUND8(x)     (((x)+7)&~7)
   8598 
   8599 /*
   8600 ** Round down to the nearest multiple of 8
   8601 */
   8602 #define ROUNDDOWN8(x) ((x)&~7)
   8603 
   8604 /*
   8605 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
   8606 ** macro is used only within assert() to verify that the code gets
   8607 ** all alignment restrictions correct.
   8608 **
   8609 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
   8610 ** underlying malloc() implemention might return us 4-byte aligned
   8611 ** pointers.  In that case, only verify 4-byte alignment.
   8612 */
   8613 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   8614 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
   8615 #else
   8616 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
   8617 #endif
   8618 
   8619 /*
   8620 ** Disable MMAP on platforms where it is known to not work
   8621 */
   8622 #if defined(__OpenBSD__) || defined(__QNXNTO__)
   8623 # undef SQLITE_MAX_MMAP_SIZE
   8624 # define SQLITE_MAX_MMAP_SIZE 0
   8625 #endif
   8626 
   8627 /*
   8628 ** Default maximum size of memory used by memory-mapped I/O in the VFS
   8629 */
   8630 #ifdef __APPLE__
   8631 # include <TargetConditionals.h>
   8632 # if TARGET_OS_IPHONE
   8633 #   undef SQLITE_MAX_MMAP_SIZE
   8634 #   define SQLITE_MAX_MMAP_SIZE 0
   8635 # endif
   8636 #endif
   8637 #ifndef SQLITE_MAX_MMAP_SIZE
   8638 # if defined(__linux__) \
   8639   || defined(_WIN32) \
   8640   || (defined(__APPLE__) && defined(__MACH__)) \
   8641   || defined(__sun)
   8642 #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
   8643 # else
   8644 #   define SQLITE_MAX_MMAP_SIZE 0
   8645 # endif
   8646 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
   8647 #endif
   8648 
   8649 /*
   8650 ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
   8651 ** default MMAP_SIZE is specified at compile-time, make sure that it does
   8652 ** not exceed the maximum mmap size.
   8653 */
   8654 #ifndef SQLITE_DEFAULT_MMAP_SIZE
   8655 # define SQLITE_DEFAULT_MMAP_SIZE 0
   8656 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
   8657 #endif
   8658 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
   8659 # undef SQLITE_DEFAULT_MMAP_SIZE
   8660 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
   8661 #endif
   8662 
   8663 /*
   8664 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
   8665 ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
   8666 ** define SQLITE_ENABLE_STAT3_OR_STAT4
   8667 */
   8668 #ifdef SQLITE_ENABLE_STAT4
   8669 # undef SQLITE_ENABLE_STAT3
   8670 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
   8671 #elif SQLITE_ENABLE_STAT3
   8672 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
   8673 #elif SQLITE_ENABLE_STAT3_OR_STAT4
   8674 # undef SQLITE_ENABLE_STAT3_OR_STAT4
   8675 #endif
   8676 
   8677 /*
   8678 ** An instance of the following structure is used to store the busy-handler
   8679 ** callback for a given sqlite handle.
   8680 **
   8681 ** The sqlite.busyHandler member of the sqlite struct contains the busy
   8682 ** callback for the database handle. Each pager opened via the sqlite
   8683 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
   8684 ** callback is currently invoked only from within pager.c.
   8685 */
   8686 typedef struct BusyHandler BusyHandler;
   8687 struct BusyHandler {
   8688   int (*xFunc)(void *,int);  /* The busy callback */
   8689   void *pArg;                /* First arg to busy callback */
   8690   int nBusy;                 /* Incremented with each busy call */
   8691 };
   8692 
   8693 /*
   8694 ** Name of the master database table.  The master database table
   8695 ** is a special table that holds the names and attributes of all
   8696 ** user tables and indices.
   8697 */
   8698 #define MASTER_NAME       "sqlite_master"
   8699 #define TEMP_MASTER_NAME  "sqlite_temp_master"
   8700 
   8701 /*
   8702 ** The root-page of the master database table.
   8703 */
   8704 #define MASTER_ROOT       1
   8705 
   8706 /*
   8707 ** The name of the schema table.
   8708 */
   8709 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
   8710 
   8711 /*
   8712 ** A convenience macro that returns the number of elements in
   8713 ** an array.
   8714 */
   8715 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
   8716 
   8717 /*
   8718 ** Determine if the argument is a power of two
   8719 */
   8720 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
   8721 
   8722 /*
   8723 ** The following value as a destructor means to use sqlite3DbFree().
   8724 ** The sqlite3DbFree() routine requires two parameters instead of the
   8725 ** one parameter that destructors normally want.  So we have to introduce
   8726 ** this magic value that the code knows to handle differently.  Any
   8727 ** pointer will work here as long as it is distinct from SQLITE_STATIC
   8728 ** and SQLITE_TRANSIENT.
   8729 */
   8730 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
   8731 
   8732 /*
   8733 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
   8734 ** not support Writable Static Data (WSD) such as global and static variables.
   8735 ** All variables must either be on the stack or dynamically allocated from
   8736 ** the heap.  When WSD is unsupported, the variable declarations scattered
   8737 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
   8738 ** macro is used for this purpose.  And instead of referencing the variable
   8739 ** directly, we use its constant as a key to lookup the run-time allocated
   8740 ** buffer that holds real variable.  The constant is also the initializer
   8741 ** for the run-time allocated buffer.
   8742 **
   8743 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
   8744 ** macros become no-ops and have zero performance impact.
   8745 */
   8746 #ifdef SQLITE_OMIT_WSD
   8747   #define SQLITE_WSD const
   8748   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
   8749   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
   8750 SQLITE_API   int sqlite3_wsd_init(int N, int J);
   8751 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
   8752 #else
   8753   #define SQLITE_WSD
   8754   #define GLOBAL(t,v) v
   8755   #define sqlite3GlobalConfig sqlite3Config
   8756 #endif
   8757 
   8758 /*
   8759 ** The following macros are used to suppress compiler warnings and to
   8760 ** make it clear to human readers when a function parameter is deliberately
   8761 ** left unused within the body of a function. This usually happens when
   8762 ** a function is called via a function pointer. For example the
   8763 ** implementation of an SQL aggregate step callback may not use the
   8764 ** parameter indicating the number of arguments passed to the aggregate,
   8765 ** if it knows that this is enforced elsewhere.
   8766 **
   8767 ** When a function parameter is not used at all within the body of a function,
   8768 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
   8769 ** However, these macros may also be used to suppress warnings related to
   8770 ** parameters that may or may not be used depending on compilation options.
   8771 ** For example those parameters only used in assert() statements. In these
   8772 ** cases the parameters are named as per the usual conventions.
   8773 */
   8774 #define UNUSED_PARAMETER(x) (void)(x)
   8775 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
   8776 
   8777 /*
   8778 ** Forward references to structures
   8779 */
   8780 typedef struct AggInfo AggInfo;
   8781 typedef struct AuthContext AuthContext;
   8782 typedef struct AutoincInfo AutoincInfo;
   8783 typedef struct Bitvec Bitvec;
   8784 typedef struct CollSeq CollSeq;
   8785 typedef struct Column Column;
   8786 typedef struct Db Db;
   8787 typedef struct Schema Schema;
   8788 typedef struct Expr Expr;
   8789 typedef struct ExprList ExprList;
   8790 typedef struct ExprSpan ExprSpan;
   8791 typedef struct FKey FKey;
   8792 typedef struct FuncDestructor FuncDestructor;
   8793 typedef struct FuncDef FuncDef;
   8794 typedef struct FuncDefHash FuncDefHash;
   8795 typedef struct IdList IdList;
   8796 typedef struct Index Index;
   8797 typedef struct IndexSample IndexSample;
   8798 typedef struct KeyClass KeyClass;
   8799 typedef struct KeyInfo KeyInfo;
   8800 typedef struct Lookaside Lookaside;
   8801 typedef struct LookasideSlot LookasideSlot;
   8802 typedef struct Module Module;
   8803 typedef struct NameContext NameContext;
   8804 typedef struct Parse Parse;
   8805 typedef struct PrintfArguments PrintfArguments;
   8806 typedef struct RowSet RowSet;
   8807 typedef struct Savepoint Savepoint;
   8808 typedef struct Select Select;
   8809 typedef struct SelectDest SelectDest;
   8810 typedef struct SrcList SrcList;
   8811 typedef struct StrAccum StrAccum;
   8812 typedef struct Table Table;
   8813 typedef struct TableLock TableLock;
   8814 typedef struct Token Token;
   8815 typedef struct Trigger Trigger;
   8816 typedef struct TriggerPrg TriggerPrg;
   8817 typedef struct TriggerStep TriggerStep;
   8818 typedef struct UnpackedRecord UnpackedRecord;
   8819 typedef struct VTable VTable;
   8820 typedef struct VtabCtx VtabCtx;
   8821 typedef struct Walker Walker;
   8822 typedef struct WhereInfo WhereInfo;
   8823 typedef struct With With;
   8824 
   8825 /*
   8826 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
   8827 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
   8828 ** pointer types (i.e. FuncDef) defined above.
   8829 */
   8830 /************** Include btree.h in the middle of sqliteInt.h *****************/
   8831 /************** Begin file btree.h *******************************************/
   8832 /*
   8833 ** 2001 September 15
   8834 **
   8835 ** The author disclaims copyright to this source code.  In place of
   8836 ** a legal notice, here is a blessing:
   8837 **
   8838 **    May you do good and not evil.
   8839 **    May you find forgiveness for yourself and forgive others.
   8840 **    May you share freely, never taking more than you give.
   8841 **
   8842 *************************************************************************
   8843 ** This header file defines the interface that the sqlite B-Tree file
   8844 ** subsystem.  See comments in the source code for a detailed description
   8845 ** of what each interface routine does.
   8846 */
   8847 #ifndef _BTREE_H_
   8848 #define _BTREE_H_
   8849 
   8850 /* TODO: This definition is just included so other modules compile. It
   8851 ** needs to be revisited.
   8852 */
   8853 #define SQLITE_N_BTREE_META 10
   8854 
   8855 /*
   8856 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
   8857 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
   8858 */
   8859 #ifndef SQLITE_DEFAULT_AUTOVACUUM
   8860   #define SQLITE_DEFAULT_AUTOVACUUM 0
   8861 #endif
   8862 
   8863 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
   8864 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
   8865 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
   8866 
   8867 /*
   8868 ** Forward declarations of structure
   8869 */
   8870 typedef struct Btree Btree;
   8871 typedef struct BtCursor BtCursor;
   8872 typedef struct BtShared BtShared;
   8873 
   8874 
   8875 SQLITE_PRIVATE int sqlite3BtreeOpen(
   8876   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
   8877   const char *zFilename,   /* Name of database file to open */
   8878   sqlite3 *db,             /* Associated database connection */
   8879   Btree **ppBtree,         /* Return open Btree* here */
   8880   int flags,               /* Flags */
   8881   int vfsFlags             /* Flags passed through to VFS open */
   8882 );
   8883 
   8884 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
   8885 ** following values.
   8886 **
   8887 ** NOTE:  These values must match the corresponding PAGER_ values in
   8888 ** pager.h.
   8889 */
   8890 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
   8891 #define BTREE_MEMORY        2  /* This is an in-memory DB */
   8892 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
   8893 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
   8894 
   8895 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
   8896 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
   8897 #if SQLITE_MAX_MMAP_SIZE>0
   8898 SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
   8899 #endif
   8900 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
   8901 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
   8902 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
   8903 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
   8904 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
   8905 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
   8906 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
   8907 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
   8908 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
   8909 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
   8910 #endif
   8911 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
   8912 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
   8913 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
   8914 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
   8915 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
   8916 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
   8917 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
   8918 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
   8919 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
   8920 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
   8921 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
   8922 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
   8923 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
   8924 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
   8925 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
   8926 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
   8927 
   8928 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
   8929 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
   8930 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
   8931 
   8932 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
   8933 
   8934 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
   8935 ** of the flags shown below.
   8936 **
   8937 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
   8938 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
   8939 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
   8940 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
   8941 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
   8942 ** indices.)
   8943 */
   8944 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
   8945 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
   8946 
   8947 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
   8948 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
   8949 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
   8950 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
   8951 
   8952 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
   8953 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
   8954 
   8955 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
   8956 
   8957 /*
   8958 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
   8959 ** should be one of the following values. The integer values are assigned
   8960 ** to constants so that the offset of the corresponding field in an
   8961 ** SQLite database header may be found using the following formula:
   8962 **
   8963 **   offset = 36 + (idx * 4)
   8964 **
   8965 ** For example, the free-page-count field is located at byte offset 36 of
   8966 ** the database file header. The incr-vacuum-flag field is located at
   8967 ** byte offset 64 (== 36+4*7).
   8968 */
   8969 #define BTREE_FREE_PAGE_COUNT     0
   8970 #define BTREE_SCHEMA_VERSION      1
   8971 #define BTREE_FILE_FORMAT         2
   8972 #define BTREE_DEFAULT_CACHE_SIZE  3
   8973 #define BTREE_LARGEST_ROOT_PAGE   4
   8974 #define BTREE_TEXT_ENCODING       5
   8975 #define BTREE_USER_VERSION        6
   8976 #define BTREE_INCR_VACUUM         7
   8977 #define BTREE_APPLICATION_ID      8
   8978 
   8979 /*
   8980 ** Values that may be OR'd together to form the second argument of an
   8981 ** sqlite3BtreeCursorHints() call.
   8982 */
   8983 #define BTREE_BULKLOAD 0x00000001
   8984 
   8985 SQLITE_PRIVATE int sqlite3BtreeCursor(
   8986   Btree*,                              /* BTree containing table to open */
   8987   int iTable,                          /* Index of root page */
   8988   int wrFlag,                          /* 1 for writing.  0 for read-only */
   8989   struct KeyInfo*,                     /* First argument to compare function */
   8990   BtCursor *pCursor                    /* Space to write cursor structure */
   8991 );
   8992 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
   8993 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
   8994 
   8995 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
   8996 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   8997   BtCursor*,
   8998   UnpackedRecord *pUnKey,
   8999   i64 intKey,
   9000   int bias,
   9001   int *pRes
   9002 );
   9003 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
   9004 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
   9005 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
   9006                                   const void *pData, int nData,
   9007                                   int nZero, int bias, int seekResult);
   9008 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
   9009 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
   9010 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
   9011 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
   9012 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
   9013 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
   9014 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
   9015 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
   9016 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
   9017 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
   9018 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
   9019 
   9020 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
   9021 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
   9022 
   9023 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
   9024 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
   9025 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
   9026 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
   9027 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
   9028 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
   9029 
   9030 #ifndef NDEBUG
   9031 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
   9032 #endif
   9033 
   9034 #ifndef SQLITE_OMIT_BTREECOUNT
   9035 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
   9036 #endif
   9037 
   9038 #ifdef SQLITE_TEST
   9039 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
   9040 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
   9041 #endif
   9042 
   9043 #ifndef SQLITE_OMIT_WAL
   9044 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
   9045 #endif
   9046 
   9047 /*
   9048 ** If we are not using shared cache, then there is no need to
   9049 ** use mutexes to access the BtShared structures.  So make the
   9050 ** Enter and Leave procedures no-ops.
   9051 */
   9052 #ifndef SQLITE_OMIT_SHARED_CACHE
   9053 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
   9054 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
   9055 #else
   9056 # define sqlite3BtreeEnter(X)
   9057 # define sqlite3BtreeEnterAll(X)
   9058 #endif
   9059 
   9060 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
   9061 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
   9062 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
   9063 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
   9064 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
   9065 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
   9066 #ifndef NDEBUG
   9067   /* These routines are used inside assert() statements only. */
   9068 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
   9069 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
   9070 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
   9071 #endif
   9072 #else
   9073 
   9074 # define sqlite3BtreeSharable(X) 0
   9075 # define sqlite3BtreeLeave(X)
   9076 # define sqlite3BtreeEnterCursor(X)
   9077 # define sqlite3BtreeLeaveCursor(X)
   9078 # define sqlite3BtreeLeaveAll(X)
   9079 
   9080 # define sqlite3BtreeHoldsMutex(X) 1
   9081 # define sqlite3BtreeHoldsAllMutexes(X) 1
   9082 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
   9083 #endif
   9084 
   9085 
   9086 #endif /* _BTREE_H_ */
   9087 
   9088 /************** End of btree.h ***********************************************/
   9089 /************** Continuing where we left off in sqliteInt.h ******************/
   9090 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
   9091 /************** Begin file vdbe.h ********************************************/
   9092 /*
   9093 ** 2001 September 15
   9094 **
   9095 ** The author disclaims copyright to this source code.  In place of
   9096 ** a legal notice, here is a blessing:
   9097 **
   9098 **    May you do good and not evil.
   9099 **    May you find forgiveness for yourself and forgive others.
   9100 **    May you share freely, never taking more than you give.
   9101 **
   9102 *************************************************************************
   9103 ** Header file for the Virtual DataBase Engine (VDBE)
   9104 **
   9105 ** This header defines the interface to the virtual database engine
   9106 ** or VDBE.  The VDBE implements an abstract machine that runs a
   9107 ** simple program to access and modify the underlying database.
   9108 */
   9109 #ifndef _SQLITE_VDBE_H_
   9110 #define _SQLITE_VDBE_H_
   9111 /* #include <stdio.h> */
   9112 
   9113 /*
   9114 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
   9115 ** in the source file sqliteVdbe.c are allowed to see the insides
   9116 ** of this structure.
   9117 */
   9118 typedef struct Vdbe Vdbe;
   9119 
   9120 /*
   9121 ** The names of the following types declared in vdbeInt.h are required
   9122 ** for the VdbeOp definition.
   9123 */
   9124 typedef struct Mem Mem;
   9125 typedef struct SubProgram SubProgram;
   9126 
   9127 /*
   9128 ** A single instruction of the virtual machine has an opcode
   9129 ** and as many as three operands.  The instruction is recorded
   9130 ** as an instance of the following structure:
   9131 */
   9132 struct VdbeOp {
   9133   u8 opcode;          /* What operation to perform */
   9134   signed char p4type; /* One of the P4_xxx constants for p4 */
   9135   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
   9136   u8 p5;              /* Fifth parameter is an unsigned character */
   9137   int p1;             /* First operand */
   9138   int p2;             /* Second parameter (often the jump destination) */
   9139   int p3;             /* The third parameter */
   9140   union {             /* fourth parameter */
   9141     int i;                 /* Integer value if p4type==P4_INT32 */
   9142     void *p;               /* Generic pointer */
   9143     char *z;               /* Pointer to data for string (char array) types */
   9144     i64 *pI64;             /* Used when p4type is P4_INT64 */
   9145     double *pReal;         /* Used when p4type is P4_REAL */
   9146     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
   9147     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
   9148     Mem *pMem;             /* Used when p4type is P4_MEM */
   9149     VTable *pVtab;         /* Used when p4type is P4_VTAB */
   9150     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
   9151     int *ai;               /* Used when p4type is P4_INTARRAY */
   9152     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
   9153     int (*xAdvance)(BtCursor *, int *);
   9154   } p4;
   9155 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   9156   char *zComment;          /* Comment to improve readability */
   9157 #endif
   9158 #ifdef VDBE_PROFILE
   9159   u32 cnt;                 /* Number of times this instruction was executed */
   9160   u64 cycles;              /* Total time spent executing this instruction */
   9161 #endif
   9162 #ifdef SQLITE_VDBE_COVERAGE
   9163   int iSrcLine;            /* Source-code line that generated this opcode */
   9164 #endif
   9165 };
   9166 typedef struct VdbeOp VdbeOp;
   9167 
   9168 
   9169 /*
   9170 ** A sub-routine used to implement a trigger program.
   9171 */
   9172 struct SubProgram {
   9173   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
   9174   int nOp;                      /* Elements in aOp[] */
   9175   int nMem;                     /* Number of memory cells required */
   9176   int nCsr;                     /* Number of cursors required */
   9177   int nOnce;                    /* Number of OP_Once instructions */
   9178   void *token;                  /* id that may be used to recursive triggers */
   9179   SubProgram *pNext;            /* Next sub-program already visited */
   9180 };
   9181 
   9182 /*
   9183 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
   9184 ** it takes up less space.
   9185 */
   9186 struct VdbeOpList {
   9187   u8 opcode;          /* What operation to perform */
   9188   signed char p1;     /* First operand */
   9189   signed char p2;     /* Second parameter (often the jump destination) */
   9190   signed char p3;     /* Third parameter */
   9191 };
   9192 typedef struct VdbeOpList VdbeOpList;
   9193 
   9194 /*
   9195 ** Allowed values of VdbeOp.p4type
   9196 */
   9197 #define P4_NOTUSED    0   /* The P4 parameter is not used */
   9198 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
   9199 #define P4_STATIC   (-2)  /* Pointer to a static string */
   9200 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
   9201 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
   9202 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
   9203 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
   9204 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
   9205 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
   9206 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
   9207 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
   9208 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
   9209 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
   9210 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
   9211 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
   9212 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
   9213 
   9214 /* Error message codes for OP_Halt */
   9215 #define P5_ConstraintNotNull 1
   9216 #define P5_ConstraintUnique  2
   9217 #define P5_ConstraintCheck   3
   9218 #define P5_ConstraintFK      4
   9219 
   9220 /*
   9221 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
   9222 ** number of columns of data returned by the statement.
   9223 */
   9224 #define COLNAME_NAME     0
   9225 #define COLNAME_DECLTYPE 1
   9226 #define COLNAME_DATABASE 2
   9227 #define COLNAME_TABLE    3
   9228 #define COLNAME_COLUMN   4
   9229 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   9230 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
   9231 #else
   9232 # ifdef SQLITE_OMIT_DECLTYPE
   9233 #   define COLNAME_N      1      /* Store only the name */
   9234 # else
   9235 #   define COLNAME_N      2      /* Store the name and decltype */
   9236 # endif
   9237 #endif
   9238 
   9239 /*
   9240 ** The following macro converts a relative address in the p2 field
   9241 ** of a VdbeOp structure into a negative number so that
   9242 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
   9243 ** the macro again restores the address.
   9244 */
   9245 #define ADDR(X)  (-1-(X))
   9246 
   9247 /*
   9248 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
   9249 ** header file that defines a number for each opcode used by the VDBE.
   9250 */
   9251 /************** Include opcodes.h in the middle of vdbe.h ********************/
   9252 /************** Begin file opcodes.h *****************************************/
   9253 /* Automatically generated.  Do not edit */
   9254 /* See the mkopcodeh.awk script for details */
   9255 #define OP_Function        1 /* synopsis: r[P3]=func(r[P2@P5])             */
   9256 #define OP_Savepoint       2
   9257 #define OP_AutoCommit      3
   9258 #define OP_Transaction     4
   9259 #define OP_SorterNext      5
   9260 #define OP_PrevIfOpen      6
   9261 #define OP_NextIfOpen      7
   9262 #define OP_Prev            8
   9263 #define OP_Next            9
   9264 #define OP_AggStep        10 /* synopsis: accum=r[P3] step(r[P2@P5])       */
   9265 #define OP_Checkpoint     11
   9266 #define OP_JournalMode    12
   9267 #define OP_Vacuum         13
   9268 #define OP_VFilter        14 /* synopsis: iplan=r[P3] zplan='P4'           */
   9269 #define OP_VUpdate        15 /* synopsis: data=r[P3@P2]                    */
   9270 #define OP_Goto           16
   9271 #define OP_Gosub          17
   9272 #define OP_Return         18
   9273 #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
   9274 #define OP_InitCoroutine  20
   9275 #define OP_EndCoroutine   21
   9276 #define OP_Yield          22
   9277 #define OP_HaltIfNull     23 /* synopsis: if r[P3]=null halt               */
   9278 #define OP_Halt           24
   9279 #define OP_Integer        25 /* synopsis: r[P2]=P1                         */
   9280 #define OP_Int64          26 /* synopsis: r[P2]=P4                         */
   9281 #define OP_String         27 /* synopsis: r[P2]='P4' (len=P1)              */
   9282 #define OP_Null           28 /* synopsis: r[P2..P3]=NULL                   */
   9283 #define OP_SoftNull       29 /* synopsis: r[P1]=NULL                       */
   9284 #define OP_Blob           30 /* synopsis: r[P2]=P4 (len=P1)                */
   9285 #define OP_Variable       31 /* synopsis: r[P2]=parameter(P1,P4)           */
   9286 #define OP_Move           32 /* synopsis: r[P2@P3]=r[P1@P3]                */
   9287 #define OP_Copy           33 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
   9288 #define OP_SCopy          34 /* synopsis: r[P2]=r[P1]                      */
   9289 #define OP_ResultRow      35 /* synopsis: output=r[P1@P2]                  */
   9290 #define OP_CollSeq        36
   9291 #define OP_AddImm         37 /* synopsis: r[P1]=r[P1]+P2                   */
   9292 #define OP_MustBeInt      38
   9293 #define OP_RealAffinity   39
   9294 #define OP_Permutation    40
   9295 #define OP_Compare        41 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
   9296 #define OP_Jump           42
   9297 #define OP_Once           43
   9298 #define OP_If             44
   9299 #define OP_IfNot          45
   9300 #define OP_Column         46 /* synopsis: r[P3]=PX                         */
   9301 #define OP_Affinity       47 /* synopsis: affinity(r[P1@P2])               */
   9302 #define OP_MakeRecord     48 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
   9303 #define OP_Count          49 /* synopsis: r[P2]=count()                    */
   9304 #define OP_ReadCookie     50
   9305 #define OP_SetCookie      51
   9306 #define OP_ReopenIdx      52 /* synopsis: root=P2 iDb=P3                   */
   9307 #define OP_OpenRead       53 /* synopsis: root=P2 iDb=P3                   */
   9308 #define OP_OpenWrite      54 /* synopsis: root=P2 iDb=P3                   */
   9309 #define OP_OpenAutoindex  55 /* synopsis: nColumn=P2                       */
   9310 #define OP_OpenEphemeral  56 /* synopsis: nColumn=P2                       */
   9311 #define OP_SorterOpen     57
   9312 #define OP_OpenPseudo     58 /* synopsis: P3 columns in r[P2]              */
   9313 #define OP_Close          59
   9314 #define OP_SeekLT         60 /* synopsis: key=r[P3@P4]                     */
   9315 #define OP_SeekLE         61 /* synopsis: key=r[P3@P4]                     */
   9316 #define OP_SeekGE         62 /* synopsis: key=r[P3@P4]                     */
   9317 #define OP_SeekGT         63 /* synopsis: key=r[P3@P4]                     */
   9318 #define OP_Seek           64 /* synopsis: intkey=r[P2]                     */
   9319 #define OP_NoConflict     65 /* synopsis: key=r[P3@P4]                     */
   9320 #define OP_NotFound       66 /* synopsis: key=r[P3@P4]                     */
   9321 #define OP_Found          67 /* synopsis: key=r[P3@P4]                     */
   9322 #define OP_NotExists      68 /* synopsis: intkey=r[P3]                     */
   9323 #define OP_Sequence       69 /* synopsis: r[P2]=cursor[P1].ctr++           */
   9324 #define OP_NewRowid       70 /* synopsis: r[P2]=rowid                      */
   9325 #define OP_Or             71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
   9326 #define OP_And            72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
   9327 #define OP_Insert         73 /* synopsis: intkey=r[P3] data=r[P2]          */
   9328 #define OP_InsertInt      74 /* synopsis: intkey=P3 data=r[P2]             */
   9329 #define OP_Delete         75
   9330 #define OP_IsNull         76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
   9331 #define OP_NotNull        77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
   9332 #define OP_Ne             78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
   9333 #define OP_Eq             79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
   9334 #define OP_Gt             80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
   9335 #define OP_Le             81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
   9336 #define OP_Lt             82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
   9337 #define OP_Ge             83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
   9338 #define OP_ResetCount     84
   9339 #define OP_BitAnd         85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
   9340 #define OP_BitOr          86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
   9341 #define OP_ShiftLeft      87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
   9342 #define OP_ShiftRight     88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
   9343 #define OP_Add            89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
   9344 #define OP_Subtract       90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
   9345 #define OP_Multiply       91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
   9346 #define OP_Divide         92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
   9347 #define OP_Remainder      93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
   9348 #define OP_Concat         94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
   9349 #define OP_SorterCompare  95 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
   9350 #define OP_BitNot         96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
   9351 #define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
   9352 #define OP_SorterData     98 /* synopsis: r[P2]=data                       */
   9353 #define OP_RowKey         99 /* synopsis: r[P2]=key                        */
   9354 #define OP_RowData       100 /* synopsis: r[P2]=data                       */
   9355 #define OP_Rowid         101 /* synopsis: r[P2]=rowid                      */
   9356 #define OP_NullRow       102
   9357 #define OP_Last          103
   9358 #define OP_SorterSort    104
   9359 #define OP_Sort          105
   9360 #define OP_Rewind        106
   9361 #define OP_SorterInsert  107
   9362 #define OP_IdxInsert     108 /* synopsis: key=r[P2]                        */
   9363 #define OP_IdxDelete     109 /* synopsis: key=r[P2@P3]                     */
   9364 #define OP_IdxRowid      110 /* synopsis: r[P2]=rowid                      */
   9365 #define OP_IdxLE         111 /* synopsis: key=r[P3@P4]                     */
   9366 #define OP_IdxGT         112 /* synopsis: key=r[P3@P4]                     */
   9367 #define OP_IdxLT         113 /* synopsis: key=r[P3@P4]                     */
   9368 #define OP_IdxGE         114 /* synopsis: key=r[P3@P4]                     */
   9369 #define OP_Destroy       115
   9370 #define OP_Clear         116
   9371 #define OP_ResetSorter   117
   9372 #define OP_CreateIndex   118 /* synopsis: r[P2]=root iDb=P1                */
   9373 #define OP_CreateTable   119 /* synopsis: r[P2]=root iDb=P1                */
   9374 #define OP_ParseSchema   120
   9375 #define OP_LoadAnalysis  121
   9376 #define OP_DropTable     122
   9377 #define OP_DropIndex     123
   9378 #define OP_DropTrigger   124
   9379 #define OP_IntegrityCk   125
   9380 #define OP_RowSetAdd     126 /* synopsis: rowset(P1)=r[P2]                 */
   9381 #define OP_RowSetRead    127 /* synopsis: r[P3]=rowset(P1)                 */
   9382 #define OP_RowSetTest    128 /* synopsis: if r[P3] in rowset(P1) goto P2   */
   9383 #define OP_Program       129
   9384 #define OP_Param         130
   9385 #define OP_FkCounter     131 /* synopsis: fkctr[P1]+=P2                    */
   9386 #define OP_FkIfZero      132 /* synopsis: if fkctr[P1]==0 goto P2          */
   9387 #define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
   9388 #define OP_MemMax        134 /* synopsis: r[P1]=max(r[P1],r[P2])           */
   9389 #define OP_IfPos         135 /* synopsis: if r[P1]>0 goto P2               */
   9390 #define OP_IfNeg         136 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2    */
   9391 #define OP_IfZero        137 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2   */
   9392 #define OP_AggFinal      138 /* synopsis: accum=r[P1] N=P2                 */
   9393 #define OP_IncrVacuum    139
   9394 #define OP_Expire        140
   9395 #define OP_TableLock     141 /* synopsis: iDb=P1 root=P2 write=P3          */
   9396 #define OP_VBegin        142
   9397 #define OP_ToText        143 /* same as TK_TO_TEXT                         */
   9398 #define OP_ToBlob        144 /* same as TK_TO_BLOB                         */
   9399 #define OP_ToNumeric     145 /* same as TK_TO_NUMERIC                      */
   9400 #define OP_ToInt         146 /* same as TK_TO_INT                          */
   9401 #define OP_ToReal        147 /* same as TK_TO_REAL                         */
   9402 #define OP_VCreate       148
   9403 #define OP_VDestroy      149
   9404 #define OP_VOpen         150
   9405 #define OP_VColumn       151 /* synopsis: r[P3]=vcolumn(P2)                */
   9406 #define OP_VNext         152
   9407 #define OP_VRename       153
   9408 #define OP_Pagecount     154
   9409 #define OP_MaxPgcnt      155
   9410 #define OP_Init          156 /* synopsis: Start at P2                      */
   9411 #define OP_Noop          157
   9412 #define OP_Explain       158
   9413 
   9414 
   9415 /* Properties such as "out2" or "jump" that are specified in
   9416 ** comments following the "case" for each opcode in the vdbe.c
   9417 ** are encoded into bitvectors as follows:
   9418 */
   9419 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
   9420 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
   9421 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
   9422 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
   9423 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
   9424 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
   9425 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
   9426 #define OPFLG_INITIALIZER {\
   9427 /*   0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
   9428 /*   8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
   9429 /*  16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
   9430 /*  24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
   9431 /*  32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
   9432 /*  40 */ 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00,\
   9433 /*  48 */ 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00, 0x00,\
   9434 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
   9435 /*  64 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x4c,\
   9436 /*  72 */ 0x4c, 0x00, 0x00, 0x00, 0x05, 0x05, 0x15, 0x15,\
   9437 /*  80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
   9438 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
   9439 /*  96 */ 0x24, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
   9440 /* 104 */ 0x01, 0x01, 0x01, 0x08, 0x08, 0x00, 0x02, 0x01,\
   9441 /* 112 */ 0x01, 0x01, 0x01, 0x02, 0x00, 0x00, 0x02, 0x02,\
   9442 /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45,\
   9443 /* 128 */ 0x15, 0x01, 0x02, 0x00, 0x01, 0x02, 0x08, 0x05,\
   9444 /* 136 */ 0x05, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04,\
   9445 /* 144 */ 0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00,\
   9446 /* 152 */ 0x01, 0x00, 0x02, 0x02, 0x01, 0x00, 0x00,}
   9447 
   9448 /************** End of opcodes.h *********************************************/
   9449 /************** Continuing where we left off in vdbe.h ***********************/
   9450 
   9451 /*
   9452 ** Prototypes for the VDBE interface.  See comments on the implementation
   9453 ** for a description of what each of these routines does.
   9454 */
   9455 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
   9456 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
   9457 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
   9458 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
   9459 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
   9460 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
   9461 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
   9462 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
   9463 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
   9464 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
   9465 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
   9466 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
   9467 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
   9468 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
   9469 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
   9470 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
   9471 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
   9472 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
   9473 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
   9474 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
   9475 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
   9476 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
   9477 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
   9478 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
   9479 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
   9480 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
   9481 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
   9482 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
   9483 #ifdef SQLITE_DEBUG
   9484 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
   9485 #endif
   9486 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
   9487 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
   9488 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
   9489 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
   9490 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
   9491 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
   9492 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
   9493 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
   9494 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
   9495 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
   9496 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
   9497 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
   9498 #ifndef SQLITE_OMIT_TRACE
   9499 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
   9500 #endif
   9501 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
   9502 
   9503 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
   9504 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*,int);
   9505 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
   9506 
   9507 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*,int);
   9508 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
   9509 
   9510 #ifndef SQLITE_OMIT_TRIGGER
   9511 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
   9512 #endif
   9513 
   9514 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
   9515 ** each VDBE opcode.
   9516 **
   9517 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
   9518 ** comments in VDBE programs that show key decision points in the code
   9519 ** generator.
   9520 */
   9521 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   9522 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
   9523 # define VdbeComment(X)  sqlite3VdbeComment X
   9524 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
   9525 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
   9526 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
   9527 #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
   9528 # else
   9529 #   define VdbeModuleComment(X)
   9530 # endif
   9531 #else
   9532 # define VdbeComment(X)
   9533 # define VdbeNoopComment(X)
   9534 # define VdbeModuleComment(X)
   9535 #endif
   9536 
   9537 /*
   9538 ** The VdbeCoverage macros are used to set a coverage testing point
   9539 ** for VDBE branch instructions.  The coverage testing points are line
   9540 ** numbers in the sqlite3.c source file.  VDBE branch coverage testing
   9541 ** only works with an amalagmation build.  That's ok since a VDBE branch
   9542 ** coverage build designed for testing the test suite only.  No application
   9543 ** should ever ship with VDBE branch coverage measuring turned on.
   9544 **
   9545 **    VdbeCoverage(v)                  // Mark the previously coded instruction
   9546 **                                     // as a branch
   9547 **
   9548 **    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
   9549 **
   9550 **    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
   9551 **
   9552 **    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
   9553 **
   9554 ** Every VDBE branch operation must be tagged with one of the macros above.
   9555 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
   9556 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
   9557 ** routine in vdbe.c, alerting the developer to the missed tag.
   9558 */
   9559 #ifdef SQLITE_VDBE_COVERAGE
   9560 SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
   9561 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
   9562 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
   9563 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
   9564 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
   9565 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
   9566 #else
   9567 # define VdbeCoverage(v)
   9568 # define VdbeCoverageIf(v,x)
   9569 # define VdbeCoverageAlwaysTaken(v)
   9570 # define VdbeCoverageNeverTaken(v)
   9571 # define VDBE_OFFSET_LINENO(x) 0
   9572 #endif
   9573 
   9574 #endif
   9575 
   9576 /************** End of vdbe.h ************************************************/
   9577 /************** Continuing where we left off in sqliteInt.h ******************/
   9578 /************** Include pager.h in the middle of sqliteInt.h *****************/
   9579 /************** Begin file pager.h *******************************************/
   9580 /*
   9581 ** 2001 September 15
   9582 **
   9583 ** The author disclaims copyright to this source code.  In place of
   9584 ** a legal notice, here is a blessing:
   9585 **
   9586 **    May you do good and not evil.
   9587 **    May you find forgiveness for yourself and forgive others.
   9588 **    May you share freely, never taking more than you give.
   9589 **
   9590 *************************************************************************
   9591 ** This header file defines the interface that the sqlite page cache
   9592 ** subsystem.  The page cache subsystem reads and writes a file a page
   9593 ** at a time and provides a journal for rollback.
   9594 */
   9595 
   9596 #ifndef _PAGER_H_
   9597 #define _PAGER_H_
   9598 
   9599 /*
   9600 ** Default maximum size for persistent journal files. A negative
   9601 ** value means no limit. This value may be overridden using the
   9602 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
   9603 */
   9604 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
   9605   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
   9606 #endif
   9607 
   9608 /*
   9609 ** The type used to represent a page number.  The first page in a file
   9610 ** is called page 1.  0 is used to represent "not a page".
   9611 */
   9612 typedef u32 Pgno;
   9613 
   9614 /*
   9615 ** Each open file is managed by a separate instance of the "Pager" structure.
   9616 */
   9617 typedef struct Pager Pager;
   9618 
   9619 /*
   9620 ** Handle type for pages.
   9621 */
   9622 typedef struct PgHdr DbPage;
   9623 
   9624 /*
   9625 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
   9626 ** reserved for working around a windows/posix incompatibility). It is
   9627 ** used in the journal to signify that the remainder of the journal file
   9628 ** is devoted to storing a master journal name - there are no more pages to
   9629 ** roll back. See comments for function writeMasterJournal() in pager.c
   9630 ** for details.
   9631 */
   9632 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
   9633 
   9634 /*
   9635 ** Allowed values for the flags parameter to sqlite3PagerOpen().
   9636 **
   9637 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
   9638 */
   9639 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
   9640 #define PAGER_MEMORY        0x0002    /* In-memory database */
   9641 
   9642 /*
   9643 ** Valid values for the second argument to sqlite3PagerLockingMode().
   9644 */
   9645 #define PAGER_LOCKINGMODE_QUERY      -1
   9646 #define PAGER_LOCKINGMODE_NORMAL      0
   9647 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
   9648 
   9649 /*
   9650 ** Numeric constants that encode the journalmode.
   9651 */
   9652 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
   9653 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
   9654 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
   9655 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
   9656 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
   9657 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
   9658 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
   9659 
   9660 /*
   9661 ** Flags that make up the mask passed to sqlite3PagerAcquire().
   9662 */
   9663 #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
   9664 #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
   9665 
   9666 /*
   9667 ** Flags for sqlite3PagerSetFlags()
   9668 */
   9669 #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
   9670 #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
   9671 #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
   9672 #define PAGER_SYNCHRONOUS_MASK      0x03  /* Mask for three values above */
   9673 #define PAGER_FULLFSYNC             0x04  /* PRAGMA fullfsync=ON */
   9674 #define PAGER_CKPT_FULLFSYNC        0x08  /* PRAGMA checkpoint_fullfsync=ON */
   9675 #define PAGER_CACHESPILL            0x10  /* PRAGMA cache_spill=ON */
   9676 #define PAGER_FLAGS_MASK            0x1c  /* All above except SYNCHRONOUS */
   9677 
   9678 /*
   9679 ** The remainder of this file contains the declarations of the functions
   9680 ** that make up the Pager sub-system API. See source code comments for
   9681 ** a detailed description of each routine.
   9682 */
   9683 
   9684 /* Open and close a Pager connection. */
   9685 SQLITE_PRIVATE int sqlite3PagerOpen(
   9686   sqlite3_vfs*,
   9687   Pager **ppPager,
   9688   const char*,
   9689   int,
   9690   int,
   9691   int,
   9692   void(*)(DbPage*)
   9693 );
   9694 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
   9695 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
   9696 
   9697 /* Functions used to configure a Pager object. */
   9698 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
   9699 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
   9700 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
   9701 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
   9702 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
   9703 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
   9704 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
   9705 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
   9706 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
   9707 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
   9708 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
   9709 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
   9710 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
   9711 
   9712 /* Functions used to obtain and release page references. */
   9713 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
   9714 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
   9715 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
   9716 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
   9717 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
   9718 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
   9719 
   9720 /* Operations on page references. */
   9721 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
   9722 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
   9723 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
   9724 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
   9725 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
   9726 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
   9727 
   9728 /* Functions used to manage pager transactions and savepoints. */
   9729 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
   9730 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
   9731 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
   9732 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
   9733 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
   9734 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
   9735 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
   9736 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
   9737 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
   9738 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
   9739 
   9740 #ifndef SQLITE_OMIT_WAL
   9741 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
   9742 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
   9743 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
   9744 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
   9745 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
   9746 #endif
   9747 
   9748 #ifdef SQLITE_ENABLE_ZIPVFS
   9749 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
   9750 #endif
   9751 
   9752 /* Functions used to query pager state and configuration. */
   9753 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
   9754 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
   9755 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
   9756 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
   9757 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
   9758 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
   9759 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
   9760 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
   9761 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
   9762 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
   9763 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
   9764 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
   9765 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
   9766 
   9767 /* Functions used to truncate the database file. */
   9768 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
   9769 
   9770 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
   9771 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
   9772 #endif
   9773 
   9774 /* Functions to support testing and debugging. */
   9775 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   9776 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
   9777 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
   9778 #endif
   9779 #ifdef SQLITE_TEST
   9780 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
   9781 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
   9782   void disable_simulated_io_errors(void);
   9783   void enable_simulated_io_errors(void);
   9784 #else
   9785 # define disable_simulated_io_errors()
   9786 # define enable_simulated_io_errors()
   9787 #endif
   9788 
   9789 #endif /* _PAGER_H_ */
   9790 
   9791 /************** End of pager.h ***********************************************/
   9792 /************** Continuing where we left off in sqliteInt.h ******************/
   9793 /************** Include pcache.h in the middle of sqliteInt.h ****************/
   9794 /************** Begin file pcache.h ******************************************/
   9795 /*
   9796 ** 2008 August 05
   9797 **
   9798 ** The author disclaims copyright to this source code.  In place of
   9799 ** a legal notice, here is a blessing:
   9800 **
   9801 **    May you do good and not evil.
   9802 **    May you find forgiveness for yourself and forgive others.
   9803 **    May you share freely, never taking more than you give.
   9804 **
   9805 *************************************************************************
   9806 ** This header file defines the interface that the sqlite page cache
   9807 ** subsystem.
   9808 */
   9809 
   9810 #ifndef _PCACHE_H_
   9811 
   9812 typedef struct PgHdr PgHdr;
   9813 typedef struct PCache PCache;
   9814 
   9815 /*
   9816 ** Every page in the cache is controlled by an instance of the following
   9817 ** structure.
   9818 */
   9819 struct PgHdr {
   9820   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
   9821   void *pData;                   /* Page data */
   9822   void *pExtra;                  /* Extra content */
   9823   PgHdr *pDirty;                 /* Transient list of dirty pages */
   9824   Pager *pPager;                 /* The pager this page is part of */
   9825   Pgno pgno;                     /* Page number for this page */
   9826 #ifdef SQLITE_CHECK_PAGES
   9827   u32 pageHash;                  /* Hash of page content */
   9828 #endif
   9829   u16 flags;                     /* PGHDR flags defined below */
   9830 
   9831   /**********************************************************************
   9832   ** Elements above are public.  All that follows is private to pcache.c
   9833   ** and should not be accessed by other modules.
   9834   */
   9835   i16 nRef;                      /* Number of users of this page */
   9836   PCache *pCache;                /* Cache that owns this page */
   9837 
   9838   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
   9839   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
   9840 };
   9841 
   9842 /* Bit values for PgHdr.flags */
   9843 #define PGHDR_DIRTY             0x002  /* Page has changed */
   9844 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
   9845                                        ** writing this page to the database */
   9846 #define PGHDR_NEED_READ         0x008  /* Content is unread */
   9847 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
   9848 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
   9849 
   9850 #define PGHDR_MMAP              0x040  /* This is an mmap page object */
   9851 
   9852 /* Initialize and shutdown the page cache subsystem */
   9853 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
   9854 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
   9855 
   9856 /* Page cache buffer management:
   9857 ** These routines implement SQLITE_CONFIG_PAGECACHE.
   9858 */
   9859 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
   9860 
   9861 /* Create a new pager cache.
   9862 ** Under memory stress, invoke xStress to try to make pages clean.
   9863 ** Only clean and unpinned pages can be reclaimed.
   9864 */
   9865 SQLITE_PRIVATE void sqlite3PcacheOpen(
   9866   int szPage,                    /* Size of every page */
   9867   int szExtra,                   /* Extra space associated with each page */
   9868   int bPurgeable,                /* True if pages are on backing store */
   9869   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
   9870   void *pStress,                 /* Argument to xStress */
   9871   PCache *pToInit                /* Preallocated space for the PCache */
   9872 );
   9873 
   9874 /* Modify the page-size after the cache has been created. */
   9875 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
   9876 
   9877 /* Return the size in bytes of a PCache object.  Used to preallocate
   9878 ** storage space.
   9879 */
   9880 SQLITE_PRIVATE int sqlite3PcacheSize(void);
   9881 
   9882 /* One release per successful fetch.  Page is pinned until released.
   9883 ** Reference counted.
   9884 */
   9885 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
   9886 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
   9887 
   9888 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
   9889 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
   9890 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
   9891 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
   9892 
   9893 /* Change a page number.  Used by incr-vacuum. */
   9894 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
   9895 
   9896 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
   9897 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
   9898 
   9899 /* Get a list of all dirty pages in the cache, sorted by page number */
   9900 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
   9901 
   9902 /* Reset and close the cache object */
   9903 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
   9904 
   9905 /* Clear flags from pages of the page cache */
   9906 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
   9907 
   9908 /* Discard the contents of the cache */
   9909 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
   9910 
   9911 /* Return the total number of outstanding page references */
   9912 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
   9913 
   9914 /* Increment the reference count of an existing page */
   9915 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
   9916 
   9917 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
   9918 
   9919 /* Return the total number of pages stored in the cache */
   9920 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
   9921 
   9922 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   9923 /* Iterate through all dirty pages currently stored in the cache. This
   9924 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
   9925 ** library is built.
   9926 */
   9927 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
   9928 #endif
   9929 
   9930 /* Set and get the suggested cache-size for the specified pager-cache.
   9931 **
   9932 ** If no global maximum is configured, then the system attempts to limit
   9933 ** the total number of pages cached by purgeable pager-caches to the sum
   9934 ** of the suggested cache-sizes.
   9935 */
   9936 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
   9937 #ifdef SQLITE_TEST
   9938 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
   9939 #endif
   9940 
   9941 /* Free up as much memory as possible from the page cache */
   9942 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
   9943 
   9944 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   9945 /* Try to return memory used by the pcache module to the main memory heap */
   9946 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
   9947 #endif
   9948 
   9949 #ifdef SQLITE_TEST
   9950 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
   9951 #endif
   9952 
   9953 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
   9954 
   9955 #endif /* _PCACHE_H_ */
   9956 
   9957 /************** End of pcache.h **********************************************/
   9958 /************** Continuing where we left off in sqliteInt.h ******************/
   9959 
   9960 /************** Include os.h in the middle of sqliteInt.h ********************/
   9961 /************** Begin file os.h **********************************************/
   9962 /*
   9963 ** 2001 September 16
   9964 **
   9965 ** The author disclaims copyright to this source code.  In place of
   9966 ** a legal notice, here is a blessing:
   9967 **
   9968 **    May you do good and not evil.
   9969 **    May you find forgiveness for yourself and forgive others.
   9970 **    May you share freely, never taking more than you give.
   9971 **
   9972 ******************************************************************************
   9973 **
   9974 ** This header file (together with is companion C source-code file
   9975 ** "os.c") attempt to abstract the underlying operating system so that
   9976 ** the SQLite library will work on both POSIX and windows systems.
   9977 **
   9978 ** This header file is #include-ed by sqliteInt.h and thus ends up
   9979 ** being included by every source file.
   9980 */
   9981 #ifndef _SQLITE_OS_H_
   9982 #define _SQLITE_OS_H_
   9983 
   9984 /*
   9985 ** Attempt to automatically detect the operating system and setup the
   9986 ** necessary pre-processor macros for it.
   9987 */
   9988 /************** Include os_setup.h in the middle of os.h *********************/
   9989 /************** Begin file os_setup.h ****************************************/
   9990 /*
   9991 ** 2013 November 25
   9992 **
   9993 ** The author disclaims copyright to this source code.  In place of
   9994 ** a legal notice, here is a blessing:
   9995 **
   9996 **    May you do good and not evil.
   9997 **    May you find forgiveness for yourself and forgive others.
   9998 **    May you share freely, never taking more than you give.
   9999 **
   10000 ******************************************************************************
   10001 **
   10002 ** This file contains pre-processor directives related to operating system
   10003 ** detection and/or setup.
   10004 */
   10005 #ifndef _OS_SETUP_H_
   10006 #define _OS_SETUP_H_
   10007 
   10008 /*
   10009 ** Figure out if we are dealing with Unix, Windows, or some other operating
   10010 ** system.
   10011 **
   10012 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
   10013 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
   10014 ** the three will be 1.  The other two will be 0.
   10015 */
   10016 #if defined(SQLITE_OS_OTHER)
   10017 #  if SQLITE_OS_OTHER==1
   10018 #    undef SQLITE_OS_UNIX
   10019 #    define SQLITE_OS_UNIX 0
   10020 #    undef SQLITE_OS_WIN
   10021 #    define SQLITE_OS_WIN 0
   10022 #  else
   10023 #    undef SQLITE_OS_OTHER
   10024 #  endif
   10025 #endif
   10026 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
   10027 #  define SQLITE_OS_OTHER 0
   10028 #  ifndef SQLITE_OS_WIN
   10029 #    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
   10030         defined(__MINGW32__) || defined(__BORLANDC__)
   10031 #      define SQLITE_OS_WIN 1
   10032 #      define SQLITE_OS_UNIX 0
   10033 #    else
   10034 #      define SQLITE_OS_WIN 0
   10035 #      define SQLITE_OS_UNIX 1
   10036 #    endif
   10037 #  else
   10038 #    define SQLITE_OS_UNIX 0
   10039 #  endif
   10040 #else
   10041 #  ifndef SQLITE_OS_WIN
   10042 #    define SQLITE_OS_WIN 0
   10043 #  endif
   10044 #endif
   10045 
   10046 #endif /* _OS_SETUP_H_ */
   10047 
   10048 /************** End of os_setup.h ********************************************/
   10049 /************** Continuing where we left off in os.h *************************/
   10050 
   10051 /* If the SET_FULLSYNC macro is not defined above, then make it
   10052 ** a no-op
   10053 */
   10054 #ifndef SET_FULLSYNC
   10055 # define SET_FULLSYNC(x,y)
   10056 #endif
   10057 
   10058 /*
   10059 ** The default size of a disk sector
   10060 */
   10061 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
   10062 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
   10063 #endif
   10064 
   10065 /*
   10066 ** Temporary files are named starting with this prefix followed by 16 random
   10067 ** alphanumeric characters, and no file extension. They are stored in the
   10068 ** OS's standard temporary file directory, and are deleted prior to exit.
   10069 ** If sqlite is being embedded in another program, you may wish to change the
   10070 ** prefix to reflect your program's name, so that if your program exits
   10071 ** prematurely, old temporary files can be easily identified. This can be done
   10072 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
   10073 **
   10074 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
   10075 ** Mcafee started using SQLite in their anti-virus product and it
   10076 ** started putting files with the "sqlite" name in the c:/temp folder.
   10077 ** This annoyed many windows users.  Those users would then do a
   10078 ** Google search for "sqlite", find the telephone numbers of the
   10079 ** developers and call to wake them up at night and complain.
   10080 ** For this reason, the default name prefix is changed to be "sqlite"
   10081 ** spelled backwards.  So the temp files are still identified, but
   10082 ** anybody smart enough to figure out the code is also likely smart
   10083 ** enough to know that calling the developer will not help get rid
   10084 ** of the file.
   10085 */
   10086 #ifndef SQLITE_TEMP_FILE_PREFIX
   10087 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
   10088 #endif
   10089 
   10090 /*
   10091 ** The following values may be passed as the second argument to
   10092 ** sqlite3OsLock(). The various locks exhibit the following semantics:
   10093 **
   10094 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
   10095 ** RESERVED:  A single process may hold a RESERVED lock on a file at
   10096 **            any time. Other processes may hold and obtain new SHARED locks.
   10097 ** PENDING:   A single process may hold a PENDING lock on a file at
   10098 **            any one time. Existing SHARED locks may persist, but no new
   10099 **            SHARED locks may be obtained by other processes.
   10100 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
   10101 **
   10102 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
   10103 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
   10104 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
   10105 ** sqlite3OsLock().
   10106 */
   10107 #define NO_LOCK         0
   10108 #define SHARED_LOCK     1
   10109 #define RESERVED_LOCK   2
   10110 #define PENDING_LOCK    3
   10111 #define EXCLUSIVE_LOCK  4
   10112 
   10113 /*
   10114 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
   10115 **
   10116 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
   10117 ** those functions are not available.  So we use only LockFile() and
   10118 ** UnlockFile().
   10119 **
   10120 ** LockFile() prevents not just writing but also reading by other processes.
   10121 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
   10122 ** byte out of a specific range of bytes. The lock byte is obtained at
   10123 ** random so two separate readers can probably access the file at the
   10124 ** same time, unless they are unlucky and choose the same lock byte.
   10125 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
   10126 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
   10127 ** a single byte of the file that is designated as the reserved lock byte.
   10128 ** A PENDING_LOCK is obtained by locking a designated byte different from
   10129 ** the RESERVED_LOCK byte.
   10130 **
   10131 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
   10132 ** which means we can use reader/writer locks.  When reader/writer locks
   10133 ** are used, the lock is placed on the same range of bytes that is used
   10134 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
   10135 ** will support two or more Win95 readers or two or more WinNT readers.
   10136 ** But a single Win95 reader will lock out all WinNT readers and a single
   10137 ** WinNT reader will lock out all other Win95 readers.
   10138 **
   10139 ** The following #defines specify the range of bytes used for locking.
   10140 ** SHARED_SIZE is the number of bytes available in the pool from which
   10141 ** a random byte is selected for a shared lock.  The pool of bytes for
   10142 ** shared locks begins at SHARED_FIRST.
   10143 **
   10144 ** The same locking strategy and
   10145 ** byte ranges are used for Unix.  This leaves open the possiblity of having
   10146 ** clients on win95, winNT, and unix all talking to the same shared file
   10147 ** and all locking correctly.  To do so would require that samba (or whatever
   10148 ** tool is being used for file sharing) implements locks correctly between
   10149 ** windows and unix.  I'm guessing that isn't likely to happen, but by
   10150 ** using the same locking range we are at least open to the possibility.
   10151 **
   10152 ** Locking in windows is manditory.  For this reason, we cannot store
   10153 ** actual data in the bytes used for locking.  The pager never allocates
   10154 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
   10155 ** that all locks will fit on a single page even at the minimum page size.
   10156 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
   10157 ** is set high so that we don't have to allocate an unused page except
   10158 ** for very large databases.  But one should test the page skipping logic
   10159 ** by setting PENDING_BYTE low and running the entire regression suite.
   10160 **
   10161 ** Changing the value of PENDING_BYTE results in a subtly incompatible
   10162 ** file format.  Depending on how it is changed, you might not notice
   10163 ** the incompatibility right away, even running a full regression test.
   10164 ** The default location of PENDING_BYTE is the first byte past the
   10165 ** 1GB boundary.
   10166 **
   10167 */
   10168 #ifdef SQLITE_OMIT_WSD
   10169 # define PENDING_BYTE     (0x40000000)
   10170 #else
   10171 # define PENDING_BYTE      sqlite3PendingByte
   10172 #endif
   10173 #define RESERVED_BYTE     (PENDING_BYTE+1)
   10174 #define SHARED_FIRST      (PENDING_BYTE+2)
   10175 #define SHARED_SIZE       510
   10176 
   10177 /*
   10178 ** Wrapper around OS specific sqlite3_os_init() function.
   10179 */
   10180 SQLITE_PRIVATE int sqlite3OsInit(void);
   10181 
   10182 /*
   10183 ** Functions for accessing sqlite3_file methods
   10184 */
   10185 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
   10186 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
   10187 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
   10188 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
   10189 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
   10190 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
   10191 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
   10192 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
   10193 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
   10194 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
   10195 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
   10196 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
   10197 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
   10198 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
   10199 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
   10200 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
   10201 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
   10202 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
   10203 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
   10204 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
   10205 
   10206 
   10207 /*
   10208 ** Functions for accessing sqlite3_vfs methods
   10209 */
   10210 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
   10211 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
   10212 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
   10213 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
   10214 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   10215 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
   10216 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
   10217 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
   10218 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
   10219 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   10220 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
   10221 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
   10222 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
   10223 
   10224 /*
   10225 ** Convenience functions for opening and closing files using
   10226 ** sqlite3_malloc() to obtain space for the file-handle structure.
   10227 */
   10228 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
   10229 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
   10230 
   10231 #endif /* _SQLITE_OS_H_ */
   10232 
   10233 /************** End of os.h **************************************************/
   10234 /************** Continuing where we left off in sqliteInt.h ******************/
   10235 /************** Include mutex.h in the middle of sqliteInt.h *****************/
   10236 /************** Begin file mutex.h *******************************************/
   10237 /*
   10238 ** 2007 August 28
   10239 **
   10240 ** The author disclaims copyright to this source code.  In place of
   10241 ** a legal notice, here is a blessing:
   10242 **
   10243 **    May you do good and not evil.
   10244 **    May you find forgiveness for yourself and forgive others.
   10245 **    May you share freely, never taking more than you give.
   10246 **
   10247 *************************************************************************
   10248 **
   10249 ** This file contains the common header for all mutex implementations.
   10250 ** The sqliteInt.h header #includes this file so that it is available
   10251 ** to all source files.  We break it out in an effort to keep the code
   10252 ** better organized.
   10253 **
   10254 ** NOTE:  source files should *not* #include this header file directly.
   10255 ** Source files should #include the sqliteInt.h file and let that file
   10256 ** include this one indirectly.
   10257 */
   10258 
   10259 
   10260 /*
   10261 ** Figure out what version of the code to use.  The choices are
   10262 **
   10263 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
   10264 **                             mutexes implemention cannot be overridden
   10265 **                             at start-time.
   10266 **
   10267 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
   10268 **                             mutual exclusion is provided.  But this
   10269 **                             implementation can be overridden at
   10270 **                             start-time.
   10271 **
   10272 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
   10273 **
   10274 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
   10275 */
   10276 #if !SQLITE_THREADSAFE
   10277 # define SQLITE_MUTEX_OMIT
   10278 #endif
   10279 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
   10280 #  if SQLITE_OS_UNIX
   10281 #    define SQLITE_MUTEX_PTHREADS
   10282 #  elif SQLITE_OS_WIN
   10283 #    define SQLITE_MUTEX_W32
   10284 #  else
   10285 #    define SQLITE_MUTEX_NOOP
   10286 #  endif
   10287 #endif
   10288 
   10289 #ifdef SQLITE_MUTEX_OMIT
   10290 /*
   10291 ** If this is a no-op implementation, implement everything as macros.
   10292 */
   10293 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
   10294 #define sqlite3_mutex_free(X)
   10295 #define sqlite3_mutex_enter(X)
   10296 #define sqlite3_mutex_try(X)      SQLITE_OK
   10297 #define sqlite3_mutex_leave(X)
   10298 #define sqlite3_mutex_held(X)     ((void)(X),1)
   10299 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
   10300 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
   10301 #define sqlite3MutexInit()        SQLITE_OK
   10302 #define sqlite3MutexEnd()
   10303 #define MUTEX_LOGIC(X)
   10304 #else
   10305 #define MUTEX_LOGIC(X)            X
   10306 #endif /* defined(SQLITE_MUTEX_OMIT) */
   10307 
   10308 /************** End of mutex.h ***********************************************/
   10309 /************** Continuing where we left off in sqliteInt.h ******************/
   10310 
   10311 
   10312 /*
   10313 ** Each database file to be accessed by the system is an instance
   10314 ** of the following structure.  There are normally two of these structures
   10315 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
   10316 ** aDb[1] is the database file used to hold temporary tables.  Additional
   10317 ** databases may be attached.
   10318 */
   10319 struct Db {
   10320   char *zName;         /* Name of this database */
   10321   Btree *pBt;          /* The B*Tree structure for this database file */
   10322   u8 safety_level;     /* How aggressive at syncing data to disk */
   10323   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
   10324 };
   10325 
   10326 /*
   10327 ** An instance of the following structure stores a database schema.
   10328 **
   10329 ** Most Schema objects are associated with a Btree.  The exception is
   10330 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
   10331 ** In shared cache mode, a single Schema object can be shared by multiple
   10332 ** Btrees that refer to the same underlying BtShared object.
   10333 **
   10334 ** Schema objects are automatically deallocated when the last Btree that
   10335 ** references them is destroyed.   The TEMP Schema is manually freed by
   10336 ** sqlite3_close().
   10337 *
   10338 ** A thread must be holding a mutex on the corresponding Btree in order
   10339 ** to access Schema content.  This implies that the thread must also be
   10340 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
   10341 ** For a TEMP Schema, only the connection mutex is required.
   10342 */
   10343 struct Schema {
   10344   int schema_cookie;   /* Database schema version number for this file */
   10345   int iGeneration;     /* Generation counter.  Incremented with each change */
   10346   Hash tblHash;        /* All tables indexed by name */
   10347   Hash idxHash;        /* All (named) indices indexed by name */
   10348   Hash trigHash;       /* All triggers indexed by name */
   10349   Hash fkeyHash;       /* All foreign keys by referenced table name */
   10350   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
   10351   u8 file_format;      /* Schema format version for this file */
   10352   u8 enc;              /* Text encoding used by this database */
   10353   u16 schemaFlags;     /* Flags associated with this schema */
   10354   int cache_size;      /* Number of pages to use in the cache */
   10355 };
   10356 
   10357 /*
   10358 ** These macros can be used to test, set, or clear bits in the
   10359 ** Db.pSchema->flags field.
   10360 */
   10361 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
   10362 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
   10363 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
   10364 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
   10365 
   10366 /*
   10367 ** Allowed values for the DB.pSchema->flags field.
   10368 **
   10369 ** The DB_SchemaLoaded flag is set after the database schema has been
   10370 ** read into internal hash tables.
   10371 **
   10372 ** DB_UnresetViews means that one or more views have column names that
   10373 ** have been filled out.  If the schema changes, these column names might
   10374 ** changes and so the view will need to be reset.
   10375 */
   10376 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
   10377 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
   10378 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
   10379 
   10380 /*
   10381 ** The number of different kinds of things that can be limited
   10382 ** using the sqlite3_limit() interface.
   10383 */
   10384 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
   10385 
   10386 /*
   10387 ** Lookaside malloc is a set of fixed-size buffers that can be used
   10388 ** to satisfy small transient memory allocation requests for objects
   10389 ** associated with a particular database connection.  The use of
   10390 ** lookaside malloc provides a significant performance enhancement
   10391 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
   10392 ** SQL statements.
   10393 **
   10394 ** The Lookaside structure holds configuration information about the
   10395 ** lookaside malloc subsystem.  Each available memory allocation in
   10396 ** the lookaside subsystem is stored on a linked list of LookasideSlot
   10397 ** objects.
   10398 **
   10399 ** Lookaside allocations are only allowed for objects that are associated
   10400 ** with a particular database connection.  Hence, schema information cannot
   10401 ** be stored in lookaside because in shared cache mode the schema information
   10402 ** is shared by multiple database connections.  Therefore, while parsing
   10403 ** schema information, the Lookaside.bEnabled flag is cleared so that
   10404 ** lookaside allocations are not used to construct the schema objects.
   10405 */
   10406 struct Lookaside {
   10407   u16 sz;                 /* Size of each buffer in bytes */
   10408   u8 bEnabled;            /* False to disable new lookaside allocations */
   10409   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
   10410   int nOut;               /* Number of buffers currently checked out */
   10411   int mxOut;              /* Highwater mark for nOut */
   10412   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
   10413   LookasideSlot *pFree;   /* List of available buffers */
   10414   void *pStart;           /* First byte of available memory space */
   10415   void *pEnd;             /* First byte past end of available space */
   10416 };
   10417 struct LookasideSlot {
   10418   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
   10419 };
   10420 
   10421 /*
   10422 ** A hash table for function definitions.
   10423 **
   10424 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
   10425 ** Collisions are on the FuncDef.pHash chain.
   10426 */
   10427 struct FuncDefHash {
   10428   FuncDef *a[23];       /* Hash table for functions */
   10429 };
   10430 
   10431 /*
   10432 ** Each database connection is an instance of the following structure.
   10433 */
   10434 struct sqlite3 {
   10435   sqlite3_vfs *pVfs;            /* OS Interface */
   10436   struct Vdbe *pVdbe;           /* List of active virtual machines */
   10437   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
   10438   sqlite3_mutex *mutex;         /* Connection mutex */
   10439   Db *aDb;                      /* All backends */
   10440   int nDb;                      /* Number of backends currently in use */
   10441   int flags;                    /* Miscellaneous flags. See below */
   10442   i64 lastRowid;                /* ROWID of most recent insert (see above) */
   10443   i64 szMmap;                   /* Default mmap_size setting */
   10444   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
   10445   int errCode;                  /* Most recent error code (SQLITE_*) */
   10446   int errMask;                  /* & result codes with this before returning */
   10447   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
   10448   u8 autoCommit;                /* The auto-commit flag. */
   10449   u8 temp_store;                /* 1: file 2: memory 0: default */
   10450   u8 mallocFailed;              /* True if we have seen a malloc failure */
   10451   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
   10452   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
   10453   u8 suppressErr;               /* Do not issue error messages if true */
   10454   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
   10455   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
   10456   int nextPagesize;             /* Pagesize after VACUUM if >0 */
   10457   u32 magic;                    /* Magic number for detect library misuse */
   10458   int nChange;                  /* Value returned by sqlite3_changes() */
   10459   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
   10460   int aLimit[SQLITE_N_LIMIT];   /* Limits */
   10461   struct sqlite3InitInfo {      /* Information used during initialization */
   10462     int newTnum;                /* Rootpage of table being initialized */
   10463     u8 iDb;                     /* Which db file is being initialized */
   10464     u8 busy;                    /* TRUE if currently initializing */
   10465     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
   10466   } init;
   10467   int nVdbeActive;              /* Number of VDBEs currently running */
   10468   int nVdbeRead;                /* Number of active VDBEs that read or write */
   10469   int nVdbeWrite;               /* Number of active VDBEs that read and write */
   10470   int nVdbeExec;                /* Number of nested calls to VdbeExec() */
   10471   int nExtension;               /* Number of loaded extensions */
   10472   void **aExtension;            /* Array of shared library handles */
   10473   void (*xTrace)(void*,const char*);        /* Trace function */
   10474   void *pTraceArg;                          /* Argument to the trace function */
   10475   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
   10476   void *pProfileArg;                        /* Argument to profile function */
   10477   void *pCommitArg;                 /* Argument to xCommitCallback() */
   10478   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
   10479   void *pRollbackArg;               /* Argument to xRollbackCallback() */
   10480   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
   10481   void *pUpdateArg;
   10482   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
   10483 #ifndef SQLITE_OMIT_WAL
   10484   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
   10485   void *pWalArg;
   10486 #endif
   10487   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
   10488   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
   10489   void *pCollNeededArg;
   10490   sqlite3_value *pErr;          /* Most recent error message */
   10491   union {
   10492     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
   10493     double notUsed1;            /* Spacer */
   10494   } u1;
   10495   Lookaside lookaside;          /* Lookaside malloc configuration */
   10496 #ifndef SQLITE_OMIT_AUTHORIZATION
   10497   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   10498                                 /* Access authorization function */
   10499   void *pAuthArg;               /* 1st argument to the access auth function */
   10500 #endif
   10501 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   10502   int (*xProgress)(void *);     /* The progress callback */
   10503   void *pProgressArg;           /* Argument to the progress callback */
   10504   unsigned nProgressOps;        /* Number of opcodes for progress callback */
   10505 #endif
   10506 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10507   int nVTrans;                  /* Allocated size of aVTrans */
   10508   Hash aModule;                 /* populated by sqlite3_create_module() */
   10509   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
   10510   VTable **aVTrans;             /* Virtual tables with open transactions */
   10511   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
   10512 #endif
   10513   FuncDefHash aFunc;            /* Hash table of connection functions */
   10514   Hash aCollSeq;                /* All collating sequences */
   10515   BusyHandler busyHandler;      /* Busy callback */
   10516   Db aDbStatic[2];              /* Static space for the 2 default backends */
   10517   Savepoint *pSavepoint;        /* List of active savepoints */
   10518   int busyTimeout;              /* Busy handler timeout, in msec */
   10519   int nSavepoint;               /* Number of non-transaction savepoints */
   10520   int nStatement;               /* Number of nested statement-transactions  */
   10521   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
   10522   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
   10523   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
   10524 
   10525 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   10526   /* The following variables are all protected by the STATIC_MASTER
   10527   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
   10528   **
   10529   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
   10530   ** unlock so that it can proceed.
   10531   **
   10532   ** When X.pBlockingConnection==Y, that means that something that X tried
   10533   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
   10534   ** held by Y.
   10535   */
   10536   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
   10537   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
   10538   void *pUnlockArg;                     /* Argument to xUnlockNotify */
   10539   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
   10540   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
   10541 #endif
   10542 };
   10543 
   10544 /*
   10545 ** A macro to discover the encoding of a database.
   10546 */
   10547 #define ENC(db) ((db)->aDb[0].pSchema->enc)
   10548 
   10549 /*
   10550 ** Possible values for the sqlite3.flags.
   10551 */
   10552 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
   10553 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
   10554 #define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
   10555 #define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
   10556 #define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
   10557 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
   10558 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
   10559 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
   10560                                           /*   DELETE, or UPDATE and return */
   10561                                           /*   the count using a callback. */
   10562 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
   10563                                           /*   result set is empty */
   10564 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
   10565 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
   10566 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
   10567 #define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
   10568 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
   10569 #define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
   10570 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
   10571 #define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
   10572 #define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
   10573 #define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
   10574 #define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
   10575 #define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
   10576 #define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
   10577 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
   10578 #define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
   10579 #define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
   10580 #define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
   10581 #define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
   10582 
   10583 
   10584 /*
   10585 ** Bits of the sqlite3.dbOptFlags field that are used by the
   10586 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
   10587 ** selectively disable various optimizations.
   10588 */
   10589 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
   10590 #define SQLITE_ColumnCache    0x0002   /* Column cache */
   10591 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
   10592 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
   10593 /*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
   10594 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
   10595 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
   10596 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
   10597 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
   10598 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
   10599 #define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
   10600 #define SQLITE_Stat3          0x0800   /* Use the SQLITE_STAT3 table */
   10601 #define SQLITE_AdjustOutEst   0x1000   /* Adjust output estimates using WHERE */
   10602 #define SQLITE_AllOpts        0xffff   /* All optimizations */
   10603 
   10604 /*
   10605 ** Macros for testing whether or not optimizations are enabled or disabled.
   10606 */
   10607 #ifndef SQLITE_OMIT_BUILTIN_TEST
   10608 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
   10609 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
   10610 #else
   10611 #define OptimizationDisabled(db, mask)  0
   10612 #define OptimizationEnabled(db, mask)   1
   10613 #endif
   10614 
   10615 /*
   10616 ** Return true if it OK to factor constant expressions into the initialization
   10617 ** code. The argument is a Parse object for the code generator.
   10618 */
   10619 #define ConstFactorOk(P) ((P)->okConstFactor)
   10620 
   10621 /*
   10622 ** Possible values for the sqlite.magic field.
   10623 ** The numbers are obtained at random and have no special meaning, other
   10624 ** than being distinct from one another.
   10625 */
   10626 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
   10627 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
   10628 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
   10629 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
   10630 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
   10631 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
   10632 
   10633 /*
   10634 ** Each SQL function is defined by an instance of the following
   10635 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
   10636 ** hash table.  When multiple functions have the same name, the hash table
   10637 ** points to a linked list of these structures.
   10638 */
   10639 struct FuncDef {
   10640   i16 nArg;            /* Number of arguments.  -1 means unlimited */
   10641   u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
   10642   void *pUserData;     /* User data parameter */
   10643   FuncDef *pNext;      /* Next function with same name */
   10644   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
   10645   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
   10646   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
   10647   char *zName;         /* SQL name of the function. */
   10648   FuncDef *pHash;      /* Next with a different name but the same hash */
   10649   FuncDestructor *pDestructor;   /* Reference counted destructor function */
   10650 };
   10651 
   10652 /*
   10653 ** This structure encapsulates a user-function destructor callback (as
   10654 ** configured using create_function_v2()) and a reference counter. When
   10655 ** create_function_v2() is called to create a function with a destructor,
   10656 ** a single object of this type is allocated. FuncDestructor.nRef is set to
   10657 ** the number of FuncDef objects created (either 1 or 3, depending on whether
   10658 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
   10659 ** member of each of the new FuncDef objects is set to point to the allocated
   10660 ** FuncDestructor.
   10661 **
   10662 ** Thereafter, when one of the FuncDef objects is deleted, the reference
   10663 ** count on this object is decremented. When it reaches 0, the destructor
   10664 ** is invoked and the FuncDestructor structure freed.
   10665 */
   10666 struct FuncDestructor {
   10667   int nRef;
   10668   void (*xDestroy)(void *);
   10669   void *pUserData;
   10670 };
   10671 
   10672 /*
   10673 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
   10674 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
   10675 ** are assert() statements in the code to verify this.
   10676 */
   10677 #define SQLITE_FUNC_ENCMASK  0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
   10678 #define SQLITE_FUNC_LIKE     0x004 /* Candidate for the LIKE optimization */
   10679 #define SQLITE_FUNC_CASE     0x008 /* Case-sensitive LIKE-type function */
   10680 #define SQLITE_FUNC_EPHEM    0x010 /* Ephemeral.  Delete with VDBE */
   10681 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
   10682 #define SQLITE_FUNC_LENGTH   0x040 /* Built-in length() function */
   10683 #define SQLITE_FUNC_TYPEOF   0x080 /* Built-in typeof() function */
   10684 #define SQLITE_FUNC_COUNT    0x100 /* Built-in count(*) aggregate */
   10685 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
   10686 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
   10687 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
   10688 
   10689 /*
   10690 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
   10691 ** used to create the initializers for the FuncDef structures.
   10692 **
   10693 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
   10694 **     Used to create a scalar function definition of a function zName
   10695 **     implemented by C function xFunc that accepts nArg arguments. The
   10696 **     value passed as iArg is cast to a (void*) and made available
   10697 **     as the user-data (sqlite3_user_data()) for the function. If
   10698 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
   10699 **
   10700 **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
   10701 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
   10702 **
   10703 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
   10704 **     Used to create an aggregate function definition implemented by
   10705 **     the C functions xStep and xFinal. The first four parameters
   10706 **     are interpreted in the same way as the first 4 parameters to
   10707 **     FUNCTION().
   10708 **
   10709 **   LIKEFUNC(zName, nArg, pArg, flags)
   10710 **     Used to create a scalar function definition of a function zName
   10711 **     that accepts nArg arguments and is implemented by a call to C
   10712 **     function likeFunc. Argument pArg is cast to a (void *) and made
   10713 **     available as the function user-data (sqlite3_user_data()). The
   10714 **     FuncDef.flags variable is set to the value passed as the flags
   10715 **     parameter.
   10716 */
   10717 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
   10718   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
   10719    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
   10720 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
   10721   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
   10722    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
   10723 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
   10724   {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
   10725    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
   10726 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
   10727   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
   10728    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
   10729 #define LIKEFUNC(zName, nArg, arg, flags) \
   10730   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
   10731    (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
   10732 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
   10733   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
   10734    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
   10735 
   10736 /*
   10737 ** All current savepoints are stored in a linked list starting at
   10738 ** sqlite3.pSavepoint. The first element in the list is the most recently
   10739 ** opened savepoint. Savepoints are added to the list by the vdbe
   10740 ** OP_Savepoint instruction.
   10741 */
   10742 struct Savepoint {
   10743   char *zName;                        /* Savepoint name (nul-terminated) */
   10744   i64 nDeferredCons;                  /* Number of deferred fk violations */
   10745   i64 nDeferredImmCons;               /* Number of deferred imm fk. */
   10746   Savepoint *pNext;                   /* Parent savepoint (if any) */
   10747 };
   10748 
   10749 /*
   10750 ** The following are used as the second parameter to sqlite3Savepoint(),
   10751 ** and as the P1 argument to the OP_Savepoint instruction.
   10752 */
   10753 #define SAVEPOINT_BEGIN      0
   10754 #define SAVEPOINT_RELEASE    1
   10755 #define SAVEPOINT_ROLLBACK   2
   10756 
   10757 
   10758 /*
   10759 ** Each SQLite module (virtual table definition) is defined by an
   10760 ** instance of the following structure, stored in the sqlite3.aModule
   10761 ** hash table.
   10762 */
   10763 struct Module {
   10764   const sqlite3_module *pModule;       /* Callback pointers */
   10765   const char *zName;                   /* Name passed to create_module() */
   10766   void *pAux;                          /* pAux passed to create_module() */
   10767   void (*xDestroy)(void *);            /* Module destructor function */
   10768 };
   10769 
   10770 /*
   10771 ** information about each column of an SQL table is held in an instance
   10772 ** of this structure.
   10773 */
   10774 struct Column {
   10775   char *zName;     /* Name of this column */
   10776   Expr *pDflt;     /* Default value of this column */
   10777   char *zDflt;     /* Original text of the default value */
   10778   char *zType;     /* Data type for this column */
   10779   char *zColl;     /* Collating sequence.  If NULL, use the default */
   10780   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
   10781   char affinity;   /* One of the SQLITE_AFF_... values */
   10782   u8 szEst;        /* Estimated size of this column.  INT==1 */
   10783   u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
   10784 };
   10785 
   10786 /* Allowed values for Column.colFlags:
   10787 */
   10788 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
   10789 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
   10790 
   10791 /*
   10792 ** A "Collating Sequence" is defined by an instance of the following
   10793 ** structure. Conceptually, a collating sequence consists of a name and
   10794 ** a comparison routine that defines the order of that sequence.
   10795 **
   10796 ** If CollSeq.xCmp is NULL, it means that the
   10797 ** collating sequence is undefined.  Indices built on an undefined
   10798 ** collating sequence may not be read or written.
   10799 */
   10800 struct CollSeq {
   10801   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
   10802   u8 enc;               /* Text encoding handled by xCmp() */
   10803   void *pUser;          /* First argument to xCmp() */
   10804   int (*xCmp)(void*,int, const void*, int, const void*);
   10805   void (*xDel)(void*);  /* Destructor for pUser */
   10806 };
   10807 
   10808 /*
   10809 ** A sort order can be either ASC or DESC.
   10810 */
   10811 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
   10812 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
   10813 
   10814 /*
   10815 ** Column affinity types.
   10816 **
   10817 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
   10818 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
   10819 ** the speed a little by numbering the values consecutively.
   10820 **
   10821 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
   10822 ** when multiple affinity types are concatenated into a string and
   10823 ** used as the P4 operand, they will be more readable.
   10824 **
   10825 ** Note also that the numeric types are grouped together so that testing
   10826 ** for a numeric type is a single comparison.
   10827 */
   10828 #define SQLITE_AFF_TEXT     'a'
   10829 #define SQLITE_AFF_NONE     'b'
   10830 #define SQLITE_AFF_NUMERIC  'c'
   10831 #define SQLITE_AFF_INTEGER  'd'
   10832 #define SQLITE_AFF_REAL     'e'
   10833 
   10834 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
   10835 
   10836 /*
   10837 ** The SQLITE_AFF_MASK values masks off the significant bits of an
   10838 ** affinity value.
   10839 */
   10840 #define SQLITE_AFF_MASK     0x67
   10841 
   10842 /*
   10843 ** Additional bit values that can be ORed with an affinity without
   10844 ** changing the affinity.
   10845 **
   10846 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
   10847 ** It causes an assert() to fire if either operand to a comparison
   10848 ** operator is NULL.  It is added to certain comparison operators to
   10849 ** prove that the operands are always NOT NULL.
   10850 */
   10851 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
   10852 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
   10853 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
   10854 #define SQLITE_NOTNULL      0x88  /* Assert that operands are never NULL */
   10855 
   10856 /*
   10857 ** An object of this type is created for each virtual table present in
   10858 ** the database schema.
   10859 **
   10860 ** If the database schema is shared, then there is one instance of this
   10861 ** structure for each database connection (sqlite3*) that uses the shared
   10862 ** schema. This is because each database connection requires its own unique
   10863 ** instance of the sqlite3_vtab* handle used to access the virtual table
   10864 ** implementation. sqlite3_vtab* handles can not be shared between
   10865 ** database connections, even when the rest of the in-memory database
   10866 ** schema is shared, as the implementation often stores the database
   10867 ** connection handle passed to it via the xConnect() or xCreate() method
   10868 ** during initialization internally. This database connection handle may
   10869 ** then be used by the virtual table implementation to access real tables
   10870 ** within the database. So that they appear as part of the callers
   10871 ** transaction, these accesses need to be made via the same database
   10872 ** connection as that used to execute SQL operations on the virtual table.
   10873 **
   10874 ** All VTable objects that correspond to a single table in a shared
   10875 ** database schema are initially stored in a linked-list pointed to by
   10876 ** the Table.pVTable member variable of the corresponding Table object.
   10877 ** When an sqlite3_prepare() operation is required to access the virtual
   10878 ** table, it searches the list for the VTable that corresponds to the
   10879 ** database connection doing the preparing so as to use the correct
   10880 ** sqlite3_vtab* handle in the compiled query.
   10881 **
   10882 ** When an in-memory Table object is deleted (for example when the
   10883 ** schema is being reloaded for some reason), the VTable objects are not
   10884 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
   10885 ** immediately. Instead, they are moved from the Table.pVTable list to
   10886 ** another linked list headed by the sqlite3.pDisconnect member of the
   10887 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
   10888 ** next time a statement is prepared using said sqlite3*. This is done
   10889 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
   10890 ** Refer to comments above function sqlite3VtabUnlockList() for an
   10891 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
   10892 ** list without holding the corresponding sqlite3.mutex mutex.
   10893 **
   10894 ** The memory for objects of this type is always allocated by
   10895 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
   10896 ** the first argument.
   10897 */
   10898 struct VTable {
   10899   sqlite3 *db;              /* Database connection associated with this table */
   10900   Module *pMod;             /* Pointer to module implementation */
   10901   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
   10902   int nRef;                 /* Number of pointers to this structure */
   10903   u8 bConstraint;           /* True if constraints are supported */
   10904   int iSavepoint;           /* Depth of the SAVEPOINT stack */
   10905   VTable *pNext;            /* Next in linked list (see above) */
   10906 };
   10907 
   10908 /*
   10909 ** Each SQL table is represented in memory by an instance of the
   10910 ** following structure.
   10911 **
   10912 ** Table.zName is the name of the table.  The case of the original
   10913 ** CREATE TABLE statement is stored, but case is not significant for
   10914 ** comparisons.
   10915 **
   10916 ** Table.nCol is the number of columns in this table.  Table.aCol is a
   10917 ** pointer to an array of Column structures, one for each column.
   10918 **
   10919 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
   10920 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
   10921 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
   10922 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
   10923 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
   10924 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
   10925 ** the table has any PRIMARY KEY, INTEGER or otherwise.
   10926 **
   10927 ** Table.tnum is the page number for the root BTree page of the table in the
   10928 ** database file.  If Table.iDb is the index of the database table backend
   10929 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
   10930 ** holds temporary tables and indices.  If TF_Ephemeral is set
   10931 ** then the table is stored in a file that is automatically deleted
   10932 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
   10933 ** refers VDBE cursor number that holds the table open, not to the root
   10934 ** page number.  Transient tables are used to hold the results of a
   10935 ** sub-query that appears instead of a real table name in the FROM clause
   10936 ** of a SELECT statement.
   10937 */
   10938 struct Table {
   10939   char *zName;         /* Name of the table or view */
   10940   Column *aCol;        /* Information about each column */
   10941   Index *pIndex;       /* List of SQL indexes on this table. */
   10942   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
   10943   FKey *pFKey;         /* Linked list of all foreign keys in this table */
   10944   char *zColAff;       /* String defining the affinity of each column */
   10945 #ifndef SQLITE_OMIT_CHECK
   10946   ExprList *pCheck;    /* All CHECK constraints */
   10947 #endif
   10948   LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
   10949   int tnum;            /* Root BTree node for this table (see note above) */
   10950   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
   10951   i16 nCol;            /* Number of columns in this table */
   10952   u16 nRef;            /* Number of pointers to this Table */
   10953   LogEst szTabRow;     /* Estimated size of each table row in bytes */
   10954 #ifdef SQLITE_ENABLE_COSTMULT
   10955   LogEst costMult;     /* Cost multiplier for using this table */
   10956 #endif
   10957   u8 tabFlags;         /* Mask of TF_* values */
   10958   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
   10959 #ifndef SQLITE_OMIT_ALTERTABLE
   10960   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
   10961 #endif
   10962 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10963   int nModuleArg;      /* Number of arguments to the module */
   10964   char **azModuleArg;  /* Text of all module args. [0] is module name */
   10965   VTable *pVTable;     /* List of VTable objects. */
   10966 #endif
   10967   Trigger *pTrigger;   /* List of triggers stored in pSchema */
   10968   Schema *pSchema;     /* Schema that contains this table */
   10969   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
   10970 };
   10971 
   10972 /*
   10973 ** Allowed values for Table.tabFlags.
   10974 */
   10975 #define TF_Readonly        0x01    /* Read-only system table */
   10976 #define TF_Ephemeral       0x02    /* An ephemeral table */
   10977 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
   10978 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
   10979 #define TF_Virtual         0x10    /* Is a virtual table */
   10980 #define TF_WithoutRowid    0x20    /* No rowid used. PRIMARY KEY is the key */
   10981 
   10982 
   10983 /*
   10984 ** Test to see whether or not a table is a virtual table.  This is
   10985 ** done as a macro so that it will be optimized out when virtual
   10986 ** table support is omitted from the build.
   10987 */
   10988 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10989 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
   10990 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
   10991 #else
   10992 #  define IsVirtual(X)      0
   10993 #  define IsHiddenColumn(X) 0
   10994 #endif
   10995 
   10996 /* Does the table have a rowid */
   10997 #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
   10998 
   10999 /*
   11000 ** Each foreign key constraint is an instance of the following structure.
   11001 **
   11002 ** A foreign key is associated with two tables.  The "from" table is
   11003 ** the table that contains the REFERENCES clause that creates the foreign
   11004 ** key.  The "to" table is the table that is named in the REFERENCES clause.
   11005 ** Consider this example:
   11006 **
   11007 **     CREATE TABLE ex1(
   11008 **       a INTEGER PRIMARY KEY,
   11009 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
   11010 **     );
   11011 **
   11012 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
   11013 ** Equivalent names:
   11014 **
   11015 **     from-table == child-table
   11016 **       to-table == parent-table
   11017 **
   11018 ** Each REFERENCES clause generates an instance of the following structure
   11019 ** which is attached to the from-table.  The to-table need not exist when
   11020 ** the from-table is created.  The existence of the to-table is not checked.
   11021 **
   11022 ** The list of all parents for child Table X is held at X.pFKey.
   11023 **
   11024 ** A list of all children for a table named Z (which might not even exist)
   11025 ** is held in Schema.fkeyHash with a hash key of Z.
   11026 */
   11027 struct FKey {
   11028   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
   11029   FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
   11030   char *zTo;        /* Name of table that the key points to (aka: Parent) */
   11031   FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
   11032   FKey *pPrevTo;    /* Previous with the same zTo */
   11033   int nCol;         /* Number of columns in this key */
   11034   /* EV: R-30323-21917 */
   11035   u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
   11036   u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
   11037   Trigger *apTrigger[2];/* Triggers for aAction[] actions */
   11038   struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
   11039     int iFrom;            /* Index of column in pFrom */
   11040     char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
   11041   } aCol[1];            /* One entry for each of nCol columns */
   11042 };
   11043 
   11044 /*
   11045 ** SQLite supports many different ways to resolve a constraint
   11046 ** error.  ROLLBACK processing means that a constraint violation
   11047 ** causes the operation in process to fail and for the current transaction
   11048 ** to be rolled back.  ABORT processing means the operation in process
   11049 ** fails and any prior changes from that one operation are backed out,
   11050 ** but the transaction is not rolled back.  FAIL processing means that
   11051 ** the operation in progress stops and returns an error code.  But prior
   11052 ** changes due to the same operation are not backed out and no rollback
   11053 ** occurs.  IGNORE means that the particular row that caused the constraint
   11054 ** error is not inserted or updated.  Processing continues and no error
   11055 ** is returned.  REPLACE means that preexisting database rows that caused
   11056 ** a UNIQUE constraint violation are removed so that the new insert or
   11057 ** update can proceed.  Processing continues and no error is reported.
   11058 **
   11059 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
   11060 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
   11061 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
   11062 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
   11063 ** referenced table row is propagated into the row that holds the
   11064 ** foreign key.
   11065 **
   11066 ** The following symbolic values are used to record which type
   11067 ** of action to take.
   11068 */
   11069 #define OE_None     0   /* There is no constraint to check */
   11070 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
   11071 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
   11072 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
   11073 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
   11074 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
   11075 
   11076 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
   11077 #define OE_SetNull  7   /* Set the foreign key value to NULL */
   11078 #define OE_SetDflt  8   /* Set the foreign key value to its default */
   11079 #define OE_Cascade  9   /* Cascade the changes */
   11080 
   11081 #define OE_Default  10  /* Do whatever the default action is */
   11082 
   11083 
   11084 /*
   11085 ** An instance of the following structure is passed as the first
   11086 ** argument to sqlite3VdbeKeyCompare and is used to control the
   11087 ** comparison of the two index keys.
   11088 **
   11089 ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
   11090 ** are nField slots for the columns of an index then one extra slot
   11091 ** for the rowid at the end.
   11092 */
   11093 struct KeyInfo {
   11094   u32 nRef;           /* Number of references to this KeyInfo object */
   11095   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
   11096   u16 nField;         /* Number of key columns in the index */
   11097   u16 nXField;        /* Number of columns beyond the key columns */
   11098   sqlite3 *db;        /* The database connection */
   11099   u8 *aSortOrder;     /* Sort order for each column. */
   11100   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
   11101 };
   11102 
   11103 /*
   11104 ** An instance of the following structure holds information about a
   11105 ** single index record that has already been parsed out into individual
   11106 ** values.
   11107 **
   11108 ** A record is an object that contains one or more fields of data.
   11109 ** Records are used to store the content of a table row and to store
   11110 ** the key of an index.  A blob encoding of a record is created by
   11111 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
   11112 ** OP_Column opcode.
   11113 **
   11114 ** This structure holds a record that has already been disassembled
   11115 ** into its constituent fields.
   11116 **
   11117 ** The r1 and r2 member variables are only used by the optimized comparison
   11118 ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
   11119 */
   11120 struct UnpackedRecord {
   11121   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
   11122   u16 nField;         /* Number of entries in apMem[] */
   11123   i8 default_rc;      /* Comparison result if keys are equal */
   11124   u8 isCorrupt;       /* Corruption detected by xRecordCompare() */
   11125   Mem *aMem;          /* Values */
   11126   int r1;             /* Value to return if (lhs > rhs) */
   11127   int r2;             /* Value to return if (rhs < lhs) */
   11128 };
   11129 
   11130 
   11131 /*
   11132 ** Each SQL index is represented in memory by an
   11133 ** instance of the following structure.
   11134 **
   11135 ** The columns of the table that are to be indexed are described
   11136 ** by the aiColumn[] field of this structure.  For example, suppose
   11137 ** we have the following table and index:
   11138 **
   11139 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
   11140 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
   11141 **
   11142 ** In the Table structure describing Ex1, nCol==3 because there are
   11143 ** three columns in the table.  In the Index structure describing
   11144 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
   11145 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
   11146 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
   11147 ** The second column to be indexed (c1) has an index of 0 in
   11148 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
   11149 **
   11150 ** The Index.onError field determines whether or not the indexed columns
   11151 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
   11152 ** it means this is not a unique index.  Otherwise it is a unique index
   11153 ** and the value of Index.onError indicate the which conflict resolution
   11154 ** algorithm to employ whenever an attempt is made to insert a non-unique
   11155 ** element.
   11156 */
   11157 struct Index {
   11158   char *zName;             /* Name of this index */
   11159   i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
   11160   LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
   11161   Table *pTable;           /* The SQL table being indexed */
   11162   char *zColAff;           /* String defining the affinity of each column */
   11163   Index *pNext;            /* The next index associated with the same table */
   11164   Schema *pSchema;         /* Schema containing this index */
   11165   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
   11166   char **azColl;           /* Array of collation sequence names for index */
   11167   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
   11168   KeyInfo *pKeyInfo;       /* A KeyInfo object suitable for this index */
   11169   int tnum;                /* DB Page containing root of this index */
   11170   LogEst szIdxRow;         /* Estimated average row size in bytes */
   11171   u16 nKeyCol;             /* Number of columns forming the key */
   11172   u16 nColumn;             /* Number of columns stored in the index */
   11173   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   11174   unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
   11175   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
   11176   unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
   11177   unsigned isResized:1;    /* True if resizeIndexObject() has been called */
   11178   unsigned isCovering:1;   /* True if this is a covering index */
   11179 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   11180   int nSample;             /* Number of elements in aSample[] */
   11181   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
   11182   tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
   11183   IndexSample *aSample;    /* Samples of the left-most key */
   11184 #endif
   11185 };
   11186 
   11187 /*
   11188 ** Allowed values for Index.idxType
   11189 */
   11190 #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
   11191 #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
   11192 #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
   11193 
   11194 /* Return true if index X is a PRIMARY KEY index */
   11195 #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
   11196 
   11197 /* Return true if index X is a UNIQUE index */
   11198 #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
   11199 
   11200 /*
   11201 ** Each sample stored in the sqlite_stat3 table is represented in memory
   11202 ** using a structure of this type.  See documentation at the top of the
   11203 ** analyze.c source file for additional information.
   11204 */
   11205 struct IndexSample {
   11206   void *p;          /* Pointer to sampled record */
   11207   int n;            /* Size of record in bytes */
   11208   tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
   11209   tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
   11210   tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
   11211 };
   11212 
   11213 /*
   11214 ** Each token coming out of the lexer is an instance of
   11215 ** this structure.  Tokens are also used as part of an expression.
   11216 **
   11217 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
   11218 ** may contain random values.  Do not make any assumptions about Token.dyn
   11219 ** and Token.n when Token.z==0.
   11220 */
   11221 struct Token {
   11222   const char *z;     /* Text of the token.  Not NULL-terminated! */
   11223   unsigned int n;    /* Number of characters in this token */
   11224 };
   11225 
   11226 /*
   11227 ** An instance of this structure contains information needed to generate
   11228 ** code for a SELECT that contains aggregate functions.
   11229 **
   11230 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
   11231 ** pointer to this structure.  The Expr.iColumn field is the index in
   11232 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
   11233 ** code for that node.
   11234 **
   11235 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
   11236 ** original Select structure that describes the SELECT statement.  These
   11237 ** fields do not need to be freed when deallocating the AggInfo structure.
   11238 */
   11239 struct AggInfo {
   11240   u8 directMode;          /* Direct rendering mode means take data directly
   11241                           ** from source tables rather than from accumulators */
   11242   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
   11243                           ** than the source table */
   11244   int sortingIdx;         /* Cursor number of the sorting index */
   11245   int sortingIdxPTab;     /* Cursor number of pseudo-table */
   11246   int nSortingColumn;     /* Number of columns in the sorting index */
   11247   int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
   11248   ExprList *pGroupBy;     /* The group by clause */
   11249   struct AggInfo_col {    /* For each column used in source tables */
   11250     Table *pTab;             /* Source table */
   11251     int iTable;              /* Cursor number of the source table */
   11252     int iColumn;             /* Column number within the source table */
   11253     int iSorterColumn;       /* Column number in the sorting index */
   11254     int iMem;                /* Memory location that acts as accumulator */
   11255     Expr *pExpr;             /* The original expression */
   11256   } *aCol;
   11257   int nColumn;            /* Number of used entries in aCol[] */
   11258   int nAccumulator;       /* Number of columns that show through to the output.
   11259                           ** Additional columns are used only as parameters to
   11260                           ** aggregate functions */
   11261   struct AggInfo_func {   /* For each aggregate function */
   11262     Expr *pExpr;             /* Expression encoding the function */
   11263     FuncDef *pFunc;          /* The aggregate function implementation */
   11264     int iMem;                /* Memory location that acts as accumulator */
   11265     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
   11266   } *aFunc;
   11267   int nFunc;              /* Number of entries in aFunc[] */
   11268 };
   11269 
   11270 /*
   11271 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
   11272 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
   11273 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
   11274 ** it uses less memory in the Expr object, which is a big memory user
   11275 ** in systems with lots of prepared statements.  And few applications
   11276 ** need more than about 10 or 20 variables.  But some extreme users want
   11277 ** to have prepared statements with over 32767 variables, and for them
   11278 ** the option is available (at compile-time).
   11279 */
   11280 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
   11281 typedef i16 ynVar;
   11282 #else
   11283 typedef int ynVar;
   11284 #endif
   11285 
   11286 /*
   11287 ** Each node of an expression in the parse tree is an instance
   11288 ** of this structure.
   11289 **
   11290 ** Expr.op is the opcode. The integer parser token codes are reused
   11291 ** as opcodes here. For example, the parser defines TK_GE to be an integer
   11292 ** code representing the ">=" operator. This same integer code is reused
   11293 ** to represent the greater-than-or-equal-to operator in the expression
   11294 ** tree.
   11295 **
   11296 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
   11297 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
   11298 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
   11299 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
   11300 ** then Expr.token contains the name of the function.
   11301 **
   11302 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
   11303 ** binary operator. Either or both may be NULL.
   11304 **
   11305 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
   11306 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
   11307 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
   11308 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
   11309 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
   11310 ** valid.
   11311 **
   11312 ** An expression of the form ID or ID.ID refers to a column in a table.
   11313 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
   11314 ** the integer cursor number of a VDBE cursor pointing to that table and
   11315 ** Expr.iColumn is the column number for the specific column.  If the
   11316 ** expression is used as a result in an aggregate SELECT, then the
   11317 ** value is also stored in the Expr.iAgg column in the aggregate so that
   11318 ** it can be accessed after all aggregates are computed.
   11319 **
   11320 ** If the expression is an unbound variable marker (a question mark
   11321 ** character '?' in the original SQL) then the Expr.iTable holds the index
   11322 ** number for that variable.
   11323 **
   11324 ** If the expression is a subquery then Expr.iColumn holds an integer
   11325 ** register number containing the result of the subquery.  If the
   11326 ** subquery gives a constant result, then iTable is -1.  If the subquery
   11327 ** gives a different answer at different times during statement processing
   11328 ** then iTable is the address of a subroutine that computes the subquery.
   11329 **
   11330 ** If the Expr is of type OP_Column, and the table it is selecting from
   11331 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
   11332 ** corresponding table definition.
   11333 **
   11334 ** ALLOCATION NOTES:
   11335 **
   11336 ** Expr objects can use a lot of memory space in database schema.  To
   11337 ** help reduce memory requirements, sometimes an Expr object will be
   11338 ** truncated.  And to reduce the number of memory allocations, sometimes
   11339 ** two or more Expr objects will be stored in a single memory allocation,
   11340 ** together with Expr.zToken strings.
   11341 **
   11342 ** If the EP_Reduced and EP_TokenOnly flags are set when
   11343 ** an Expr object is truncated.  When EP_Reduced is set, then all
   11344 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
   11345 ** are contained within the same memory allocation.  Note, however, that
   11346 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
   11347 ** allocated, regardless of whether or not EP_Reduced is set.
   11348 */
   11349 struct Expr {
   11350   u8 op;                 /* Operation performed by this node */
   11351   char affinity;         /* The affinity of the column or 0 if not a column */
   11352   u32 flags;             /* Various flags.  EP_* See below */
   11353   union {
   11354     char *zToken;          /* Token value. Zero terminated and dequoted */
   11355     int iValue;            /* Non-negative integer value if EP_IntValue */
   11356   } u;
   11357 
   11358   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
   11359   ** space is allocated for the fields below this point. An attempt to
   11360   ** access them will result in a segfault or malfunction.
   11361   *********************************************************************/
   11362 
   11363   Expr *pLeft;           /* Left subnode */
   11364   Expr *pRight;          /* Right subnode */
   11365   union {
   11366     ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
   11367     Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
   11368   } x;
   11369 
   11370   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
   11371   ** space is allocated for the fields below this point. An attempt to
   11372   ** access them will result in a segfault or malfunction.
   11373   *********************************************************************/
   11374 
   11375 #if SQLITE_MAX_EXPR_DEPTH>0
   11376   int nHeight;           /* Height of the tree headed by this node */
   11377 #endif
   11378   int iTable;            /* TK_COLUMN: cursor number of table holding column
   11379                          ** TK_REGISTER: register number
   11380                          ** TK_TRIGGER: 1 -> new, 0 -> old
   11381                          ** EP_Unlikely:  1000 times likelihood */
   11382   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
   11383                          ** TK_VARIABLE: variable number (always >= 1). */
   11384   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
   11385   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
   11386   u8 op2;                /* TK_REGISTER: original value of Expr.op
   11387                          ** TK_COLUMN: the value of p5 for OP_Column
   11388                          ** TK_AGG_FUNCTION: nesting depth */
   11389   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   11390   Table *pTab;           /* Table for TK_COLUMN expressions. */
   11391 };
   11392 
   11393 /*
   11394 ** The following are the meanings of bits in the Expr.flags field.
   11395 */
   11396 #define EP_FromJoin  0x000001 /* Originated in ON or USING clause of a join */
   11397 #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
   11398 #define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
   11399 #define EP_Error     0x000008 /* Expression contains one or more errors */
   11400 #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
   11401 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
   11402 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
   11403 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
   11404 #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
   11405 #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
   11406 #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
   11407 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
   11408 #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
   11409 #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
   11410 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
   11411 #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
   11412 #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
   11413 #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
   11414 #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
   11415 #define EP_Constant  0x080000 /* Node is a constant */
   11416 
   11417 /*
   11418 ** These macros can be used to test, set, or clear bits in the
   11419 ** Expr.flags field.
   11420 */
   11421 #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
   11422 #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
   11423 #define ExprSetProperty(E,P)     (E)->flags|=(P)
   11424 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
   11425 
   11426 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
   11427 ** and Accreditation only.  It works like ExprSetProperty() during VVA
   11428 ** processes but is a no-op for delivery.
   11429 */
   11430 #ifdef SQLITE_DEBUG
   11431 # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
   11432 #else
   11433 # define ExprSetVVAProperty(E,P)
   11434 #endif
   11435 
   11436 /*
   11437 ** Macros to determine the number of bytes required by a normal Expr
   11438 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
   11439 ** and an Expr struct with the EP_TokenOnly flag set.
   11440 */
   11441 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
   11442 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
   11443 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
   11444 
   11445 /*
   11446 ** Flags passed to the sqlite3ExprDup() function. See the header comment
   11447 ** above sqlite3ExprDup() for details.
   11448 */
   11449 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
   11450 
   11451 /*
   11452 ** A list of expressions.  Each expression may optionally have a
   11453 ** name.  An expr/name combination can be used in several ways, such
   11454 ** as the list of "expr AS ID" fields following a "SELECT" or in the
   11455 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
   11456 ** also be used as the argument to a function, in which case the a.zName
   11457 ** field is not used.
   11458 **
   11459 ** By default the Expr.zSpan field holds a human-readable description of
   11460 ** the expression that is used in the generation of error messages and
   11461 ** column labels.  In this case, Expr.zSpan is typically the text of a
   11462 ** column expression as it exists in a SELECT statement.  However, if
   11463 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
   11464 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
   11465 ** form is used for name resolution with nested FROM clauses.
   11466 */
   11467 struct ExprList {
   11468   int nExpr;             /* Number of expressions on the list */
   11469   struct ExprList_item { /* For each expression in the list */
   11470     Expr *pExpr;            /* The list of expressions */
   11471     char *zName;            /* Token associated with this expression */
   11472     char *zSpan;            /* Original text of the expression */
   11473     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
   11474     unsigned done :1;       /* A flag to indicate when processing is finished */
   11475     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
   11476     unsigned reusable :1;   /* Constant expression is reusable */
   11477     union {
   11478       struct {
   11479         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
   11480         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
   11481       } x;
   11482       int iConstExprReg;      /* Register in which Expr value is cached */
   11483     } u;
   11484   } *a;                  /* Alloc a power of two greater or equal to nExpr */
   11485 };
   11486 
   11487 /*
   11488 ** An instance of this structure is used by the parser to record both
   11489 ** the parse tree for an expression and the span of input text for an
   11490 ** expression.
   11491 */
   11492 struct ExprSpan {
   11493   Expr *pExpr;          /* The expression parse tree */
   11494   const char *zStart;   /* First character of input text */
   11495   const char *zEnd;     /* One character past the end of input text */
   11496 };
   11497 
   11498 /*
   11499 ** An instance of this structure can hold a simple list of identifiers,
   11500 ** such as the list "a,b,c" in the following statements:
   11501 **
   11502 **      INSERT INTO t(a,b,c) VALUES ...;
   11503 **      CREATE INDEX idx ON t(a,b,c);
   11504 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
   11505 **
   11506 ** The IdList.a.idx field is used when the IdList represents the list of
   11507 ** column names after a table name in an INSERT statement.  In the statement
   11508 **
   11509 **     INSERT INTO t(a,b,c) ...
   11510 **
   11511 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
   11512 */
   11513 struct IdList {
   11514   struct IdList_item {
   11515     char *zName;      /* Name of the identifier */
   11516     int idx;          /* Index in some Table.aCol[] of a column named zName */
   11517   } *a;
   11518   int nId;         /* Number of identifiers on the list */
   11519 };
   11520 
   11521 /*
   11522 ** The bitmask datatype defined below is used for various optimizations.
   11523 **
   11524 ** Changing this from a 64-bit to a 32-bit type limits the number of
   11525 ** tables in a join to 32 instead of 64.  But it also reduces the size
   11526 ** of the library by 738 bytes on ix86.
   11527 */
   11528 typedef u64 Bitmask;
   11529 
   11530 /*
   11531 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
   11532 */
   11533 #define BMS  ((int)(sizeof(Bitmask)*8))
   11534 
   11535 /*
   11536 ** A bit in a Bitmask
   11537 */
   11538 #define MASKBIT(n)   (((Bitmask)1)<<(n))
   11539 #define MASKBIT32(n) (((unsigned int)1)<<(n))
   11540 
   11541 /*
   11542 ** The following structure describes the FROM clause of a SELECT statement.
   11543 ** Each table or subquery in the FROM clause is a separate element of
   11544 ** the SrcList.a[] array.
   11545 **
   11546 ** With the addition of multiple database support, the following structure
   11547 ** can also be used to describe a particular table such as the table that
   11548 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
   11549 ** such a table must be a simple name: ID.  But in SQLite, the table can
   11550 ** now be identified by a database name, a dot, then the table name: ID.ID.
   11551 **
   11552 ** The jointype starts out showing the join type between the current table
   11553 ** and the next table on the list.  The parser builds the list this way.
   11554 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
   11555 ** jointype expresses the join between the table and the previous table.
   11556 **
   11557 ** In the colUsed field, the high-order bit (bit 63) is set if the table
   11558 ** contains more than 63 columns and the 64-th or later column is used.
   11559 */
   11560 struct SrcList {
   11561   int nSrc;        /* Number of tables or subqueries in the FROM clause */
   11562   u32 nAlloc;      /* Number of entries allocated in a[] below */
   11563   struct SrcList_item {
   11564     Schema *pSchema;  /* Schema to which this item is fixed */
   11565     char *zDatabase;  /* Name of database holding this table */
   11566     char *zName;      /* Name of the table */
   11567     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
   11568     Table *pTab;      /* An SQL table corresponding to zName */
   11569     Select *pSelect;  /* A SELECT statement used in place of a table name */
   11570     int addrFillSub;  /* Address of subroutine to manifest a subquery */
   11571     int regReturn;    /* Register holding return address of addrFillSub */
   11572     int regResult;    /* Registers holding results of a co-routine */
   11573     u8 jointype;      /* Type of join between this able and the previous */
   11574     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
   11575     unsigned isCorrelated :1;  /* True if sub-query is correlated */
   11576     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
   11577     unsigned isRecursive :1;   /* True for recursive reference in WITH */
   11578 #ifndef SQLITE_OMIT_EXPLAIN
   11579     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
   11580 #endif
   11581     int iCursor;      /* The VDBE cursor number used to access this table */
   11582     Expr *pOn;        /* The ON clause of a join */
   11583     IdList *pUsing;   /* The USING clause of a join */
   11584     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
   11585     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
   11586     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
   11587   } a[1];             /* One entry for each identifier on the list */
   11588 };
   11589 
   11590 /*
   11591 ** Permitted values of the SrcList.a.jointype field
   11592 */
   11593 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
   11594 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
   11595 #define JT_NATURAL   0x0004    /* True for a "natural" join */
   11596 #define JT_LEFT      0x0008    /* Left outer join */
   11597 #define JT_RIGHT     0x0010    /* Right outer join */
   11598 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
   11599 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
   11600 
   11601 
   11602 /*
   11603 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
   11604 ** and the WhereInfo.wctrlFlags member.
   11605 */
   11606 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
   11607 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
   11608 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
   11609 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
   11610 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
   11611 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
   11612 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
   11613 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
   11614 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
   11615 #define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
   11616 #define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
   11617 #define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
   11618 #define WHERE_SORTBYGROUP      0x0800 /* Support sqlite3WhereIsSorted() */
   11619 #define WHERE_REOPEN_IDX       0x1000 /* Try to use OP_ReopenIdx */
   11620 
   11621 /* Allowed return values from sqlite3WhereIsDistinct()
   11622 */
   11623 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
   11624 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
   11625 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
   11626 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
   11627 
   11628 /*
   11629 ** A NameContext defines a context in which to resolve table and column
   11630 ** names.  The context consists of a list of tables (the pSrcList) field and
   11631 ** a list of named expression (pEList).  The named expression list may
   11632 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
   11633 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
   11634 ** pEList corresponds to the result set of a SELECT and is NULL for
   11635 ** other statements.
   11636 **
   11637 ** NameContexts can be nested.  When resolving names, the inner-most
   11638 ** context is searched first.  If no match is found, the next outer
   11639 ** context is checked.  If there is still no match, the next context
   11640 ** is checked.  This process continues until either a match is found
   11641 ** or all contexts are check.  When a match is found, the nRef member of
   11642 ** the context containing the match is incremented.
   11643 **
   11644 ** Each subquery gets a new NameContext.  The pNext field points to the
   11645 ** NameContext in the parent query.  Thus the process of scanning the
   11646 ** NameContext list corresponds to searching through successively outer
   11647 ** subqueries looking for a match.
   11648 */
   11649 struct NameContext {
   11650   Parse *pParse;       /* The parser */
   11651   SrcList *pSrcList;   /* One or more tables used to resolve names */
   11652   ExprList *pEList;    /* Optional list of result-set columns */
   11653   AggInfo *pAggInfo;   /* Information about aggregates at this level */
   11654   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
   11655   int nRef;            /* Number of names resolved by this context */
   11656   int nErr;            /* Number of errors encountered while resolving names */
   11657   u8 ncFlags;          /* Zero or more NC_* flags defined below */
   11658 };
   11659 
   11660 /*
   11661 ** Allowed values for the NameContext, ncFlags field.
   11662 */
   11663 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
   11664 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
   11665 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
   11666 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
   11667 #define NC_PartIdx   0x10    /* True if resolving a partial index WHERE */
   11668 
   11669 /*
   11670 ** An instance of the following structure contains all information
   11671 ** needed to generate code for a single SELECT statement.
   11672 **
   11673 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
   11674 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
   11675 ** limit and nOffset to the value of the offset (or 0 if there is not
   11676 ** offset).  But later on, nLimit and nOffset become the memory locations
   11677 ** in the VDBE that record the limit and offset counters.
   11678 **
   11679 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
   11680 ** These addresses must be stored so that we can go back and fill in
   11681 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
   11682 ** the number of columns in P2 can be computed at the same time
   11683 ** as the OP_OpenEphm instruction is coded because not
   11684 ** enough information about the compound query is known at that point.
   11685 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
   11686 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
   11687 ** sequences for the ORDER BY clause.
   11688 */
   11689 struct Select {
   11690   ExprList *pEList;      /* The fields of the result */
   11691   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
   11692   u16 selFlags;          /* Various SF_* values */
   11693   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
   11694   int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
   11695   u64 nSelectRow;        /* Estimated number of result rows */
   11696   SrcList *pSrc;         /* The FROM clause */
   11697   Expr *pWhere;          /* The WHERE clause */
   11698   ExprList *pGroupBy;    /* The GROUP BY clause */
   11699   Expr *pHaving;         /* The HAVING clause */
   11700   ExprList *pOrderBy;    /* The ORDER BY clause */
   11701   Select *pPrior;        /* Prior select in a compound select statement */
   11702   Select *pNext;         /* Next select to the left in a compound */
   11703   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
   11704   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
   11705   With *pWith;           /* WITH clause attached to this select. Or NULL. */
   11706 };
   11707 
   11708 /*
   11709 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
   11710 ** "Select Flag".
   11711 */
   11712 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
   11713 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
   11714 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
   11715 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
   11716 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
   11717 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
   11718                     /*     0x0040  NOT USED */
   11719 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
   11720                     /*     0x0100  NOT USED */
   11721 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
   11722 #define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
   11723 #define SF_Recursive       0x0800  /* The recursive part of a recursive CTE */
   11724 #define SF_Compound        0x1000  /* Part of a compound query */
   11725 
   11726 
   11727 /*
   11728 ** The results of a SELECT can be distributed in several ways, as defined
   11729 ** by one of the following macros.  The "SRT" prefix means "SELECT Result
   11730 ** Type".
   11731 **
   11732 **     SRT_Union       Store results as a key in a temporary index
   11733 **                     identified by pDest->iSDParm.
   11734 **
   11735 **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
   11736 **
   11737 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
   11738 **                     set is not empty.
   11739 **
   11740 **     SRT_Discard     Throw the results away.  This is used by SELECT
   11741 **                     statements within triggers whose only purpose is
   11742 **                     the side-effects of functions.
   11743 **
   11744 ** All of the above are free to ignore their ORDER BY clause. Those that
   11745 ** follow must honor the ORDER BY clause.
   11746 **
   11747 **     SRT_Output      Generate a row of output (using the OP_ResultRow
   11748 **                     opcode) for each row in the result set.
   11749 **
   11750 **     SRT_Mem         Only valid if the result is a single column.
   11751 **                     Store the first column of the first result row
   11752 **                     in register pDest->iSDParm then abandon the rest
   11753 **                     of the query.  This destination implies "LIMIT 1".
   11754 **
   11755 **     SRT_Set         The result must be a single column.  Store each
   11756 **                     row of result as the key in table pDest->iSDParm.
   11757 **                     Apply the affinity pDest->affSdst before storing
   11758 **                     results.  Used to implement "IN (SELECT ...)".
   11759 **
   11760 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
   11761 **                     the result there. The cursor is left open after
   11762 **                     returning.  This is like SRT_Table except that
   11763 **                     this destination uses OP_OpenEphemeral to create
   11764 **                     the table first.
   11765 **
   11766 **     SRT_Coroutine   Generate a co-routine that returns a new row of
   11767 **                     results each time it is invoked.  The entry point
   11768 **                     of the co-routine is stored in register pDest->iSDParm
   11769 **                     and the result row is stored in pDest->nDest registers
   11770 **                     starting with pDest->iSdst.
   11771 **
   11772 **     SRT_Table       Store results in temporary table pDest->iSDParm.
   11773 **     SRT_Fifo        This is like SRT_EphemTab except that the table
   11774 **                     is assumed to already be open.  SRT_Fifo has
   11775 **                     the additional property of being able to ignore
   11776 **                     the ORDER BY clause.
   11777 **
   11778 **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
   11779 **                     But also use temporary table pDest->iSDParm+1 as
   11780 **                     a record of all prior results and ignore any duplicate
   11781 **                     rows.  Name means:  "Distinct Fifo".
   11782 **
   11783 **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
   11784 **                     an index).  Append a sequence number so that all entries
   11785 **                     are distinct.
   11786 **
   11787 **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
   11788 **                     the same record has never been stored before.  The
   11789 **                     index at pDest->iSDParm+1 hold all prior stores.
   11790 */
   11791 #define SRT_Union        1  /* Store result as keys in an index */
   11792 #define SRT_Except       2  /* Remove result from a UNION index */
   11793 #define SRT_Exists       3  /* Store 1 if the result is not empty */
   11794 #define SRT_Discard      4  /* Do not save the results anywhere */
   11795 #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
   11796 #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
   11797 #define SRT_Queue        7  /* Store result in an queue */
   11798 #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
   11799 
   11800 /* The ORDER BY clause is ignored for all of the above */
   11801 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
   11802 
   11803 #define SRT_Output       9  /* Output each row of result */
   11804 #define SRT_Mem         10  /* Store result in a memory cell */
   11805 #define SRT_Set         11  /* Store results as keys in an index */
   11806 #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
   11807 #define SRT_Coroutine   13  /* Generate a single row of result */
   11808 #define SRT_Table       14  /* Store result as data with an automatic rowid */
   11809 
   11810 /*
   11811 ** An instance of this object describes where to put of the results of
   11812 ** a SELECT statement.
   11813 */
   11814 struct SelectDest {
   11815   u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
   11816   char affSdst;        /* Affinity used when eDest==SRT_Set */
   11817   int iSDParm;         /* A parameter used by the eDest disposal method */
   11818   int iSdst;           /* Base register where results are written */
   11819   int nSdst;           /* Number of registers allocated */
   11820   ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
   11821 };
   11822 
   11823 /*
   11824 ** During code generation of statements that do inserts into AUTOINCREMENT
   11825 ** tables, the following information is attached to the Table.u.autoInc.p
   11826 ** pointer of each autoincrement table to record some side information that
   11827 ** the code generator needs.  We have to keep per-table autoincrement
   11828 ** information in case inserts are down within triggers.  Triggers do not
   11829 ** normally coordinate their activities, but we do need to coordinate the
   11830 ** loading and saving of autoincrement information.
   11831 */
   11832 struct AutoincInfo {
   11833   AutoincInfo *pNext;   /* Next info block in a list of them all */
   11834   Table *pTab;          /* Table this info block refers to */
   11835   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
   11836   int regCtr;           /* Memory register holding the rowid counter */
   11837 };
   11838 
   11839 /*
   11840 ** Size of the column cache
   11841 */
   11842 #ifndef SQLITE_N_COLCACHE
   11843 # define SQLITE_N_COLCACHE 10
   11844 #endif
   11845 
   11846 /*
   11847 ** At least one instance of the following structure is created for each
   11848 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
   11849 ** statement. All such objects are stored in the linked list headed at
   11850 ** Parse.pTriggerPrg and deleted once statement compilation has been
   11851 ** completed.
   11852 **
   11853 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
   11854 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
   11855 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
   11856 ** The Parse.pTriggerPrg list never contains two entries with the same
   11857 ** values for both pTrigger and orconf.
   11858 **
   11859 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
   11860 ** accessed (or set to 0 for triggers fired as a result of INSERT
   11861 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
   11862 ** a mask of new.* columns used by the program.
   11863 */
   11864 struct TriggerPrg {
   11865   Trigger *pTrigger;      /* Trigger this program was coded from */
   11866   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
   11867   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
   11868   int orconf;             /* Default ON CONFLICT policy */
   11869   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
   11870 };
   11871 
   11872 /*
   11873 ** The yDbMask datatype for the bitmask of all attached databases.
   11874 */
   11875 #if SQLITE_MAX_ATTACHED>30
   11876   typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
   11877 # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
   11878 # define DbMaskZero(M)      memset((M),0,sizeof(M))
   11879 # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
   11880 # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
   11881 # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
   11882 #else
   11883   typedef unsigned int yDbMask;
   11884 # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
   11885 # define DbMaskZero(M)      (M)=0
   11886 # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
   11887 # define DbMaskAllZero(M)   (M)==0
   11888 # define DbMaskNonZero(M)   (M)!=0
   11889 #endif
   11890 
   11891 /*
   11892 ** An SQL parser context.  A copy of this structure is passed through
   11893 ** the parser and down into all the parser action routine in order to
   11894 ** carry around information that is global to the entire parse.
   11895 **
   11896 ** The structure is divided into two parts.  When the parser and code
   11897 ** generate call themselves recursively, the first part of the structure
   11898 ** is constant but the second part is reset at the beginning and end of
   11899 ** each recursion.
   11900 **
   11901 ** The nTableLock and aTableLock variables are only used if the shared-cache
   11902 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
   11903 ** used to store the set of table-locks required by the statement being
   11904 ** compiled. Function sqlite3TableLock() is used to add entries to the
   11905 ** list.
   11906 */
   11907 struct Parse {
   11908   sqlite3 *db;         /* The main database structure */
   11909   char *zErrMsg;       /* An error message */
   11910   Vdbe *pVdbe;         /* An engine for executing database bytecode */
   11911   int rc;              /* Return code from execution */
   11912   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
   11913   u8 checkSchema;      /* Causes schema cookie check after an error */
   11914   u8 nested;           /* Number of nested calls to the parser/code generator */
   11915   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
   11916   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
   11917   u8 mayAbort;         /* True if statement may throw an ABORT exception */
   11918   u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
   11919   u8 okConstFactor;    /* OK to factor out constants */
   11920   int aTempReg[8];     /* Holding area for temporary registers */
   11921   int nRangeReg;       /* Size of the temporary register block */
   11922   int iRangeReg;       /* First register in temporary register block */
   11923   int nErr;            /* Number of errors seen */
   11924   int nTab;            /* Number of previously allocated VDBE cursors */
   11925   int nMem;            /* Number of memory cells used so far */
   11926   int nSet;            /* Number of sets used so far */
   11927   int nOnce;           /* Number of OP_Once instructions so far */
   11928   int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
   11929   int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
   11930   int ckBase;          /* Base register of data during check constraints */
   11931   int iPartIdxTab;     /* Table corresponding to a partial index */
   11932   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
   11933   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
   11934   int nLabel;          /* Number of labels used */
   11935   int *aLabel;         /* Space to hold the labels */
   11936   struct yColCache {
   11937     int iTable;           /* Table cursor number */
   11938     i16 iColumn;          /* Table column number */
   11939     u8 tempReg;           /* iReg is a temp register that needs to be freed */
   11940     int iLevel;           /* Nesting level */
   11941     int iReg;             /* Reg with value of this column. 0 means none. */
   11942     int lru;              /* Least recently used entry has the smallest value */
   11943   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
   11944   ExprList *pConstExpr;/* Constant expressions */
   11945   Token constraintName;/* Name of the constraint currently being parsed */
   11946   yDbMask writeMask;   /* Start a write transaction on these databases */
   11947   yDbMask cookieMask;  /* Bitmask of schema verified databases */
   11948   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
   11949   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
   11950   int regRoot;         /* Register holding root page number for new objects */
   11951   int nMaxArg;         /* Max args passed to user function by sub-program */
   11952 #ifndef SQLITE_OMIT_SHARED_CACHE
   11953   int nTableLock;        /* Number of locks in aTableLock */
   11954   TableLock *aTableLock; /* Required table locks for shared-cache mode */
   11955 #endif
   11956   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
   11957 
   11958   /* Information used while coding trigger programs. */
   11959   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
   11960   Table *pTriggerTab;  /* Table triggers are being coded for */
   11961   int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
   11962   int addrSkipPK;      /* Address of instruction to skip PRIMARY KEY index */
   11963   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
   11964   u32 oldmask;         /* Mask of old.* columns referenced */
   11965   u32 newmask;         /* Mask of new.* columns referenced */
   11966   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
   11967   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
   11968   u8 disableTriggers;  /* True to disable triggers */
   11969 
   11970   /************************************************************************
   11971   ** Above is constant between recursions.  Below is reset before and after
   11972   ** each recursion.  The boundary between these two regions is determined
   11973   ** using offsetof(Parse,nVar) so the nVar field must be the first field
   11974   ** in the recursive region.
   11975   ************************************************************************/
   11976 
   11977   int nVar;                 /* Number of '?' variables seen in the SQL so far */
   11978   int nzVar;                /* Number of available slots in azVar[] */
   11979   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
   11980   u8 bFreeWith;             /* True if pWith should be freed with parser */
   11981   u8 explain;               /* True if the EXPLAIN flag is found on the query */
   11982 #ifndef SQLITE_OMIT_VIRTUALTABLE
   11983   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
   11984   int nVtabLock;            /* Number of virtual tables to lock */
   11985 #endif
   11986   int nAlias;               /* Number of aliased result set columns */
   11987   int nHeight;              /* Expression tree height of current sub-select */
   11988 #ifndef SQLITE_OMIT_EXPLAIN
   11989   int iSelectId;            /* ID of current select for EXPLAIN output */
   11990   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
   11991 #endif
   11992   char **azVar;             /* Pointers to names of parameters */
   11993   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
   11994   const char *zTail;        /* All SQL text past the last semicolon parsed */
   11995   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
   11996   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
   11997   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
   11998   Token sNameToken;         /* Token with unqualified schema object name */
   11999   Token sLastToken;         /* The last token parsed */
   12000 #ifndef SQLITE_OMIT_VIRTUALTABLE
   12001   Token sArg;               /* Complete text of a module argument */
   12002   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
   12003 #endif
   12004   Table *pZombieTab;        /* List of Table objects to delete after code gen */
   12005   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
   12006   With *pWith;              /* Current WITH clause, or NULL */
   12007 };
   12008 
   12009 /*
   12010 ** Return true if currently inside an sqlite3_declare_vtab() call.
   12011 */
   12012 #ifdef SQLITE_OMIT_VIRTUALTABLE
   12013   #define IN_DECLARE_VTAB 0
   12014 #else
   12015   #define IN_DECLARE_VTAB (pParse->declareVtab)
   12016 #endif
   12017 
   12018 /*
   12019 ** An instance of the following structure can be declared on a stack and used
   12020 ** to save the Parse.zAuthContext value so that it can be restored later.
   12021 */
   12022 struct AuthContext {
   12023   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
   12024   Parse *pParse;              /* The Parse structure */
   12025 };
   12026 
   12027 /*
   12028 ** Bitfield flags for P5 value in various opcodes.
   12029 */
   12030 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
   12031 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
   12032 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
   12033 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
   12034 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
   12035 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
   12036 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
   12037 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
   12038 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
   12039 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
   12040 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
   12041 
   12042 /*
   12043  * Each trigger present in the database schema is stored as an instance of
   12044  * struct Trigger.
   12045  *
   12046  * Pointers to instances of struct Trigger are stored in two ways.
   12047  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
   12048  *    database). This allows Trigger structures to be retrieved by name.
   12049  * 2. All triggers associated with a single table form a linked list, using the
   12050  *    pNext member of struct Trigger. A pointer to the first element of the
   12051  *    linked list is stored as the "pTrigger" member of the associated
   12052  *    struct Table.
   12053  *
   12054  * The "step_list" member points to the first element of a linked list
   12055  * containing the SQL statements specified as the trigger program.
   12056  */
   12057 struct Trigger {
   12058   char *zName;            /* The name of the trigger                        */
   12059   char *table;            /* The table or view to which the trigger applies */
   12060   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
   12061   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   12062   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
   12063   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
   12064                              the <column-list> is stored here */
   12065   Schema *pSchema;        /* Schema containing the trigger */
   12066   Schema *pTabSchema;     /* Schema containing the table */
   12067   TriggerStep *step_list; /* Link list of trigger program steps             */
   12068   Trigger *pNext;         /* Next trigger associated with the table */
   12069 };
   12070 
   12071 /*
   12072 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
   12073 ** determine which.
   12074 **
   12075 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
   12076 ** In that cases, the constants below can be ORed together.
   12077 */
   12078 #define TRIGGER_BEFORE  1
   12079 #define TRIGGER_AFTER   2
   12080 
   12081 /*
   12082  * An instance of struct TriggerStep is used to store a single SQL statement
   12083  * that is a part of a trigger-program.
   12084  *
   12085  * Instances of struct TriggerStep are stored in a singly linked list (linked
   12086  * using the "pNext" member) referenced by the "step_list" member of the
   12087  * associated struct Trigger instance. The first element of the linked list is
   12088  * the first step of the trigger-program.
   12089  *
   12090  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
   12091  * "SELECT" statement. The meanings of the other members is determined by the
   12092  * value of "op" as follows:
   12093  *
   12094  * (op == TK_INSERT)
   12095  * orconf    -> stores the ON CONFLICT algorithm
   12096  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
   12097  *              this stores a pointer to the SELECT statement. Otherwise NULL.
   12098  * target    -> A token holding the quoted name of the table to insert into.
   12099  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
   12100  *              this stores values to be inserted. Otherwise NULL.
   12101  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
   12102  *              statement, then this stores the column-names to be
   12103  *              inserted into.
   12104  *
   12105  * (op == TK_DELETE)
   12106  * target    -> A token holding the quoted name of the table to delete from.
   12107  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
   12108  *              Otherwise NULL.
   12109  *
   12110  * (op == TK_UPDATE)
   12111  * target    -> A token holding the quoted name of the table to update rows of.
   12112  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
   12113  *              Otherwise NULL.
   12114  * pExprList -> A list of the columns to update and the expressions to update
   12115  *              them to. See sqlite3Update() documentation of "pChanges"
   12116  *              argument.
   12117  *
   12118  */
   12119 struct TriggerStep {
   12120   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
   12121   u8 orconf;           /* OE_Rollback etc. */
   12122   Trigger *pTrig;      /* The trigger that this step is a part of */
   12123   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
   12124   Token target;        /* Target table for DELETE, UPDATE, INSERT */
   12125   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
   12126   ExprList *pExprList; /* SET clause for UPDATE. */
   12127   IdList *pIdList;     /* Column names for INSERT */
   12128   TriggerStep *pNext;  /* Next in the link-list */
   12129   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
   12130 };
   12131 
   12132 /*
   12133 ** The following structure contains information used by the sqliteFix...
   12134 ** routines as they walk the parse tree to make database references
   12135 ** explicit.
   12136 */
   12137 typedef struct DbFixer DbFixer;
   12138 struct DbFixer {
   12139   Parse *pParse;      /* The parsing context.  Error messages written here */
   12140   Schema *pSchema;    /* Fix items to this schema */
   12141   int bVarOnly;       /* Check for variable references only */
   12142   const char *zDb;    /* Make sure all objects are contained in this database */
   12143   const char *zType;  /* Type of the container - used for error messages */
   12144   const Token *pName; /* Name of the container - used for error messages */
   12145 };
   12146 
   12147 /*
   12148 ** An objected used to accumulate the text of a string where we
   12149 ** do not necessarily know how big the string will be in the end.
   12150 */
   12151 struct StrAccum {
   12152   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
   12153   char *zBase;         /* A base allocation.  Not from malloc. */
   12154   char *zText;         /* The string collected so far */
   12155   int  nChar;          /* Length of the string so far */
   12156   int  nAlloc;         /* Amount of space allocated in zText */
   12157   int  mxAlloc;        /* Maximum allowed string length */
   12158   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
   12159   u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
   12160 };
   12161 #define STRACCUM_NOMEM   1
   12162 #define STRACCUM_TOOBIG  2
   12163 
   12164 /*
   12165 ** A pointer to this structure is used to communicate information
   12166 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
   12167 */
   12168 typedef struct {
   12169   sqlite3 *db;        /* The database being initialized */
   12170   char **pzErrMsg;    /* Error message stored here */
   12171   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
   12172   int rc;             /* Result code stored here */
   12173 } InitData;
   12174 
   12175 /*
   12176 ** Structure containing global configuration data for the SQLite library.
   12177 **
   12178 ** This structure also contains some state information.
   12179 */
   12180 struct Sqlite3Config {
   12181   int bMemstat;                     /* True to enable memory status */
   12182   int bCoreMutex;                   /* True to enable core mutexing */
   12183   int bFullMutex;                   /* True to enable full mutexing */
   12184   int bOpenUri;                     /* True to interpret filenames as URIs */
   12185   int bUseCis;                      /* Use covering indices for full-scans */
   12186   int mxStrlen;                     /* Maximum string length */
   12187   int neverCorrupt;                 /* Database is always well-formed */
   12188   int szLookaside;                  /* Default lookaside buffer size */
   12189   int nLookaside;                   /* Default lookaside buffer count */
   12190   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
   12191   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
   12192   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
   12193   void *pHeap;                      /* Heap storage space */
   12194   int nHeap;                        /* Size of pHeap[] */
   12195   int mnReq, mxReq;                 /* Min and max heap requests sizes */
   12196   sqlite3_int64 szMmap;             /* mmap() space per open file */
   12197   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
   12198   void *pScratch;                   /* Scratch memory */
   12199   int szScratch;                    /* Size of each scratch buffer */
   12200   int nScratch;                     /* Number of scratch buffers */
   12201   void *pPage;                      /* Page cache memory */
   12202   int szPage;                       /* Size of each page in pPage[] */
   12203   int nPage;                        /* Number of pages in pPage[] */
   12204   int mxParserStack;                /* maximum depth of the parser stack */
   12205   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
   12206   /* The above might be initialized to non-zero.  The following need to always
   12207   ** initially be zero, however. */
   12208   int isInit;                       /* True after initialization has finished */
   12209   int inProgress;                   /* True while initialization in progress */
   12210   int isMutexInit;                  /* True after mutexes are initialized */
   12211   int isMallocInit;                 /* True after malloc is initialized */
   12212   int isPCacheInit;                 /* True after malloc is initialized */
   12213   int nRefInitMutex;                /* Number of users of pInitMutex */
   12214   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
   12215   void (*xLog)(void*,int,const char*); /* Function for logging */
   12216   void *pLogArg;                       /* First argument to xLog() */
   12217 #ifdef SQLITE_ENABLE_SQLLOG
   12218   void(*xSqllog)(void*,sqlite3*,const char*, int);
   12219   void *pSqllogArg;
   12220 #endif
   12221 #ifdef SQLITE_VDBE_COVERAGE
   12222   /* The following callback (if not NULL) is invoked on every VDBE branch
   12223   ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
   12224   */
   12225   void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
   12226   void *pVdbeBranchArg;                                     /* 1st argument */
   12227 #endif
   12228 #ifndef SQLITE_OMIT_BUILTIN_TEST
   12229   int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
   12230 #endif
   12231   int bLocaltimeFault;              /* True to fail localtime() calls */
   12232 };
   12233 
   12234 /*
   12235 ** This macro is used inside of assert() statements to indicate that
   12236 ** the assert is only valid on a well-formed database.  Instead of:
   12237 **
   12238 **     assert( X );
   12239 **
   12240 ** One writes:
   12241 **
   12242 **     assert( X || CORRUPT_DB );
   12243 **
   12244 ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
   12245 ** that the database is definitely corrupt, only that it might be corrupt.
   12246 ** For most test cases, CORRUPT_DB is set to false using a special
   12247 ** sqlite3_test_control().  This enables assert() statements to prove
   12248 ** things that are always true for well-formed databases.
   12249 */
   12250 #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
   12251 
   12252 /*
   12253 ** Context pointer passed down through the tree-walk.
   12254 */
   12255 struct Walker {
   12256   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
   12257   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
   12258   void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
   12259   Parse *pParse;                            /* Parser context.  */
   12260   int walkerDepth;                          /* Number of subqueries */
   12261   union {                                   /* Extra data for callback */
   12262     NameContext *pNC;                          /* Naming context */
   12263     int i;                                     /* Integer value */
   12264     SrcList *pSrcList;                         /* FROM clause */
   12265     struct SrcCount *pSrcCount;                /* Counting column references */
   12266   } u;
   12267 };
   12268 
   12269 /* Forward declarations */
   12270 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
   12271 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
   12272 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
   12273 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
   12274 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
   12275 
   12276 /*
   12277 ** Return code from the parse-tree walking primitives and their
   12278 ** callbacks.
   12279 */
   12280 #define WRC_Continue    0   /* Continue down into children */
   12281 #define WRC_Prune       1   /* Omit children but continue walking siblings */
   12282 #define WRC_Abort       2   /* Abandon the tree walk */
   12283 
   12284 /*
   12285 ** An instance of this structure represents a set of one or more CTEs
   12286 ** (common table expressions) created by a single WITH clause.
   12287 */
   12288 struct With {
   12289   int nCte;                       /* Number of CTEs in the WITH clause */
   12290   With *pOuter;                   /* Containing WITH clause, or NULL */
   12291   struct Cte {                    /* For each CTE in the WITH clause.... */
   12292     char *zName;                    /* Name of this CTE */
   12293     ExprList *pCols;                /* List of explicit column names, or NULL */
   12294     Select *pSelect;                /* The definition of this CTE */
   12295     const char *zErr;               /* Error message for circular references */
   12296   } a[1];
   12297 };
   12298 
   12299 /*
   12300 ** Assuming zIn points to the first byte of a UTF-8 character,
   12301 ** advance zIn to point to the first byte of the next UTF-8 character.
   12302 */
   12303 #define SQLITE_SKIP_UTF8(zIn) {                        \
   12304   if( (*(zIn++))>=0xc0 ){                              \
   12305     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
   12306   }                                                    \
   12307 }
   12308 
   12309 /*
   12310 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
   12311 ** the same name but without the _BKPT suffix.  These macros invoke
   12312 ** routines that report the line-number on which the error originated
   12313 ** using sqlite3_log().  The routines also provide a convenient place
   12314 ** to set a debugger breakpoint.
   12315 */
   12316 SQLITE_PRIVATE int sqlite3CorruptError(int);
   12317 SQLITE_PRIVATE int sqlite3MisuseError(int);
   12318 SQLITE_PRIVATE int sqlite3CantopenError(int);
   12319 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
   12320 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
   12321 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
   12322 
   12323 
   12324 /*
   12325 ** FTS4 is really an extension for FTS3.  It is enabled using the
   12326 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
   12327 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
   12328 */
   12329 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   12330 # define SQLITE_ENABLE_FTS3
   12331 #endif
   12332 
   12333 /*
   12334 ** The ctype.h header is needed for non-ASCII systems.  It is also
   12335 ** needed by FTS3 when FTS3 is included in the amalgamation.
   12336 */
   12337 #if !defined(SQLITE_ASCII) || \
   12338     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
   12339 # include <ctype.h>
   12340 #endif
   12341 
   12342 /*
   12343 ** The following macros mimic the standard library functions toupper(),
   12344 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
   12345 ** sqlite versions only work for ASCII characters, regardless of locale.
   12346 */
   12347 #ifdef SQLITE_ASCII
   12348 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
   12349 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
   12350 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
   12351 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
   12352 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
   12353 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
   12354 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
   12355 #else
   12356 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
   12357 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
   12358 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
   12359 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
   12360 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
   12361 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
   12362 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
   12363 #endif
   12364 
   12365 /*
   12366 ** Internal function prototypes
   12367 */
   12368 #define sqlite3StrICmp sqlite3_stricmp
   12369 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
   12370 #define sqlite3StrNICmp sqlite3_strnicmp
   12371 
   12372 SQLITE_PRIVATE int sqlite3MallocInit(void);
   12373 SQLITE_PRIVATE void sqlite3MallocEnd(void);
   12374 SQLITE_PRIVATE void *sqlite3Malloc(int);
   12375 SQLITE_PRIVATE void *sqlite3MallocZero(int);
   12376 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
   12377 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
   12378 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
   12379 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
   12380 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
   12381 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
   12382 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
   12383 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
   12384 SQLITE_PRIVATE int sqlite3MallocSize(void*);
   12385 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
   12386 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
   12387 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
   12388 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
   12389 SQLITE_PRIVATE void sqlite3PageFree(void*);
   12390 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
   12391 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
   12392 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
   12393 
   12394 /*
   12395 ** On systems with ample stack space and that support alloca(), make
   12396 ** use of alloca() to obtain space for large automatic objects.  By default,
   12397 ** obtain space from malloc().
   12398 **
   12399 ** The alloca() routine never returns NULL.  This will cause code paths
   12400 ** that deal with sqlite3StackAlloc() failures to be unreachable.
   12401 */
   12402 #ifdef SQLITE_USE_ALLOCA
   12403 # define sqlite3StackAllocRaw(D,N)   alloca(N)
   12404 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
   12405 # define sqlite3StackFree(D,P)
   12406 #else
   12407 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
   12408 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
   12409 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
   12410 #endif
   12411 
   12412 #ifdef SQLITE_ENABLE_MEMSYS3
   12413 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
   12414 #endif
   12415 #ifdef SQLITE_ENABLE_MEMSYS5
   12416 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
   12417 #endif
   12418 
   12419 
   12420 #ifndef SQLITE_MUTEX_OMIT
   12421 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
   12422 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
   12423 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
   12424 SQLITE_PRIVATE   int sqlite3MutexInit(void);
   12425 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
   12426 #endif
   12427 
   12428 SQLITE_PRIVATE int sqlite3StatusValue(int);
   12429 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
   12430 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
   12431 
   12432 #ifndef SQLITE_OMIT_FLOATING_POINT
   12433 SQLITE_PRIVATE   int sqlite3IsNaN(double);
   12434 #else
   12435 # define sqlite3IsNaN(X)  0
   12436 #endif
   12437 
   12438 /*
   12439 ** An instance of the following structure holds information about SQL
   12440 ** functions arguments that are the parameters to the printf() function.
   12441 */
   12442 struct PrintfArguments {
   12443   int nArg;                /* Total number of arguments */
   12444   int nUsed;               /* Number of arguments used so far */
   12445   sqlite3_value **apArg;   /* The argument values */
   12446 };
   12447 
   12448 #define SQLITE_PRINTF_INTERNAL 0x01
   12449 #define SQLITE_PRINTF_SQLFUNC  0x02
   12450 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
   12451 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
   12452 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
   12453 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
   12454 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
   12455 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   12456 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
   12457 #endif
   12458 #if defined(SQLITE_TEST)
   12459 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
   12460 #endif
   12461 
   12462 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
   12463 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   12464 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
   12465 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
   12466 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
   12467 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
   12468 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
   12469 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
   12470 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
   12471 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
   12472 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
   12473 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
   12474 #else
   12475 # define sqlite3ExplainBegin(X)
   12476 # define sqlite3ExplainSelect(A,B)
   12477 # define sqlite3ExplainExpr(A,B)
   12478 # define sqlite3ExplainExprList(A,B)
   12479 # define sqlite3ExplainFinish(X)
   12480 # define sqlite3VdbeExplanation(X) 0
   12481 #endif
   12482 
   12483 
   12484 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
   12485 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
   12486 SQLITE_PRIVATE int sqlite3Dequote(char*);
   12487 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
   12488 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
   12489 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
   12490 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
   12491 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
   12492 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
   12493 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
   12494 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
   12495 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
   12496 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
   12497 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
   12498 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
   12499 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
   12500 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
   12501 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
   12502 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
   12503 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
   12504 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
   12505 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
   12506 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
   12507 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
   12508 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
   12509 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
   12510 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
   12511 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
   12512 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
   12513 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
   12514 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
   12515 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
   12516 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
   12517 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
   12518 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
   12519 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
   12520 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
   12521 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
   12522 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
   12523 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
   12524 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
   12525 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
   12526 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
   12527 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
   12528 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
   12529                     sqlite3_vfs**,char**,char **);
   12530 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
   12531 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
   12532 
   12533 #ifdef SQLITE_OMIT_BUILTIN_TEST
   12534 # define sqlite3FaultSim(X) SQLITE_OK
   12535 #else
   12536 SQLITE_PRIVATE   int sqlite3FaultSim(int);
   12537 #endif
   12538 
   12539 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
   12540 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
   12541 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
   12542 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
   12543 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
   12544 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
   12545 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
   12546 
   12547 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
   12548 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
   12549 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
   12550 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
   12551 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
   12552 
   12553 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
   12554 
   12555 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   12556 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
   12557 #else
   12558 # define sqlite3ViewGetColumnNames(A,B) 0
   12559 #endif
   12560 
   12561 #if SQLITE_MAX_ATTACHED>30
   12562 SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
   12563 #endif
   12564 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
   12565 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
   12566 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
   12567 #ifndef SQLITE_OMIT_AUTOINCREMENT
   12568 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
   12569 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
   12570 #else
   12571 # define sqlite3AutoincrementBegin(X)
   12572 # define sqlite3AutoincrementEnd(X)
   12573 #endif
   12574 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
   12575 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
   12576 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
   12577 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
   12578 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
   12579 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
   12580 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
   12581                                       Token*, Select*, Expr*, IdList*);
   12582 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
   12583 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
   12584 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
   12585 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
   12586 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
   12587 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
   12588 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
   12589 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
   12590                           Expr*, int, int);
   12591 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
   12592 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
   12593 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
   12594                          Expr*,ExprList*,u16,Expr*,Expr*);
   12595 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
   12596 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
   12597 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
   12598 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
   12599 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   12600 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
   12601 #endif
   12602 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
   12603 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
   12604 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
   12605 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
   12606 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
   12607 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
   12608 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
   12609 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
   12610 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
   12611 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
   12612 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
   12613 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
   12614 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
   12615 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
   12616 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
   12617 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
   12618 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
   12619 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
   12620 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
   12621 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
   12622 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
   12623 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
   12624 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
   12625 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
   12626 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
   12627 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
   12628 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
   12629 #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
   12630 #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
   12631 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
   12632 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
   12633 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
   12634 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
   12635 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
   12636 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
   12637 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
   12638 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
   12639 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
   12640 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
   12641 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
   12642 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
   12643 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
   12644 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
   12645 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
   12646 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
   12647 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
   12648 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
   12649 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
   12650 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
   12651 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
   12652 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
   12653 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
   12654 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
   12655 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
   12656 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
   12657 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
   12658 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
   12659 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
   12660 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
   12661 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
   12662 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
   12663 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
   12664 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
   12665 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
   12666 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
   12667 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
   12668 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
   12669 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
   12670 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
   12671 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
   12672                                      u8,u8,int,int*);
   12673 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
   12674 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
   12675 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
   12676 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
   12677 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
   12678 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
   12679 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
   12680 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
   12681 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
   12682 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
   12683 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
   12684 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
   12685 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
   12686 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
   12687 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
   12688 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
   12689 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
   12690 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
   12691 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
   12692 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
   12693 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
   12694 
   12695 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   12696 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
   12697 #endif
   12698 
   12699 #ifndef SQLITE_OMIT_TRIGGER
   12700 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
   12701                            Expr*,int, int);
   12702 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
   12703 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
   12704 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
   12705 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
   12706 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
   12707 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
   12708                             int, int, int);
   12709 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
   12710   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
   12711 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
   12712 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
   12713 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
   12714                                         Select*,u8);
   12715 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
   12716 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
   12717 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
   12718 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
   12719 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
   12720 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
   12721 #else
   12722 # define sqlite3TriggersExist(B,C,D,E,F) 0
   12723 # define sqlite3DeleteTrigger(A,B)
   12724 # define sqlite3DropTriggerPtr(A,B)
   12725 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
   12726 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
   12727 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
   12728 # define sqlite3TriggerList(X, Y) 0
   12729 # define sqlite3ParseToplevel(p) p
   12730 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
   12731 #endif
   12732 
   12733 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
   12734 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
   12735 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
   12736 #ifndef SQLITE_OMIT_AUTHORIZATION
   12737 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
   12738 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
   12739 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
   12740 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
   12741 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
   12742 #else
   12743 # define sqlite3AuthRead(a,b,c,d)
   12744 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
   12745 # define sqlite3AuthContextPush(a,b,c)
   12746 # define sqlite3AuthContextPop(a)  ((void)(a))
   12747 #endif
   12748 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
   12749 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
   12750 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
   12751 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
   12752 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
   12753 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
   12754 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
   12755 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
   12756 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
   12757 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
   12758 SQLITE_PRIVATE int sqlite3Atoi(const char*);
   12759 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
   12760 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
   12761 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
   12762 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
   12763 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
   12764 #ifndef SQLITE_OMIT_VIRTUALTABLE
   12765 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
   12766 #endif
   12767 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
   12768 
   12769 /*
   12770 ** Routines to read and write variable-length integers.  These used to
   12771 ** be defined locally, but now we use the varint routines in the util.c
   12772 ** file.  Code should use the MACRO forms below, as the Varint32 versions
   12773 ** are coded to assume the single byte case is already handled (which
   12774 ** the MACRO form does).
   12775 */
   12776 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
   12777 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
   12778 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
   12779 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
   12780 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
   12781 
   12782 /*
   12783 ** The header of a record consists of a sequence variable-length integers.
   12784 ** These integers are almost always small and are encoded as a single byte.
   12785 ** The following macros take advantage this fact to provide a fast encode
   12786 ** and decode of the integers in a record header.  It is faster for the common
   12787 ** case where the integer is a single byte.  It is a little slower when the
   12788 ** integer is two or more bytes.  But overall it is faster.
   12789 **
   12790 ** The following expressions are equivalent:
   12791 **
   12792 **     x = sqlite3GetVarint32( A, &B );
   12793 **     x = sqlite3PutVarint32( A, B );
   12794 **
   12795 **     x = getVarint32( A, B );
   12796 **     x = putVarint32( A, B );
   12797 **
   12798 */
   12799 #define getVarint32(A,B)  \
   12800   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
   12801 #define putVarint32(A,B)  \
   12802   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
   12803   sqlite3PutVarint32((A),(B)))
   12804 #define getVarint    sqlite3GetVarint
   12805 #define putVarint    sqlite3PutVarint
   12806 
   12807 
   12808 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
   12809 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
   12810 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
   12811 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
   12812 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
   12813 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
   12814 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
   12815 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
   12816 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
   12817 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
   12818 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
   12819 
   12820 #if defined(SQLITE_TEST)
   12821 SQLITE_PRIVATE const char *sqlite3ErrName(int);
   12822 #endif
   12823 
   12824 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
   12825 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
   12826 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
   12827 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
   12828 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
   12829 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*);
   12830 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
   12831 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
   12832 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
   12833 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
   12834 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
   12835 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
   12836 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
   12837 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
   12838 SQLITE_PRIVATE int sqlite3AbsInt32(int);
   12839 #ifdef SQLITE_ENABLE_8_3_NAMES
   12840 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
   12841 #else
   12842 # define sqlite3FileSuffix3(X,Y)
   12843 #endif
   12844 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
   12845 
   12846 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
   12847 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
   12848 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
   12849                         void(*)(void*));
   12850 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
   12851 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
   12852 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
   12853 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
   12854 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
   12855 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
   12856 #ifndef SQLITE_AMALGAMATION
   12857 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
   12858 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
   12859 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
   12860 SQLITE_PRIVATE const Token sqlite3IntTokens[];
   12861 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
   12862 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   12863 #ifndef SQLITE_OMIT_WSD
   12864 SQLITE_PRIVATE int sqlite3PendingByte;
   12865 #endif
   12866 #endif
   12867 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
   12868 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
   12869 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
   12870 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
   12871 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
   12872 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
   12873 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
   12874 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
   12875 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
   12876 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
   12877 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
   12878 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
   12879 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
   12880 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
   12881 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
   12882 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
   12883 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
   12884 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
   12885 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
   12886 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
   12887 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
   12888 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
   12889 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
   12890 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
   12891 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
   12892 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
   12893 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
   12894 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
   12895 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
   12896 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
   12897 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
   12898 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
   12899 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
   12900 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
   12901 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
   12902 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
   12903 #ifdef SQLITE_DEBUG
   12904 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
   12905 #endif
   12906 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
   12907   void (*)(sqlite3_context*,int,sqlite3_value **),
   12908   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
   12909   FuncDestructor *pDestructor
   12910 );
   12911 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
   12912 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
   12913 
   12914 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
   12915 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
   12916 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
   12917 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
   12918 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
   12919 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
   12920 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
   12921 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
   12922 
   12923 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
   12924 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
   12925 
   12926 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   12927 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
   12928 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
   12929 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
   12930 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
   12931 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
   12932 #endif
   12933 
   12934 /*
   12935 ** The interface to the LEMON-generated parser
   12936 */
   12937 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
   12938 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
   12939 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
   12940 #ifdef YYTRACKMAXSTACKDEPTH
   12941 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
   12942 #endif
   12943 
   12944 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
   12945 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   12946 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
   12947 #else
   12948 # define sqlite3CloseExtensions(X)
   12949 #endif
   12950 
   12951 #ifndef SQLITE_OMIT_SHARED_CACHE
   12952 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
   12953 #else
   12954   #define sqlite3TableLock(v,w,x,y,z)
   12955 #endif
   12956 
   12957 #ifdef SQLITE_TEST
   12958 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
   12959 #endif
   12960 
   12961 #ifdef SQLITE_OMIT_VIRTUALTABLE
   12962 #  define sqlite3VtabClear(Y)
   12963 #  define sqlite3VtabSync(X,Y) SQLITE_OK
   12964 #  define sqlite3VtabRollback(X)
   12965 #  define sqlite3VtabCommit(X)
   12966 #  define sqlite3VtabInSync(db) 0
   12967 #  define sqlite3VtabLock(X)
   12968 #  define sqlite3VtabUnlock(X)
   12969 #  define sqlite3VtabUnlockList(X)
   12970 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
   12971 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
   12972 #else
   12973 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
   12974 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
   12975 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
   12976 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
   12977 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
   12978 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
   12979 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
   12980 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
   12981 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
   12982 SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
   12983 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
   12984 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
   12985 #endif
   12986 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
   12987 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
   12988 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
   12989 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
   12990 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
   12991 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
   12992 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
   12993 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
   12994 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
   12995 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
   12996 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
   12997 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
   12998 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
   12999 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
   13000 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
   13001 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
   13002 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
   13003 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
   13004 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
   13005 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
   13006 #ifndef SQLITE_OMIT_WAL
   13007 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
   13008 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
   13009 #endif
   13010 #ifndef SQLITE_OMIT_CTE
   13011 SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
   13012 SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
   13013 SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
   13014 #else
   13015 #define sqlite3WithPush(x,y,z)
   13016 #define sqlite3WithDelete(x,y)
   13017 #endif
   13018 
   13019 /* Declarations for functions in fkey.c. All of these are replaced by
   13020 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
   13021 ** key functionality is available. If OMIT_TRIGGER is defined but
   13022 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
   13023 ** this case foreign keys are parsed, but no other functionality is
   13024 ** provided (enforcement of FK constraints requires the triggers sub-system).
   13025 */
   13026 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   13027 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
   13028 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
   13029 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
   13030 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
   13031 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
   13032 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
   13033 #else
   13034   #define sqlite3FkActions(a,b,c,d,e,f)
   13035   #define sqlite3FkCheck(a,b,c,d,e,f)
   13036   #define sqlite3FkDropTable(a,b,c)
   13037   #define sqlite3FkOldmask(a,b)         0
   13038   #define sqlite3FkRequired(a,b,c,d)    0
   13039 #endif
   13040 #ifndef SQLITE_OMIT_FOREIGN_KEY
   13041 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
   13042 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
   13043 #else
   13044   #define sqlite3FkDelete(a,b)
   13045   #define sqlite3FkLocateIndex(a,b,c,d,e)
   13046 #endif
   13047 
   13048 
   13049 /*
   13050 ** Available fault injectors.  Should be numbered beginning with 0.
   13051 */
   13052 #define SQLITE_FAULTINJECTOR_MALLOC     0
   13053 #define SQLITE_FAULTINJECTOR_COUNT      1
   13054 
   13055 /*
   13056 ** The interface to the code in fault.c used for identifying "benign"
   13057 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
   13058 ** is not defined.
   13059 */
   13060 #ifndef SQLITE_OMIT_BUILTIN_TEST
   13061 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
   13062 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
   13063 #else
   13064   #define sqlite3BeginBenignMalloc()
   13065   #define sqlite3EndBenignMalloc()
   13066 #endif
   13067 
   13068 /*
   13069 ** Allowed return values from sqlite3FindInIndex()
   13070 */
   13071 #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
   13072 #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
   13073 #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
   13074 #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
   13075 #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
   13076 /*
   13077 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
   13078 */
   13079 #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
   13080 #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
   13081 #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
   13082 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
   13083 
   13084 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   13085 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
   13086 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
   13087 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
   13088 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
   13089 #else
   13090   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
   13091   #define sqlite3JournalExists(p) 1
   13092 #endif
   13093 
   13094 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
   13095 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
   13096 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
   13097 
   13098 #if SQLITE_MAX_EXPR_DEPTH>0
   13099 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
   13100 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
   13101 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
   13102 #else
   13103   #define sqlite3ExprSetHeight(x,y)
   13104   #define sqlite3SelectExprHeight(x) 0
   13105   #define sqlite3ExprCheckHeight(x,y)
   13106 #endif
   13107 
   13108 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
   13109 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
   13110 
   13111 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   13112 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
   13113 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
   13114 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
   13115 #else
   13116   #define sqlite3ConnectionBlocked(x,y)
   13117   #define sqlite3ConnectionUnlocked(x)
   13118   #define sqlite3ConnectionClosed(x)
   13119 #endif
   13120 
   13121 #ifdef SQLITE_DEBUG
   13122 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
   13123 #endif
   13124 
   13125 /*
   13126 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
   13127 ** sqlite3IoTrace is a pointer to a printf-like routine used to
   13128 ** print I/O tracing messages.
   13129 */
   13130 #ifdef SQLITE_ENABLE_IOTRACE
   13131 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
   13132 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
   13133 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
   13134 #else
   13135 # define IOTRACE(A)
   13136 # define sqlite3VdbeIOTraceSql(X)
   13137 #endif
   13138 
   13139 /*
   13140 ** These routines are available for the mem2.c debugging memory allocator
   13141 ** only.  They are used to verify that different "types" of memory
   13142 ** allocations are properly tracked by the system.
   13143 **
   13144 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
   13145 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
   13146 ** a single bit set.
   13147 **
   13148 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
   13149 ** argument match the type set by the previous sqlite3MemdebugSetType().
   13150 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
   13151 **
   13152 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
   13153 ** argument match the type set by the previous sqlite3MemdebugSetType().
   13154 **
   13155 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
   13156 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
   13157 ** it might have been allocated by lookaside, except the allocation was
   13158 ** too large or lookaside was already full.  It is important to verify
   13159 ** that allocations that might have been satisfied by lookaside are not
   13160 ** passed back to non-lookaside free() routines.  Asserts such as the
   13161 ** example above are placed on the non-lookaside free() routines to verify
   13162 ** this constraint.
   13163 **
   13164 ** All of this is no-op for a production build.  It only comes into
   13165 ** play when the SQLITE_MEMDEBUG compile-time option is used.
   13166 */
   13167 #ifdef SQLITE_MEMDEBUG
   13168 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
   13169 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
   13170 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
   13171 #else
   13172 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
   13173 # define sqlite3MemdebugHasType(X,Y)  1
   13174 # define sqlite3MemdebugNoType(X,Y)   1
   13175 #endif
   13176 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
   13177 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
   13178 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
   13179 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
   13180 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
   13181 
   13182 #endif /* _SQLITEINT_H_ */
   13183 
   13184 /************** End of sqliteInt.h *******************************************/
   13185 /************** Begin file global.c ******************************************/
   13186 /*
   13187 ** 2008 June 13
   13188 **
   13189 ** The author disclaims copyright to this source code.  In place of
   13190 ** a legal notice, here is a blessing:
   13191 **
   13192 **    May you do good and not evil.
   13193 **    May you find forgiveness for yourself and forgive others.
   13194 **    May you share freely, never taking more than you give.
   13195 **
   13196 *************************************************************************
   13197 **
   13198 ** This file contains definitions of global variables and contants.
   13199 */
   13200 
   13201 /* An array to map all upper-case characters into their corresponding
   13202 ** lower-case character.
   13203 **
   13204 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
   13205 ** handle case conversions for the UTF character set since the tables
   13206 ** involved are nearly as big or bigger than SQLite itself.
   13207 */
   13208 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
   13209 #ifdef SQLITE_ASCII
   13210       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
   13211      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
   13212      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
   13213      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
   13214     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
   13215     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
   13216     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
   13217     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
   13218     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
   13219     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
   13220     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
   13221     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
   13222     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
   13223     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
   13224     252,253,254,255
   13225 #endif
   13226 #ifdef SQLITE_EBCDIC
   13227       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
   13228      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
   13229      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
   13230      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
   13231      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
   13232      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
   13233      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
   13234     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
   13235     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
   13236     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
   13237     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
   13238     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
   13239     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
   13240     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
   13241     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
   13242     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
   13243 #endif
   13244 };
   13245 
   13246 /*
   13247 ** The following 256 byte lookup table is used to support SQLites built-in
   13248 ** equivalents to the following standard library functions:
   13249 **
   13250 **   isspace()                        0x01
   13251 **   isalpha()                        0x02
   13252 **   isdigit()                        0x04
   13253 **   isalnum()                        0x06
   13254 **   isxdigit()                       0x08
   13255 **   toupper()                        0x20
   13256 **   SQLite identifier character      0x40
   13257 **
   13258 ** Bit 0x20 is set if the mapped character requires translation to upper
   13259 ** case. i.e. if the character is a lower-case ASCII character.
   13260 ** If x is a lower-case ASCII character, then its upper-case equivalent
   13261 ** is (x - 0x20). Therefore toupper() can be implemented as:
   13262 **
   13263 **   (x & ~(map[x]&0x20))
   13264 **
   13265 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
   13266 ** array. tolower() is used more often than toupper() by SQLite.
   13267 **
   13268 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
   13269 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
   13270 ** non-ASCII UTF character. Hence the test for whether or not a character is
   13271 ** part of an identifier is 0x46.
   13272 **
   13273 ** SQLite's versions are identical to the standard versions assuming a
   13274 ** locale of "C". They are implemented as macros in sqliteInt.h.
   13275 */
   13276 #ifdef SQLITE_ASCII
   13277 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
   13278   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
   13279   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
   13280   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
   13281   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
   13282   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
   13283   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
   13284   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
   13285   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
   13286 
   13287   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
   13288   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
   13289   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
   13290   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
   13291   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
   13292   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
   13293   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
   13294   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
   13295 
   13296   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
   13297   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
   13298   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
   13299   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
   13300   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
   13301   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
   13302   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
   13303   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
   13304 
   13305   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
   13306   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
   13307   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
   13308   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
   13309   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
   13310   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
   13311   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
   13312   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
   13313 };
   13314 #endif
   13315 
   13316 #ifndef SQLITE_USE_URI
   13317 # define  SQLITE_USE_URI 0
   13318 #endif
   13319 
   13320 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
   13321 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
   13322 #endif
   13323 
   13324 /*
   13325 ** The following singleton contains the global configuration for
   13326 ** the SQLite library.
   13327 */
   13328 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   13329    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   13330    1,                         /* bCoreMutex */
   13331    SQLITE_THREADSAFE==1,      /* bFullMutex */
   13332    SQLITE_USE_URI,            /* bOpenUri */
   13333    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
   13334    0x7ffffffe,                /* mxStrlen */
   13335    0,                         /* neverCorrupt */
   13336    128,                       /* szLookaside */
   13337    500,                       /* nLookaside */
   13338    {0,0,0,0,0,0,0,0},         /* m */
   13339    {0,0,0,0,0,0,0,0,0},       /* mutex */
   13340    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
   13341    (void*)0,                  /* pHeap */
   13342    0,                         /* nHeap */
   13343    0, 0,                      /* mnHeap, mxHeap */
   13344    SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
   13345    SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
   13346    (void*)0,                  /* pScratch */
   13347    0,                         /* szScratch */
   13348    0,                         /* nScratch */
   13349    (void*)0,                  /* pPage */
   13350    0,                         /* szPage */
   13351    0,                         /* nPage */
   13352    0,                         /* mxParserStack */
   13353    0,                         /* sharedCacheEnabled */
   13354    /* All the rest should always be initialized to zero */
   13355    0,                         /* isInit */
   13356    0,                         /* inProgress */
   13357    0,                         /* isMutexInit */
   13358    0,                         /* isMallocInit */
   13359    0,                         /* isPCacheInit */
   13360    0,                         /* nRefInitMutex */
   13361    0,                         /* pInitMutex */
   13362    0,                         /* xLog */
   13363    0,                         /* pLogArg */
   13364 #ifdef SQLITE_ENABLE_SQLLOG
   13365    0,                         /* xSqllog */
   13366    0,                         /* pSqllogArg */
   13367 #endif
   13368 #ifdef SQLITE_VDBE_COVERAGE
   13369    0,                         /* xVdbeBranch */
   13370    0,                         /* pVbeBranchArg */
   13371 #endif
   13372 #ifndef SQLITE_OMIT_BUILTIN_TEST
   13373    0,                         /* xTestCallback */
   13374 #endif
   13375    0                          /* bLocaltimeFault */
   13376 };
   13377 
   13378 /*
   13379 ** Hash table for global functions - functions common to all
   13380 ** database connections.  After initialization, this table is
   13381 ** read-only.
   13382 */
   13383 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   13384 
   13385 /*
   13386 ** Constant tokens for values 0 and 1.
   13387 */
   13388 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
   13389    { "0", 1 },
   13390    { "1", 1 }
   13391 };
   13392 
   13393 
   13394 /*
   13395 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
   13396 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
   13397 ** the database page that contains the pending byte.  It never attempts
   13398 ** to read or write that page.  The pending byte page is set assign
   13399 ** for use by the VFS layers as space for managing file locks.
   13400 **
   13401 ** During testing, it is often desirable to move the pending byte to
   13402 ** a different position in the file.  This allows code that has to
   13403 ** deal with the pending byte to run on files that are much smaller
   13404 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
   13405 ** move the pending byte.
   13406 **
   13407 ** IMPORTANT:  Changing the pending byte to any value other than
   13408 ** 0x40000000 results in an incompatible database file format!
   13409 ** Changing the pending byte during operating results in undefined
   13410 ** and dileterious behavior.
   13411 */
   13412 #ifndef SQLITE_OMIT_WSD
   13413 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
   13414 #endif
   13415 
   13416 /*
   13417 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
   13418 ** created by mkopcodeh.awk during compilation.  Data is obtained
   13419 ** from the comments following the "case OP_xxxx:" statements in
   13420 ** the vdbe.c file.
   13421 */
   13422 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
   13423 
   13424 /************** End of global.c **********************************************/
   13425 /************** Begin file ctime.c *******************************************/
   13426 /*
   13427 ** 2010 February 23
   13428 **
   13429 ** The author disclaims copyright to this source code.  In place of
   13430 ** a legal notice, here is a blessing:
   13431 **
   13432 **    May you do good and not evil.
   13433 **    May you find forgiveness for yourself and forgive others.
   13434 **    May you share freely, never taking more than you give.
   13435 **
   13436 *************************************************************************
   13437 **
   13438 ** This file implements routines used to report what compile-time options
   13439 ** SQLite was built with.
   13440 */
   13441 
   13442 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   13443 
   13444 
   13445 /*
   13446 ** An array of names of all compile-time options.  This array should
   13447 ** be sorted A-Z.
   13448 **
   13449 ** This array looks large, but in a typical installation actually uses
   13450 ** only a handful of compile-time options, so most times this array is usually
   13451 ** rather short and uses little memory space.
   13452 */
   13453 static const char * const azCompileOpt[] = {
   13454 
   13455 /* These macros are provided to "stringify" the value of the define
   13456 ** for those options in which the value is meaningful. */
   13457 #define CTIMEOPT_VAL_(opt) #opt
   13458 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
   13459 
   13460 #ifdef SQLITE_32BIT_ROWID
   13461   "32BIT_ROWID",
   13462 #endif
   13463 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   13464   "4_BYTE_ALIGNED_MALLOC",
   13465 #endif
   13466 #ifdef SQLITE_CASE_SENSITIVE_LIKE
   13467   "CASE_SENSITIVE_LIKE",
   13468 #endif
   13469 #ifdef SQLITE_CHECK_PAGES
   13470   "CHECK_PAGES",
   13471 #endif
   13472 #ifdef SQLITE_COVERAGE_TEST
   13473   "COVERAGE_TEST",
   13474 #endif
   13475 #ifdef SQLITE_DEBUG
   13476   "DEBUG",
   13477 #endif
   13478 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   13479   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
   13480 #endif
   13481 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
   13482   "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
   13483 #endif
   13484 #ifdef SQLITE_DISABLE_DIRSYNC
   13485   "DISABLE_DIRSYNC",
   13486 #endif
   13487 #ifdef SQLITE_DISABLE_LFS
   13488   "DISABLE_LFS",
   13489 #endif
   13490 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   13491   "ENABLE_ATOMIC_WRITE",
   13492 #endif
   13493 #ifdef SQLITE_ENABLE_CEROD
   13494   "ENABLE_CEROD",
   13495 #endif
   13496 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   13497   "ENABLE_COLUMN_METADATA",
   13498 #endif
   13499 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   13500   "ENABLE_EXPENSIVE_ASSERT",
   13501 #endif
   13502 #ifdef SQLITE_ENABLE_FTS1
   13503   "ENABLE_FTS1",
   13504 #endif
   13505 #ifdef SQLITE_ENABLE_FTS2
   13506   "ENABLE_FTS2",
   13507 #endif
   13508 #ifdef SQLITE_ENABLE_FTS3
   13509   "ENABLE_FTS3",
   13510 #endif
   13511 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   13512   "ENABLE_FTS3_PARENTHESIS",
   13513 #endif
   13514 #ifdef SQLITE_ENABLE_FTS4
   13515   "ENABLE_FTS4",
   13516 #endif
   13517 #ifdef SQLITE_ENABLE_ICU
   13518   "ENABLE_ICU",
   13519 #endif
   13520 #ifdef SQLITE_ENABLE_IOTRACE
   13521   "ENABLE_IOTRACE",
   13522 #endif
   13523 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   13524   "ENABLE_LOAD_EXTENSION",
   13525 #endif
   13526 #ifdef SQLITE_ENABLE_LOCKING_STYLE
   13527   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
   13528 #endif
   13529 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   13530   "ENABLE_MEMORY_MANAGEMENT",
   13531 #endif
   13532 #ifdef SQLITE_ENABLE_MEMSYS3
   13533   "ENABLE_MEMSYS3",
   13534 #endif
   13535 #ifdef SQLITE_ENABLE_MEMSYS5
   13536   "ENABLE_MEMSYS5",
   13537 #endif
   13538 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
   13539   "ENABLE_OVERSIZE_CELL_CHECK",
   13540 #endif
   13541 #ifdef SQLITE_ENABLE_RTREE
   13542   "ENABLE_RTREE",
   13543 #endif
   13544 #if defined(SQLITE_ENABLE_STAT4)
   13545   "ENABLE_STAT4",
   13546 #elif defined(SQLITE_ENABLE_STAT3)
   13547   "ENABLE_STAT3",
   13548 #endif
   13549 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   13550   "ENABLE_UNLOCK_NOTIFY",
   13551 #endif
   13552 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
   13553   "ENABLE_UPDATE_DELETE_LIMIT",
   13554 #endif
   13555 #ifdef SQLITE_HAS_CODEC
   13556   "HAS_CODEC",
   13557 #endif
   13558 #ifdef SQLITE_HAVE_ISNAN
   13559   "HAVE_ISNAN",
   13560 #endif
   13561 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   13562   "HOMEGROWN_RECURSIVE_MUTEX",
   13563 #endif
   13564 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   13565   "IGNORE_AFP_LOCK_ERRORS",
   13566 #endif
   13567 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   13568   "IGNORE_FLOCK_LOCK_ERRORS",
   13569 #endif
   13570 #ifdef SQLITE_INT64_TYPE
   13571   "INT64_TYPE",
   13572 #endif
   13573 #ifdef SQLITE_LOCK_TRACE
   13574   "LOCK_TRACE",
   13575 #endif
   13576 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
   13577   "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
   13578 #endif
   13579 #ifdef SQLITE_MAX_SCHEMA_RETRY
   13580   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
   13581 #endif
   13582 #ifdef SQLITE_MEMDEBUG
   13583   "MEMDEBUG",
   13584 #endif
   13585 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   13586   "MIXED_ENDIAN_64BIT_FLOAT",
   13587 #endif
   13588 #ifdef SQLITE_NO_SYNC
   13589   "NO_SYNC",
   13590 #endif
   13591 #ifdef SQLITE_OMIT_ALTERTABLE
   13592   "OMIT_ALTERTABLE",
   13593 #endif
   13594 #ifdef SQLITE_OMIT_ANALYZE
   13595   "OMIT_ANALYZE",
   13596 #endif
   13597 #ifdef SQLITE_OMIT_ATTACH
   13598   "OMIT_ATTACH",
   13599 #endif
   13600 #ifdef SQLITE_OMIT_AUTHORIZATION
   13601   "OMIT_AUTHORIZATION",
   13602 #endif
   13603 #ifdef SQLITE_OMIT_AUTOINCREMENT
   13604   "OMIT_AUTOINCREMENT",
   13605 #endif
   13606 #ifdef SQLITE_OMIT_AUTOINIT
   13607   "OMIT_AUTOINIT",
   13608 #endif
   13609 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
   13610   "OMIT_AUTOMATIC_INDEX",
   13611 #endif
   13612 #ifdef SQLITE_OMIT_AUTORESET
   13613   "OMIT_AUTORESET",
   13614 #endif
   13615 #ifdef SQLITE_OMIT_AUTOVACUUM
   13616   "OMIT_AUTOVACUUM",
   13617 #endif
   13618 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   13619   "OMIT_BETWEEN_OPTIMIZATION",
   13620 #endif
   13621 #ifdef SQLITE_OMIT_BLOB_LITERAL
   13622   "OMIT_BLOB_LITERAL",
   13623 #endif
   13624 #ifdef SQLITE_OMIT_BTREECOUNT
   13625   "OMIT_BTREECOUNT",
   13626 #endif
   13627 #ifdef SQLITE_OMIT_BUILTIN_TEST
   13628   "OMIT_BUILTIN_TEST",
   13629 #endif
   13630 #ifdef SQLITE_OMIT_CAST
   13631   "OMIT_CAST",
   13632 #endif
   13633 #ifdef SQLITE_OMIT_CHECK
   13634   "OMIT_CHECK",
   13635 #endif
   13636 #ifdef SQLITE_OMIT_COMPLETE
   13637   "OMIT_COMPLETE",
   13638 #endif
   13639 #ifdef SQLITE_OMIT_COMPOUND_SELECT
   13640   "OMIT_COMPOUND_SELECT",
   13641 #endif
   13642 #ifdef SQLITE_OMIT_CTE
   13643   "OMIT_CTE",
   13644 #endif
   13645 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   13646   "OMIT_DATETIME_FUNCS",
   13647 #endif
   13648 #ifdef SQLITE_OMIT_DECLTYPE
   13649   "OMIT_DECLTYPE",
   13650 #endif
   13651 #ifdef SQLITE_OMIT_DEPRECATED
   13652   "OMIT_DEPRECATED",
   13653 #endif
   13654 #ifdef SQLITE_OMIT_DISKIO
   13655   "OMIT_DISKIO",
   13656 #endif
   13657 #ifdef SQLITE_OMIT_EXPLAIN
   13658   "OMIT_EXPLAIN",
   13659 #endif
   13660 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
   13661   "OMIT_FLAG_PRAGMAS",
   13662 #endif
   13663 #ifdef SQLITE_OMIT_FLOATING_POINT
   13664   "OMIT_FLOATING_POINT",
   13665 #endif
   13666 #ifdef SQLITE_OMIT_FOREIGN_KEY
   13667   "OMIT_FOREIGN_KEY",
   13668 #endif
   13669 #ifdef SQLITE_OMIT_GET_TABLE
   13670   "OMIT_GET_TABLE",
   13671 #endif
   13672 #ifdef SQLITE_OMIT_INCRBLOB
   13673   "OMIT_INCRBLOB",
   13674 #endif
   13675 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
   13676   "OMIT_INTEGRITY_CHECK",
   13677 #endif
   13678 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
   13679   "OMIT_LIKE_OPTIMIZATION",
   13680 #endif
   13681 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   13682   "OMIT_LOAD_EXTENSION",
   13683 #endif
   13684 #ifdef SQLITE_OMIT_LOCALTIME
   13685   "OMIT_LOCALTIME",
   13686 #endif
   13687 #ifdef SQLITE_OMIT_LOOKASIDE
   13688   "OMIT_LOOKASIDE",
   13689 #endif
   13690 #ifdef SQLITE_OMIT_MEMORYDB
   13691   "OMIT_MEMORYDB",
   13692 #endif
   13693 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
   13694   "OMIT_OR_OPTIMIZATION",
   13695 #endif
   13696 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
   13697   "OMIT_PAGER_PRAGMAS",
   13698 #endif
   13699 #ifdef SQLITE_OMIT_PRAGMA
   13700   "OMIT_PRAGMA",
   13701 #endif
   13702 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   13703   "OMIT_PROGRESS_CALLBACK",
   13704 #endif
   13705 #ifdef SQLITE_OMIT_QUICKBALANCE
   13706   "OMIT_QUICKBALANCE",
   13707 #endif
   13708 #ifdef SQLITE_OMIT_REINDEX
   13709   "OMIT_REINDEX",
   13710 #endif
   13711 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
   13712   "OMIT_SCHEMA_PRAGMAS",
   13713 #endif
   13714 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   13715   "OMIT_SCHEMA_VERSION_PRAGMAS",
   13716 #endif
   13717 #ifdef SQLITE_OMIT_SHARED_CACHE
   13718   "OMIT_SHARED_CACHE",
   13719 #endif
   13720 #ifdef SQLITE_OMIT_SUBQUERY
   13721   "OMIT_SUBQUERY",
   13722 #endif
   13723 #ifdef SQLITE_OMIT_TCL_VARIABLE
   13724   "OMIT_TCL_VARIABLE",
   13725 #endif
   13726 #ifdef SQLITE_OMIT_TEMPDB
   13727   "OMIT_TEMPDB",
   13728 #endif
   13729 #ifdef SQLITE_OMIT_TRACE
   13730   "OMIT_TRACE",
   13731 #endif
   13732 #ifdef SQLITE_OMIT_TRIGGER
   13733   "OMIT_TRIGGER",
   13734 #endif
   13735 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   13736   "OMIT_TRUNCATE_OPTIMIZATION",
   13737 #endif
   13738 #ifdef SQLITE_OMIT_UTF16
   13739   "OMIT_UTF16",
   13740 #endif
   13741 #ifdef SQLITE_OMIT_VACUUM
   13742   "OMIT_VACUUM",
   13743 #endif
   13744 #ifdef SQLITE_OMIT_VIEW
   13745   "OMIT_VIEW",
   13746 #endif
   13747 #ifdef SQLITE_OMIT_VIRTUALTABLE
   13748   "OMIT_VIRTUALTABLE",
   13749 #endif
   13750 #ifdef SQLITE_OMIT_WAL
   13751   "OMIT_WAL",
   13752 #endif
   13753 #ifdef SQLITE_OMIT_WSD
   13754   "OMIT_WSD",
   13755 #endif
   13756 #ifdef SQLITE_OMIT_XFER_OPT
   13757   "OMIT_XFER_OPT",
   13758 #endif
   13759 #ifdef SQLITE_PERFORMANCE_TRACE
   13760   "PERFORMANCE_TRACE",
   13761 #endif
   13762 #ifdef SQLITE_PROXY_DEBUG
   13763   "PROXY_DEBUG",
   13764 #endif
   13765 #ifdef SQLITE_RTREE_INT_ONLY
   13766   "RTREE_INT_ONLY",
   13767 #endif
   13768 #ifdef SQLITE_SECURE_DELETE
   13769   "SECURE_DELETE",
   13770 #endif
   13771 #ifdef SQLITE_SMALL_STACK
   13772   "SMALL_STACK",
   13773 #endif
   13774 #ifdef SQLITE_SOUNDEX
   13775   "SOUNDEX",
   13776 #endif
   13777 #ifdef SQLITE_SYSTEM_MALLOC
   13778   "SYSTEM_MALLOC",
   13779 #endif
   13780 #ifdef SQLITE_TCL
   13781   "TCL",
   13782 #endif
   13783 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
   13784   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
   13785 #endif
   13786 #ifdef SQLITE_TEST
   13787   "TEST",
   13788 #endif
   13789 #if defined(SQLITE_THREADSAFE)
   13790   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
   13791 #endif
   13792 #ifdef SQLITE_USE_ALLOCA
   13793   "USE_ALLOCA",
   13794 #endif
   13795 #ifdef SQLITE_WIN32_MALLOC
   13796   "WIN32_MALLOC",
   13797 #endif
   13798 #ifdef SQLITE_ZERO_MALLOC
   13799   "ZERO_MALLOC"
   13800 #endif
   13801 };
   13802 
   13803 /*
   13804 ** Given the name of a compile-time option, return true if that option
   13805 ** was used and false if not.
   13806 **
   13807 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
   13808 ** is not required for a match.
   13809 */
   13810 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
   13811   int i, n;
   13812   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
   13813   n = sqlite3Strlen30(zOptName);
   13814 
   13815   /* Since ArraySize(azCompileOpt) is normally in single digits, a
   13816   ** linear search is adequate.  No need for a binary search. */
   13817   for(i=0; i<ArraySize(azCompileOpt); i++){
   13818     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
   13819      && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
   13820     ){
   13821       return 1;
   13822     }
   13823   }
   13824   return 0;
   13825 }
   13826 
   13827 /*
   13828 ** Return the N-th compile-time option string.  If N is out of range,
   13829 ** return a NULL pointer.
   13830 */
   13831 SQLITE_API const char *sqlite3_compileoption_get(int N){
   13832   if( N>=0 && N<ArraySize(azCompileOpt) ){
   13833     return azCompileOpt[N];
   13834   }
   13835   return 0;
   13836 }
   13837 
   13838 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   13839 
   13840 /************** End of ctime.c ***********************************************/
   13841 /************** Begin file status.c ******************************************/
   13842 /*
   13843 ** 2008 June 18
   13844 **
   13845 ** The author disclaims copyright to this source code.  In place of
   13846 ** a legal notice, here is a blessing:
   13847 **
   13848 **    May you do good and not evil.
   13849 **    May you find forgiveness for yourself and forgive others.
   13850 **    May you share freely, never taking more than you give.
   13851 **
   13852 *************************************************************************
   13853 **
   13854 ** This module implements the sqlite3_status() interface and related
   13855 ** functionality.
   13856 */
   13857 /************** Include vdbeInt.h in the middle of status.c ******************/
   13858 /************** Begin file vdbeInt.h *****************************************/
   13859 /*
   13860 ** 2003 September 6
   13861 **
   13862 ** The author disclaims copyright to this source code.  In place of
   13863 ** a legal notice, here is a blessing:
   13864 **
   13865 **    May you do good and not evil.
   13866 **    May you find forgiveness for yourself and forgive others.
   13867 **    May you share freely, never taking more than you give.
   13868 **
   13869 *************************************************************************
   13870 ** This is the header file for information that is private to the
   13871 ** VDBE.  This information used to all be at the top of the single
   13872 ** source code file "vdbe.c".  When that file became too big (over
   13873 ** 6000 lines long) it was split up into several smaller files and
   13874 ** this header information was factored out.
   13875 */
   13876 #ifndef _VDBEINT_H_
   13877 #define _VDBEINT_H_
   13878 
   13879 /*
   13880 ** The maximum number of times that a statement will try to reparse
   13881 ** itself before giving up and returning SQLITE_SCHEMA.
   13882 */
   13883 #ifndef SQLITE_MAX_SCHEMA_RETRY
   13884 # define SQLITE_MAX_SCHEMA_RETRY 50
   13885 #endif
   13886 
   13887 /*
   13888 ** SQL is translated into a sequence of instructions to be
   13889 ** executed by a virtual machine.  Each instruction is an instance
   13890 ** of the following structure.
   13891 */
   13892 typedef struct VdbeOp Op;
   13893 
   13894 /*
   13895 ** Boolean values
   13896 */
   13897 typedef unsigned Bool;
   13898 
   13899 /* Opaque type used by code in vdbesort.c */
   13900 typedef struct VdbeSorter VdbeSorter;
   13901 
   13902 /* Opaque type used by the explainer */
   13903 typedef struct Explain Explain;
   13904 
   13905 /* Elements of the linked list at Vdbe.pAuxData */
   13906 typedef struct AuxData AuxData;
   13907 
   13908 /*
   13909 ** A cursor is a pointer into a single BTree within a database file.
   13910 ** The cursor can seek to a BTree entry with a particular key, or
   13911 ** loop over all entries of the Btree.  You can also insert new BTree
   13912 ** entries or retrieve the key or data from the entry that the cursor
   13913 ** is currently pointing to.
   13914 **
   13915 ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
   13916 ** A pseudo-table is a single-row table implemented by registers.
   13917 **
   13918 ** Every cursor that the virtual machine has open is represented by an
   13919 ** instance of the following structure.
   13920 */
   13921 struct VdbeCursor {
   13922   BtCursor *pCursor;    /* The cursor structure of the backend */
   13923   Btree *pBt;           /* Separate file holding temporary table */
   13924   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
   13925   int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
   13926   int pseudoTableReg;   /* Register holding pseudotable content. */
   13927   i16 nField;           /* Number of fields in the header */
   13928   u16 nHdrParsed;       /* Number of header fields parsed so far */
   13929 #ifdef SQLITE_DEBUG
   13930   u8 seekOp;            /* Most recent seek operation on this cursor */
   13931 #endif
   13932   i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
   13933   u8 nullRow;           /* True if pointing to a row with no data */
   13934   u8 rowidIsValid;      /* True if lastRowid is valid */
   13935   u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
   13936   Bool isEphemeral:1;   /* True for an ephemeral table */
   13937   Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
   13938   Bool isTable:1;       /* True if a table requiring integer keys */
   13939   Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
   13940   Pgno pgnoRoot;        /* Root page of the open btree cursor */
   13941   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
   13942   i64 seqCount;         /* Sequence counter */
   13943   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
   13944   i64 lastRowid;        /* Rowid being deleted by OP_Delete */
   13945   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
   13946 
   13947   /* Cached information about the header for the data record that the
   13948   ** cursor is currently pointing to.  Only valid if cacheStatus matches
   13949   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
   13950   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
   13951   ** the cache is out of date.
   13952   **
   13953   ** aRow might point to (ephemeral) data for the current row, or it might
   13954   ** be NULL.
   13955   */
   13956   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
   13957   u32 payloadSize;      /* Total number of bytes in the record */
   13958   u32 szRow;            /* Byte available in aRow */
   13959   u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
   13960   const u8 *aRow;       /* Data for the current row, if all on one page */
   13961   u32 aType[1];         /* Type values for all entries in the record */
   13962   /* 2*nField extra array elements allocated for aType[], beyond the one
   13963   ** static element declared in the structure.  nField total array slots for
   13964   ** aType[] and nField+1 array slots for aOffset[] */
   13965 };
   13966 typedef struct VdbeCursor VdbeCursor;
   13967 
   13968 /*
   13969 ** When a sub-program is executed (OP_Program), a structure of this type
   13970 ** is allocated to store the current value of the program counter, as
   13971 ** well as the current memory cell array and various other frame specific
   13972 ** values stored in the Vdbe struct. When the sub-program is finished,
   13973 ** these values are copied back to the Vdbe from the VdbeFrame structure,
   13974 ** restoring the state of the VM to as it was before the sub-program
   13975 ** began executing.
   13976 **
   13977 ** The memory for a VdbeFrame object is allocated and managed by a memory
   13978 ** cell in the parent (calling) frame. When the memory cell is deleted or
   13979 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
   13980 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
   13981 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
   13982 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
   13983 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
   13984 ** child frame are released.
   13985 **
   13986 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
   13987 ** set to NULL if the currently executing frame is the main program.
   13988 */
   13989 typedef struct VdbeFrame VdbeFrame;
   13990 struct VdbeFrame {
   13991   Vdbe *v;                /* VM this frame belongs to */
   13992   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
   13993   Op *aOp;                /* Program instructions for parent frame */
   13994   Mem *aMem;              /* Array of memory cells for parent frame */
   13995   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
   13996   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
   13997   void *token;            /* Copy of SubProgram.token */
   13998   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
   13999   int nCursor;            /* Number of entries in apCsr */
   14000   int pc;                 /* Program Counter in parent (calling) frame */
   14001   int nOp;                /* Size of aOp array */
   14002   int nMem;               /* Number of entries in aMem */
   14003   int nOnceFlag;          /* Number of entries in aOnceFlag */
   14004   int nChildMem;          /* Number of memory cells for child frame */
   14005   int nChildCsr;          /* Number of cursors for child frame */
   14006   int nChange;            /* Statement changes (Vdbe.nChanges)     */
   14007 };
   14008 
   14009 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
   14010 
   14011 /*
   14012 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
   14013 */
   14014 #define CACHE_STALE 0
   14015 
   14016 /*
   14017 ** Internally, the vdbe manipulates nearly all SQL values as Mem
   14018 ** structures. Each Mem struct may cache multiple representations (string,
   14019 ** integer etc.) of the same value.
   14020 */
   14021 struct Mem {
   14022   sqlite3 *db;        /* The associated database connection */
   14023   char *z;            /* String or BLOB value */
   14024   double r;           /* Real value */
   14025   union {
   14026     i64 i;              /* Integer value used when MEM_Int is set in flags */
   14027     int nZero;          /* Used when bit MEM_Zero is set in flags */
   14028     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
   14029     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
   14030     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
   14031   } u;
   14032   int n;              /* Number of characters in string value, excluding '\0' */
   14033   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
   14034   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
   14035 #ifdef SQLITE_DEBUG
   14036   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
   14037   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
   14038 #endif
   14039   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
   14040   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
   14041 };
   14042 
   14043 /* One or more of the following flags are set to indicate the validOK
   14044 ** representations of the value stored in the Mem struct.
   14045 **
   14046 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
   14047 ** No other flags may be set in this case.
   14048 **
   14049 ** If the MEM_Str flag is set then Mem.z points at a string representation.
   14050 ** Usually this is encoded in the same unicode encoding as the main
   14051 ** database (see below for exceptions). If the MEM_Term flag is also
   14052 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
   14053 ** flags may coexist with the MEM_Str flag.
   14054 */
   14055 #define MEM_Null      0x0001   /* Value is NULL */
   14056 #define MEM_Str       0x0002   /* Value is a string */
   14057 #define MEM_Int       0x0004   /* Value is an integer */
   14058 #define MEM_Real      0x0008   /* Value is a real number */
   14059 #define MEM_Blob      0x0010   /* Value is a BLOB */
   14060 #define MEM_AffMask   0x001f   /* Mask of affinity bits */
   14061 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
   14062 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
   14063 #define MEM_Undefined 0x0080   /* Value is undefined */
   14064 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
   14065 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
   14066 
   14067 
   14068 /* Whenever Mem contains a valid string or blob representation, one of
   14069 ** the following flags must be set to determine the memory management
   14070 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
   14071 ** string is \000 or \u0000 terminated
   14072 */
   14073 #define MEM_Term      0x0200   /* String rep is nul terminated */
   14074 #define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
   14075 #define MEM_Static    0x0800   /* Mem.z points to a static string */
   14076 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
   14077 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
   14078 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
   14079 #ifdef SQLITE_OMIT_INCRBLOB
   14080   #undef MEM_Zero
   14081   #define MEM_Zero 0x0000
   14082 #endif
   14083 
   14084 /*
   14085 ** Clear any existing type flags from a Mem and replace them with f
   14086 */
   14087 #define MemSetTypeFlag(p, f) \
   14088    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
   14089 
   14090 /*
   14091 ** Return true if a memory cell is not marked as invalid.  This macro
   14092 ** is for use inside assert() statements only.
   14093 */
   14094 #ifdef SQLITE_DEBUG
   14095 #define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
   14096 #endif
   14097 
   14098 /*
   14099 ** Each auxilliary data pointer stored by a user defined function
   14100 ** implementation calling sqlite3_set_auxdata() is stored in an instance
   14101 ** of this structure. All such structures associated with a single VM
   14102 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
   14103 ** when the VM is halted (if not before).
   14104 */
   14105 struct AuxData {
   14106   int iOp;                        /* Instruction number of OP_Function opcode */
   14107   int iArg;                       /* Index of function argument. */
   14108   void *pAux;                     /* Aux data pointer */
   14109   void (*xDelete)(void *);        /* Destructor for the aux data */
   14110   AuxData *pNext;                 /* Next element in list */
   14111 };
   14112 
   14113 /*
   14114 ** The "context" argument for a installable function.  A pointer to an
   14115 ** instance of this structure is the first argument to the routines used
   14116 ** implement the SQL functions.
   14117 **
   14118 ** There is a typedef for this structure in sqlite.h.  So all routines,
   14119 ** even the public interface to SQLite, can use a pointer to this structure.
   14120 ** But this file is the only place where the internal details of this
   14121 ** structure are known.
   14122 **
   14123 ** This structure is defined inside of vdbeInt.h because it uses substructures
   14124 ** (Mem) which are only defined there.
   14125 */
   14126 struct sqlite3_context {
   14127   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
   14128   Mem s;                /* The return value is stored here */
   14129   Mem *pMem;            /* Memory cell used to store aggregate context */
   14130   CollSeq *pColl;       /* Collating sequence */
   14131   Vdbe *pVdbe;          /* The VM that owns this context */
   14132   int iOp;              /* Instruction number of OP_Function */
   14133   int isError;          /* Error code returned by the function. */
   14134   u8 skipFlag;          /* Skip skip accumulator loading if true */
   14135   u8 fErrorOrAux;       /* isError!=0 or pVdbe->pAuxData modified */
   14136 };
   14137 
   14138 /*
   14139 ** An Explain object accumulates indented output which is helpful
   14140 ** in describing recursive data structures.
   14141 */
   14142 struct Explain {
   14143   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
   14144   StrAccum str;      /* The string being accumulated */
   14145   int nIndent;       /* Number of elements in aIndent */
   14146   u16 aIndent[100];  /* Levels of indentation */
   14147   char zBase[100];   /* Initial space */
   14148 };
   14149 
   14150 /* A bitfield type for use inside of structures.  Always follow with :N where
   14151 ** N is the number of bits.
   14152 */
   14153 typedef unsigned bft;  /* Bit Field Type */
   14154 
   14155 /*
   14156 ** An instance of the virtual machine.  This structure contains the complete
   14157 ** state of the virtual machine.
   14158 **
   14159 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
   14160 ** is really a pointer to an instance of this structure.
   14161 **
   14162 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
   14163 ** any virtual table method invocations made by the vdbe program. It is
   14164 ** set to 2 for xDestroy method calls and 1 for all other methods. This
   14165 ** variable is used for two purposes: to allow xDestroy methods to execute
   14166 ** "DROP TABLE" statements and to prevent some nasty side effects of
   14167 ** malloc failure when SQLite is invoked recursively by a virtual table
   14168 ** method function.
   14169 */
   14170 struct Vdbe {
   14171   sqlite3 *db;            /* The database connection that owns this statement */
   14172   Op *aOp;                /* Space to hold the virtual machine's program */
   14173   Mem *aMem;              /* The memory locations */
   14174   Mem **apArg;            /* Arguments to currently executing user function */
   14175   Mem *aColName;          /* Column names to return */
   14176   Mem *pResultSet;        /* Pointer to an array of results */
   14177   Parse *pParse;          /* Parsing context used to create this Vdbe */
   14178   int nMem;               /* Number of memory locations currently allocated */
   14179   int nOp;                /* Number of instructions in the program */
   14180   int nCursor;            /* Number of slots in apCsr[] */
   14181   u32 magic;              /* Magic number for sanity checking */
   14182   char *zErrMsg;          /* Error message written here */
   14183   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
   14184   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
   14185   Mem *aVar;              /* Values for the OP_Variable opcode. */
   14186   char **azVar;           /* Name of variables */
   14187   ynVar nVar;             /* Number of entries in aVar[] */
   14188   ynVar nzVar;            /* Number of entries in azVar[] */
   14189   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
   14190   int pc;                 /* The program counter */
   14191   int rc;                 /* Value to return */
   14192   u16 nResColumn;         /* Number of columns in one row of the result set */
   14193   u8 errorAction;         /* Recovery action to do in case of an error */
   14194   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
   14195   bft explain:2;          /* True if EXPLAIN present on SQL command */
   14196   bft inVtabMethod:2;     /* See comments above */
   14197   bft changeCntOn:1;      /* True to update the change-counter */
   14198   bft expired:1;          /* True if the VM needs to be recompiled */
   14199   bft runOnlyOnce:1;      /* Automatically expire on reset */
   14200   bft usesStmtJournal:1;  /* True if uses a statement journal */
   14201   bft readOnly:1;         /* True for statements that do not write */
   14202   bft bIsReader:1;        /* True for statements that read */
   14203   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
   14204   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
   14205   int nChange;            /* Number of db changes made since last reset */
   14206   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
   14207   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
   14208   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
   14209   u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
   14210 #ifndef SQLITE_OMIT_TRACE
   14211   i64 startTime;          /* Time when query started - used for profiling */
   14212 #endif
   14213   i64 iCurrentTime;       /* Value of julianday('now') for this statement */
   14214   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
   14215   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
   14216   i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
   14217   char *zSql;             /* Text of the SQL statement that generated this */
   14218   void *pFree;            /* Free this when deleting the vdbe */
   14219 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
   14220   Explain *pExplain;      /* The explainer */
   14221   char *zExplain;         /* Explanation of data structures */
   14222 #endif
   14223   VdbeFrame *pFrame;      /* Parent frame */
   14224   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
   14225   int nFrame;             /* Number of frames in pFrame list */
   14226   u32 expmask;            /* Binding to these vars invalidates VM */
   14227   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
   14228   int nOnceFlag;          /* Size of array aOnceFlag[] */
   14229   u8 *aOnceFlag;          /* Flags for OP_Once */
   14230   AuxData *pAuxData;      /* Linked list of auxdata allocations */
   14231 };
   14232 
   14233 /*
   14234 ** The following are allowed values for Vdbe.magic
   14235 */
   14236 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
   14237 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
   14238 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
   14239 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
   14240 
   14241 /*
   14242 ** Function prototypes
   14243 */
   14244 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
   14245 void sqliteVdbePopStack(Vdbe*,int);
   14246 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
   14247 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   14248 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
   14249 #endif
   14250 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
   14251 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
   14252 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
   14253 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
   14254 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
   14255 
   14256 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
   14257 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
   14258 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
   14259 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
   14260 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
   14261 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
   14262 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
   14263 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
   14264 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
   14265 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
   14266 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
   14267 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
   14268 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
   14269 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
   14270 #ifdef SQLITE_OMIT_FLOATING_POINT
   14271 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
   14272 #else
   14273 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
   14274 #endif
   14275 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
   14276 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
   14277 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
   14278 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
   14279 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
   14280 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
   14281 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
   14282 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
   14283 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
   14284 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
   14285 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
   14286 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
   14287 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
   14288 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
   14289 #define VdbeMemDynamic(X)  \
   14290   (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
   14291 #define VdbeMemRelease(X)  \
   14292   if( VdbeMemDynamic(X) ) sqlite3VdbeMemReleaseExternal(X);
   14293 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
   14294 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
   14295 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
   14296 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
   14297 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
   14298 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
   14299 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
   14300 
   14301 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
   14302 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
   14303 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
   14304 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
   14305 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
   14306 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
   14307 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
   14308 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
   14309 
   14310 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   14311 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
   14312 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
   14313 #else
   14314 # define sqlite3VdbeEnter(X)
   14315 # define sqlite3VdbeLeave(X)
   14316 #endif
   14317 
   14318 #ifdef SQLITE_DEBUG
   14319 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
   14320 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
   14321 #endif
   14322 
   14323 #ifndef SQLITE_OMIT_FOREIGN_KEY
   14324 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
   14325 #else
   14326 # define sqlite3VdbeCheckFk(p,i) 0
   14327 #endif
   14328 
   14329 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
   14330 #ifdef SQLITE_DEBUG
   14331 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
   14332 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
   14333 #endif
   14334 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
   14335 
   14336 #ifndef SQLITE_OMIT_INCRBLOB
   14337 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
   14338   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
   14339 #else
   14340   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
   14341   #define ExpandBlob(P) SQLITE_OK
   14342 #endif
   14343 
   14344 #endif /* !defined(_VDBEINT_H_) */
   14345 
   14346 /************** End of vdbeInt.h *********************************************/
   14347 /************** Continuing where we left off in status.c *********************/
   14348 
   14349 /*
   14350 ** Variables in which to record status information.
   14351 */
   14352 typedef struct sqlite3StatType sqlite3StatType;
   14353 static SQLITE_WSD struct sqlite3StatType {
   14354   int nowValue[10];         /* Current value */
   14355   int mxValue[10];          /* Maximum value */
   14356 } sqlite3Stat = { {0,}, {0,} };
   14357 
   14358 
   14359 /* The "wsdStat" macro will resolve to the status information
   14360 ** state vector.  If writable static data is unsupported on the target,
   14361 ** we have to locate the state vector at run-time.  In the more common
   14362 ** case where writable static data is supported, wsdStat can refer directly
   14363 ** to the "sqlite3Stat" state vector declared above.
   14364 */
   14365 #ifdef SQLITE_OMIT_WSD
   14366 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
   14367 # define wsdStat x[0]
   14368 #else
   14369 # define wsdStatInit
   14370 # define wsdStat sqlite3Stat
   14371 #endif
   14372 
   14373 /*
   14374 ** Return the current value of a status parameter.
   14375 */
   14376 SQLITE_PRIVATE int sqlite3StatusValue(int op){
   14377   wsdStatInit;
   14378   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   14379   return wsdStat.nowValue[op];
   14380 }
   14381 
   14382 /*
   14383 ** Add N to the value of a status record.  It is assumed that the
   14384 ** caller holds appropriate locks.
   14385 */
   14386 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
   14387   wsdStatInit;
   14388   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   14389   wsdStat.nowValue[op] += N;
   14390   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   14391     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   14392   }
   14393 }
   14394 
   14395 /*
   14396 ** Set the value of a status to X.
   14397 */
   14398 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
   14399   wsdStatInit;
   14400   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   14401   wsdStat.nowValue[op] = X;
   14402   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   14403     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   14404   }
   14405 }
   14406 
   14407 /*
   14408 ** Query status information.
   14409 **
   14410 ** This implementation assumes that reading or writing an aligned
   14411 ** 32-bit integer is an atomic operation.  If that assumption is not true,
   14412 ** then this routine is not threadsafe.
   14413 */
   14414 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
   14415   wsdStatInit;
   14416   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
   14417     return SQLITE_MISUSE_BKPT;
   14418   }
   14419   *pCurrent = wsdStat.nowValue[op];
   14420   *pHighwater = wsdStat.mxValue[op];
   14421   if( resetFlag ){
   14422     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   14423   }
   14424   return SQLITE_OK;
   14425 }
   14426 
   14427 /*
   14428 ** Query status information for a single database connection
   14429 */
   14430 SQLITE_API int sqlite3_db_status(
   14431   sqlite3 *db,          /* The database connection whose status is desired */
   14432   int op,               /* Status verb */
   14433   int *pCurrent,        /* Write current value here */
   14434   int *pHighwater,      /* Write high-water mark here */
   14435   int resetFlag         /* Reset high-water mark if true */
   14436 ){
   14437   int rc = SQLITE_OK;   /* Return code */
   14438   sqlite3_mutex_enter(db->mutex);
   14439   switch( op ){
   14440     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
   14441       *pCurrent = db->lookaside.nOut;
   14442       *pHighwater = db->lookaside.mxOut;
   14443       if( resetFlag ){
   14444         db->lookaside.mxOut = db->lookaside.nOut;
   14445       }
   14446       break;
   14447     }
   14448 
   14449     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
   14450     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
   14451     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
   14452       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
   14453       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
   14454       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
   14455       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
   14456       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
   14457       *pCurrent = 0;
   14458       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
   14459       if( resetFlag ){
   14460         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
   14461       }
   14462       break;
   14463     }
   14464 
   14465     /*
   14466     ** Return an approximation for the amount of memory currently used
   14467     ** by all pagers associated with the given database connection.  The
   14468     ** highwater mark is meaningless and is returned as zero.
   14469     */
   14470     case SQLITE_DBSTATUS_CACHE_USED: {
   14471       int totalUsed = 0;
   14472       int i;
   14473       sqlite3BtreeEnterAll(db);
   14474       for(i=0; i<db->nDb; i++){
   14475         Btree *pBt = db->aDb[i].pBt;
   14476         if( pBt ){
   14477           Pager *pPager = sqlite3BtreePager(pBt);
   14478           totalUsed += sqlite3PagerMemUsed(pPager);
   14479         }
   14480       }
   14481       sqlite3BtreeLeaveAll(db);
   14482       *pCurrent = totalUsed;
   14483       *pHighwater = 0;
   14484       break;
   14485     }
   14486 
   14487     /*
   14488     ** *pCurrent gets an accurate estimate of the amount of memory used
   14489     ** to store the schema for all databases (main, temp, and any ATTACHed
   14490     ** databases.  *pHighwater is set to zero.
   14491     */
   14492     case SQLITE_DBSTATUS_SCHEMA_USED: {
   14493       int i;                      /* Used to iterate through schemas */
   14494       int nByte = 0;              /* Used to accumulate return value */
   14495 
   14496       sqlite3BtreeEnterAll(db);
   14497       db->pnBytesFreed = &nByte;
   14498       for(i=0; i<db->nDb; i++){
   14499         Schema *pSchema = db->aDb[i].pSchema;
   14500         if( ALWAYS(pSchema!=0) ){
   14501           HashElem *p;
   14502 
   14503           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
   14504               pSchema->tblHash.count
   14505             + pSchema->trigHash.count
   14506             + pSchema->idxHash.count
   14507             + pSchema->fkeyHash.count
   14508           );
   14509           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
   14510           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
   14511           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
   14512           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
   14513 
   14514           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
   14515             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
   14516           }
   14517           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
   14518             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
   14519           }
   14520         }
   14521       }
   14522       db->pnBytesFreed = 0;
   14523       sqlite3BtreeLeaveAll(db);
   14524 
   14525       *pHighwater = 0;
   14526       *pCurrent = nByte;
   14527       break;
   14528     }
   14529 
   14530     /*
   14531     ** *pCurrent gets an accurate estimate of the amount of memory used
   14532     ** to store all prepared statements.
   14533     ** *pHighwater is set to zero.
   14534     */
   14535     case SQLITE_DBSTATUS_STMT_USED: {
   14536       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
   14537       int nByte = 0;              /* Used to accumulate return value */
   14538 
   14539       db->pnBytesFreed = &nByte;
   14540       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
   14541         sqlite3VdbeClearObject(db, pVdbe);
   14542         sqlite3DbFree(db, pVdbe);
   14543       }
   14544       db->pnBytesFreed = 0;
   14545 
   14546       *pHighwater = 0;
   14547       *pCurrent = nByte;
   14548 
   14549       break;
   14550     }
   14551 
   14552     /*
   14553     ** Set *pCurrent to the total cache hits or misses encountered by all
   14554     ** pagers the database handle is connected to. *pHighwater is always set
   14555     ** to zero.
   14556     */
   14557     case SQLITE_DBSTATUS_CACHE_HIT:
   14558     case SQLITE_DBSTATUS_CACHE_MISS:
   14559     case SQLITE_DBSTATUS_CACHE_WRITE:{
   14560       int i;
   14561       int nRet = 0;
   14562       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
   14563       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
   14564 
   14565       for(i=0; i<db->nDb; i++){
   14566         if( db->aDb[i].pBt ){
   14567           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
   14568           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
   14569         }
   14570       }
   14571       *pHighwater = 0;
   14572       *pCurrent = nRet;
   14573       break;
   14574     }
   14575 
   14576     /* Set *pCurrent to non-zero if there are unresolved deferred foreign
   14577     ** key constraints.  Set *pCurrent to zero if all foreign key constraints
   14578     ** have been satisfied.  The *pHighwater is always set to zero.
   14579     */
   14580     case SQLITE_DBSTATUS_DEFERRED_FKS: {
   14581       *pHighwater = 0;
   14582       *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
   14583       break;
   14584     }
   14585 
   14586     default: {
   14587       rc = SQLITE_ERROR;
   14588     }
   14589   }
   14590   sqlite3_mutex_leave(db->mutex);
   14591   return rc;
   14592 }
   14593 
   14594 /************** End of status.c **********************************************/
   14595 /************** Begin file date.c ********************************************/
   14596 /*
   14597 ** 2003 October 31
   14598 **
   14599 ** The author disclaims copyright to this source code.  In place of
   14600 ** a legal notice, here is a blessing:
   14601 **
   14602 **    May you do good and not evil.
   14603 **    May you find forgiveness for yourself and forgive others.
   14604 **    May you share freely, never taking more than you give.
   14605 **
   14606 *************************************************************************
   14607 ** This file contains the C functions that implement date and time
   14608 ** functions for SQLite.
   14609 **
   14610 ** There is only one exported symbol in this file - the function
   14611 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
   14612 ** All other code has file scope.
   14613 **
   14614 ** SQLite processes all times and dates as Julian Day numbers.  The
   14615 ** dates and times are stored as the number of days since noon
   14616 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
   14617 ** calendar system.
   14618 **
   14619 ** 1970-01-01 00:00:00 is JD 2440587.5
   14620 ** 2000-01-01 00:00:00 is JD 2451544.5
   14621 **
   14622 ** This implemention requires years to be expressed as a 4-digit number
   14623 ** which means that only dates between 0000-01-01 and 9999-12-31 can
   14624 ** be represented, even though julian day numbers allow a much wider
   14625 ** range of dates.
   14626 **
   14627 ** The Gregorian calendar system is used for all dates and times,
   14628 ** even those that predate the Gregorian calendar.  Historians usually
   14629 ** use the Julian calendar for dates prior to 1582-10-15 and for some
   14630 ** dates afterwards, depending on locale.  Beware of this difference.
   14631 **
   14632 ** The conversion algorithms are implemented based on descriptions
   14633 ** in the following text:
   14634 **
   14635 **      Jean Meeus
   14636 **      Astronomical Algorithms, 2nd Edition, 1998
   14637 **      ISBM 0-943396-61-1
   14638 **      Willmann-Bell, Inc
   14639 **      Richmond, Virginia (USA)
   14640 */
   14641 /* #include <stdlib.h> */
   14642 /* #include <assert.h> */
   14643 #include <time.h>
   14644 
   14645 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   14646 
   14647 
   14648 /*
   14649 ** A structure for holding a single date and time.
   14650 */
   14651 typedef struct DateTime DateTime;
   14652 struct DateTime {
   14653   sqlite3_int64 iJD; /* The julian day number times 86400000 */
   14654   int Y, M, D;       /* Year, month, and day */
   14655   int h, m;          /* Hour and minutes */
   14656   int tz;            /* Timezone offset in minutes */
   14657   double s;          /* Seconds */
   14658   char validYMD;     /* True (1) if Y,M,D are valid */
   14659   char validHMS;     /* True (1) if h,m,s are valid */
   14660   char validJD;      /* True (1) if iJD is valid */
   14661   char validTZ;      /* True (1) if tz is valid */
   14662 };
   14663 
   14664 
   14665 /*
   14666 ** Convert zDate into one or more integers.  Additional arguments
   14667 ** come in groups of 5 as follows:
   14668 **
   14669 **       N       number of digits in the integer
   14670 **       min     minimum allowed value of the integer
   14671 **       max     maximum allowed value of the integer
   14672 **       nextC   first character after the integer
   14673 **       pVal    where to write the integers value.
   14674 **
   14675 ** Conversions continue until one with nextC==0 is encountered.
   14676 ** The function returns the number of successful conversions.
   14677 */
   14678 static int getDigits(const char *zDate, ...){
   14679   va_list ap;
   14680   int val;
   14681   int N;
   14682   int min;
   14683   int max;
   14684   int nextC;
   14685   int *pVal;
   14686   int cnt = 0;
   14687   va_start(ap, zDate);
   14688   do{
   14689     N = va_arg(ap, int);
   14690     min = va_arg(ap, int);
   14691     max = va_arg(ap, int);
   14692     nextC = va_arg(ap, int);
   14693     pVal = va_arg(ap, int*);
   14694     val = 0;
   14695     while( N-- ){
   14696       if( !sqlite3Isdigit(*zDate) ){
   14697         goto end_getDigits;
   14698       }
   14699       val = val*10 + *zDate - '0';
   14700       zDate++;
   14701     }
   14702     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
   14703       goto end_getDigits;
   14704     }
   14705     *pVal = val;
   14706     zDate++;
   14707     cnt++;
   14708   }while( nextC );
   14709 end_getDigits:
   14710   va_end(ap);
   14711   return cnt;
   14712 }
   14713 
   14714 /*
   14715 ** Parse a timezone extension on the end of a date-time.
   14716 ** The extension is of the form:
   14717 **
   14718 **        (+/-)HH:MM
   14719 **
   14720 ** Or the "zulu" notation:
   14721 **
   14722 **        Z
   14723 **
   14724 ** If the parse is successful, write the number of minutes
   14725 ** of change in p->tz and return 0.  If a parser error occurs,
   14726 ** return non-zero.
   14727 **
   14728 ** A missing specifier is not considered an error.
   14729 */
   14730 static int parseTimezone(const char *zDate, DateTime *p){
   14731   int sgn = 0;
   14732   int nHr, nMn;
   14733   int c;
   14734   while( sqlite3Isspace(*zDate) ){ zDate++; }
   14735   p->tz = 0;
   14736   c = *zDate;
   14737   if( c=='-' ){
   14738     sgn = -1;
   14739   }else if( c=='+' ){
   14740     sgn = +1;
   14741   }else if( c=='Z' || c=='z' ){
   14742     zDate++;
   14743     goto zulu_time;
   14744   }else{
   14745     return c!=0;
   14746   }
   14747   zDate++;
   14748   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
   14749     return 1;
   14750   }
   14751   zDate += 5;
   14752   p->tz = sgn*(nMn + nHr*60);
   14753 zulu_time:
   14754   while( sqlite3Isspace(*zDate) ){ zDate++; }
   14755   return *zDate!=0;
   14756 }
   14757 
   14758 /*
   14759 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
   14760 ** The HH, MM, and SS must each be exactly 2 digits.  The
   14761 ** fractional seconds FFFF can be one or more digits.
   14762 **
   14763 ** Return 1 if there is a parsing error and 0 on success.
   14764 */
   14765 static int parseHhMmSs(const char *zDate, DateTime *p){
   14766   int h, m, s;
   14767   double ms = 0.0;
   14768   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
   14769     return 1;
   14770   }
   14771   zDate += 5;
   14772   if( *zDate==':' ){
   14773     zDate++;
   14774     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
   14775       return 1;
   14776     }
   14777     zDate += 2;
   14778     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
   14779       double rScale = 1.0;
   14780       zDate++;
   14781       while( sqlite3Isdigit(*zDate) ){
   14782         ms = ms*10.0 + *zDate - '0';
   14783         rScale *= 10.0;
   14784         zDate++;
   14785       }
   14786       ms /= rScale;
   14787     }
   14788   }else{
   14789     s = 0;
   14790   }
   14791   p->validJD = 0;
   14792   p->validHMS = 1;
   14793   p->h = h;
   14794   p->m = m;
   14795   p->s = s + ms;
   14796   if( parseTimezone(zDate, p) ) return 1;
   14797   p->validTZ = (p->tz!=0)?1:0;
   14798   return 0;
   14799 }
   14800 
   14801 /*
   14802 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
   14803 ** that the YYYY-MM-DD is according to the Gregorian calendar.
   14804 **
   14805 ** Reference:  Meeus page 61
   14806 */
   14807 static void computeJD(DateTime *p){
   14808   int Y, M, D, A, B, X1, X2;
   14809 
   14810   if( p->validJD ) return;
   14811   if( p->validYMD ){
   14812     Y = p->Y;
   14813     M = p->M;
   14814     D = p->D;
   14815   }else{
   14816     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
   14817     M = 1;
   14818     D = 1;
   14819   }
   14820   if( M<=2 ){
   14821     Y--;
   14822     M += 12;
   14823   }
   14824   A = Y/100;
   14825   B = 2 - A + (A/4);
   14826   X1 = 36525*(Y+4716)/100;
   14827   X2 = 306001*(M+1)/10000;
   14828   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
   14829   p->validJD = 1;
   14830   if( p->validHMS ){
   14831     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
   14832     if( p->validTZ ){
   14833       p->iJD -= p->tz*60000;
   14834       p->validYMD = 0;
   14835       p->validHMS = 0;
   14836       p->validTZ = 0;
   14837     }
   14838   }
   14839 }
   14840 
   14841 /*
   14842 ** Parse dates of the form
   14843 **
   14844 **     YYYY-MM-DD HH:MM:SS.FFF
   14845 **     YYYY-MM-DD HH:MM:SS
   14846 **     YYYY-MM-DD HH:MM
   14847 **     YYYY-MM-DD
   14848 **
   14849 ** Write the result into the DateTime structure and return 0
   14850 ** on success and 1 if the input string is not a well-formed
   14851 ** date.
   14852 */
   14853 static int parseYyyyMmDd(const char *zDate, DateTime *p){
   14854   int Y, M, D, neg;
   14855 
   14856   if( zDate[0]=='-' ){
   14857     zDate++;
   14858     neg = 1;
   14859   }else{
   14860     neg = 0;
   14861   }
   14862   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
   14863     return 1;
   14864   }
   14865   zDate += 10;
   14866   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
   14867   if( parseHhMmSs(zDate, p)==0 ){
   14868     /* We got the time */
   14869   }else if( *zDate==0 ){
   14870     p->validHMS = 0;
   14871   }else{
   14872     return 1;
   14873   }
   14874   p->validJD = 0;
   14875   p->validYMD = 1;
   14876   p->Y = neg ? -Y : Y;
   14877   p->M = M;
   14878   p->D = D;
   14879   if( p->validTZ ){
   14880     computeJD(p);
   14881   }
   14882   return 0;
   14883 }
   14884 
   14885 /*
   14886 ** Set the time to the current time reported by the VFS.
   14887 **
   14888 ** Return the number of errors.
   14889 */
   14890 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
   14891   p->iJD = sqlite3StmtCurrentTime(context);
   14892   if( p->iJD>0 ){
   14893     p->validJD = 1;
   14894     return 0;
   14895   }else{
   14896     return 1;
   14897   }
   14898 }
   14899 
   14900 /*
   14901 ** Attempt to parse the given string into a Julian Day Number.  Return
   14902 ** the number of errors.
   14903 **
   14904 ** The following are acceptable forms for the input string:
   14905 **
   14906 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
   14907 **      DDDD.DD
   14908 **      now
   14909 **
   14910 ** In the first form, the +/-HH:MM is always optional.  The fractional
   14911 ** seconds extension (the ".FFF") is optional.  The seconds portion
   14912 ** (":SS.FFF") is option.  The year and date can be omitted as long
   14913 ** as there is a time string.  The time string can be omitted as long
   14914 ** as there is a year and date.
   14915 */
   14916 static int parseDateOrTime(
   14917   sqlite3_context *context,
   14918   const char *zDate,
   14919   DateTime *p
   14920 ){
   14921   double r;
   14922   if( parseYyyyMmDd(zDate,p)==0 ){
   14923     return 0;
   14924   }else if( parseHhMmSs(zDate, p)==0 ){
   14925     return 0;
   14926   }else if( sqlite3StrICmp(zDate,"now")==0){
   14927     return setDateTimeToCurrent(context, p);
   14928   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
   14929     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
   14930     p->validJD = 1;
   14931     return 0;
   14932   }
   14933   return 1;
   14934 }
   14935 
   14936 /*
   14937 ** Compute the Year, Month, and Day from the julian day number.
   14938 */
   14939 static void computeYMD(DateTime *p){
   14940   int Z, A, B, C, D, E, X1;
   14941   if( p->validYMD ) return;
   14942   if( !p->validJD ){
   14943     p->Y = 2000;
   14944     p->M = 1;
   14945     p->D = 1;
   14946   }else{
   14947     Z = (int)((p->iJD + 43200000)/86400000);
   14948     A = (int)((Z - 1867216.25)/36524.25);
   14949     A = Z + 1 + A - (A/4);
   14950     B = A + 1524;
   14951     C = (int)((B - 122.1)/365.25);
   14952     D = (36525*C)/100;
   14953     E = (int)((B-D)/30.6001);
   14954     X1 = (int)(30.6001*E);
   14955     p->D = B - D - X1;
   14956     p->M = E<14 ? E-1 : E-13;
   14957     p->Y = p->M>2 ? C - 4716 : C - 4715;
   14958   }
   14959   p->validYMD = 1;
   14960 }
   14961 
   14962 /*
   14963 ** Compute the Hour, Minute, and Seconds from the julian day number.
   14964 */
   14965 static void computeHMS(DateTime *p){
   14966   int s;
   14967   if( p->validHMS ) return;
   14968   computeJD(p);
   14969   s = (int)((p->iJD + 43200000) % 86400000);
   14970   p->s = s/1000.0;
   14971   s = (int)p->s;
   14972   p->s -= s;
   14973   p->h = s/3600;
   14974   s -= p->h*3600;
   14975   p->m = s/60;
   14976   p->s += s - p->m*60;
   14977   p->validHMS = 1;
   14978 }
   14979 
   14980 /*
   14981 ** Compute both YMD and HMS
   14982 */
   14983 static void computeYMD_HMS(DateTime *p){
   14984   computeYMD(p);
   14985   computeHMS(p);
   14986 }
   14987 
   14988 /*
   14989 ** Clear the YMD and HMS and the TZ
   14990 */
   14991 static void clearYMD_HMS_TZ(DateTime *p){
   14992   p->validYMD = 0;
   14993   p->validHMS = 0;
   14994   p->validTZ = 0;
   14995 }
   14996 
   14997 /*
   14998 ** On recent Windows platforms, the localtime_s() function is available
   14999 ** as part of the "Secure CRT". It is essentially equivalent to
   15000 ** localtime_r() available under most POSIX platforms, except that the
   15001 ** order of the parameters is reversed.
   15002 **
   15003 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
   15004 **
   15005 ** If the user has not indicated to use localtime_r() or localtime_s()
   15006 ** already, check for an MSVC build environment that provides
   15007 ** localtime_s().
   15008 */
   15009 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
   15010      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
   15011 #define HAVE_LOCALTIME_S 1
   15012 #endif
   15013 
   15014 #ifndef SQLITE_OMIT_LOCALTIME
   15015 /*
   15016 ** The following routine implements the rough equivalent of localtime_r()
   15017 ** using whatever operating-system specific localtime facility that
   15018 ** is available.  This routine returns 0 on success and
   15019 ** non-zero on any kind of error.
   15020 **
   15021 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
   15022 ** routine will always fail.
   15023 **
   15024 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
   15025 ** library function localtime_r() is used to assist in the calculation of
   15026 ** local time.
   15027 */
   15028 static int osLocaltime(time_t *t, struct tm *pTm){
   15029   int rc;
   15030 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
   15031       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
   15032   struct tm *pX;
   15033 #if SQLITE_THREADSAFE>0
   15034   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   15035 #endif
   15036   sqlite3_mutex_enter(mutex);
   15037   pX = localtime(t);
   15038 #ifndef SQLITE_OMIT_BUILTIN_TEST
   15039   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
   15040 #endif
   15041   if( pX ) *pTm = *pX;
   15042   sqlite3_mutex_leave(mutex);
   15043   rc = pX==0;
   15044 #else
   15045 #ifndef SQLITE_OMIT_BUILTIN_TEST
   15046   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
   15047 #endif
   15048 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
   15049   rc = localtime_r(t, pTm)==0;
   15050 #else
   15051   rc = localtime_s(pTm, t);
   15052 #endif /* HAVE_LOCALTIME_R */
   15053 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
   15054   return rc;
   15055 }
   15056 #endif /* SQLITE_OMIT_LOCALTIME */
   15057 
   15058 
   15059 #ifndef SQLITE_OMIT_LOCALTIME
   15060 /*
   15061 ** Compute the difference (in milliseconds) between localtime and UTC
   15062 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
   15063 ** return this value and set *pRc to SQLITE_OK.
   15064 **
   15065 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
   15066 ** is undefined in this case.
   15067 */
   15068 static sqlite3_int64 localtimeOffset(
   15069   DateTime *p,                    /* Date at which to calculate offset */
   15070   sqlite3_context *pCtx,          /* Write error here if one occurs */
   15071   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
   15072 ){
   15073   DateTime x, y;
   15074   time_t t;
   15075   struct tm sLocal;
   15076 
   15077   /* Initialize the contents of sLocal to avoid a compiler warning. */
   15078   memset(&sLocal, 0, sizeof(sLocal));
   15079 
   15080   x = *p;
   15081   computeYMD_HMS(&x);
   15082   if( x.Y<1971 || x.Y>=2038 ){
   15083     /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
   15084     ** works for years between 1970 and 2037. For dates outside this range,
   15085     ** SQLite attempts to map the year into an equivalent year within this
   15086     ** range, do the calculation, then map the year back.
   15087     */
   15088     x.Y = 2000;
   15089     x.M = 1;
   15090     x.D = 1;
   15091     x.h = 0;
   15092     x.m = 0;
   15093     x.s = 0.0;
   15094   } else {
   15095     int s = (int)(x.s + 0.5);
   15096     x.s = s;
   15097   }
   15098   x.tz = 0;
   15099   x.validJD = 0;
   15100   computeJD(&x);
   15101   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
   15102   if( osLocaltime(&t, &sLocal) ){
   15103     sqlite3_result_error(pCtx, "local time unavailable", -1);
   15104     *pRc = SQLITE_ERROR;
   15105     return 0;
   15106   }
   15107   y.Y = sLocal.tm_year + 1900;
   15108   y.M = sLocal.tm_mon + 1;
   15109   y.D = sLocal.tm_mday;
   15110   y.h = sLocal.tm_hour;
   15111   y.m = sLocal.tm_min;
   15112   y.s = sLocal.tm_sec;
   15113   y.validYMD = 1;
   15114   y.validHMS = 1;
   15115   y.validJD = 0;
   15116   y.validTZ = 0;
   15117   computeJD(&y);
   15118   *pRc = SQLITE_OK;
   15119   return y.iJD - x.iJD;
   15120 }
   15121 #endif /* SQLITE_OMIT_LOCALTIME */
   15122 
   15123 /*
   15124 ** Process a modifier to a date-time stamp.  The modifiers are
   15125 ** as follows:
   15126 **
   15127 **     NNN days
   15128 **     NNN hours
   15129 **     NNN minutes
   15130 **     NNN.NNNN seconds
   15131 **     NNN months
   15132 **     NNN years
   15133 **     start of month
   15134 **     start of year
   15135 **     start of week
   15136 **     start of day
   15137 **     weekday N
   15138 **     unixepoch
   15139 **     localtime
   15140 **     utc
   15141 **
   15142 ** Return 0 on success and 1 if there is any kind of error. If the error
   15143 ** is in a system call (i.e. localtime()), then an error message is written
   15144 ** to context pCtx. If the error is an unrecognized modifier, no error is
   15145 ** written to pCtx.
   15146 */
   15147 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
   15148   int rc = 1;
   15149   int n;
   15150   double r;
   15151   char *z, zBuf[30];
   15152   z = zBuf;
   15153   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
   15154     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
   15155   }
   15156   z[n] = 0;
   15157   switch( z[0] ){
   15158 #ifndef SQLITE_OMIT_LOCALTIME
   15159     case 'l': {
   15160       /*    localtime
   15161       **
   15162       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
   15163       ** show local time.
   15164       */
   15165       if( strcmp(z, "localtime")==0 ){
   15166         computeJD(p);
   15167         p->iJD += localtimeOffset(p, pCtx, &rc);
   15168         clearYMD_HMS_TZ(p);
   15169       }
   15170       break;
   15171     }
   15172 #endif
   15173     case 'u': {
   15174       /*
   15175       **    unixepoch
   15176       **
   15177       ** Treat the current value of p->iJD as the number of
   15178       ** seconds since 1970.  Convert to a real julian day number.
   15179       */
   15180       if( strcmp(z, "unixepoch")==0 && p->validJD ){
   15181         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
   15182         clearYMD_HMS_TZ(p);
   15183         rc = 0;
   15184       }
   15185 #ifndef SQLITE_OMIT_LOCALTIME
   15186       else if( strcmp(z, "utc")==0 ){
   15187         sqlite3_int64 c1;
   15188         computeJD(p);
   15189         c1 = localtimeOffset(p, pCtx, &rc);
   15190         if( rc==SQLITE_OK ){
   15191           p->iJD -= c1;
   15192           clearYMD_HMS_TZ(p);
   15193           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
   15194         }
   15195       }
   15196 #endif
   15197       break;
   15198     }
   15199     case 'w': {
   15200       /*
   15201       **    weekday N
   15202       **
   15203       ** Move the date to the same time on the next occurrence of
   15204       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
   15205       ** date is already on the appropriate weekday, this is a no-op.
   15206       */
   15207       if( strncmp(z, "weekday ", 8)==0
   15208                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
   15209                && (n=(int)r)==r && n>=0 && r<7 ){
   15210         sqlite3_int64 Z;
   15211         computeYMD_HMS(p);
   15212         p->validTZ = 0;
   15213         p->validJD = 0;
   15214         computeJD(p);
   15215         Z = ((p->iJD + 129600000)/86400000) % 7;
   15216         if( Z>n ) Z -= 7;
   15217         p->iJD += (n - Z)*86400000;
   15218         clearYMD_HMS_TZ(p);
   15219         rc = 0;
   15220       }
   15221       break;
   15222     }
   15223     case 's': {
   15224       /*
   15225       **    start of TTTTT
   15226       **
   15227       ** Move the date backwards to the beginning of the current day,
   15228       ** or month or year.
   15229       */
   15230       if( strncmp(z, "start of ", 9)!=0 ) break;
   15231       z += 9;
   15232       computeYMD(p);
   15233       p->validHMS = 1;
   15234       p->h = p->m = 0;
   15235       p->s = 0.0;
   15236       p->validTZ = 0;
   15237       p->validJD = 0;
   15238       if( strcmp(z,"month")==0 ){
   15239         p->D = 1;
   15240         rc = 0;
   15241       }else if( strcmp(z,"year")==0 ){
   15242         computeYMD(p);
   15243         p->M = 1;
   15244         p->D = 1;
   15245         rc = 0;
   15246       }else if( strcmp(z,"day")==0 ){
   15247         rc = 0;
   15248       }
   15249       break;
   15250     }
   15251     case '+':
   15252     case '-':
   15253     case '0':
   15254     case '1':
   15255     case '2':
   15256     case '3':
   15257     case '4':
   15258     case '5':
   15259     case '6':
   15260     case '7':
   15261     case '8':
   15262     case '9': {
   15263       double rRounder;
   15264       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
   15265       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
   15266         rc = 1;
   15267         break;
   15268       }
   15269       if( z[n]==':' ){
   15270         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
   15271         ** specified number of hours, minutes, seconds, and fractional seconds
   15272         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
   15273         ** omitted.
   15274         */
   15275         const char *z2 = z;
   15276         DateTime tx;
   15277         sqlite3_int64 day;
   15278         if( !sqlite3Isdigit(*z2) ) z2++;
   15279         memset(&tx, 0, sizeof(tx));
   15280         if( parseHhMmSs(z2, &tx) ) break;
   15281         computeJD(&tx);
   15282         tx.iJD -= 43200000;
   15283         day = tx.iJD/86400000;
   15284         tx.iJD -= day*86400000;
   15285         if( z[0]=='-' ) tx.iJD = -tx.iJD;
   15286         computeJD(p);
   15287         clearYMD_HMS_TZ(p);
   15288         p->iJD += tx.iJD;
   15289         rc = 0;
   15290         break;
   15291       }
   15292       z += n;
   15293       while( sqlite3Isspace(*z) ) z++;
   15294       n = sqlite3Strlen30(z);
   15295       if( n>10 || n<3 ) break;
   15296       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
   15297       computeJD(p);
   15298       rc = 0;
   15299       rRounder = r<0 ? -0.5 : +0.5;
   15300       if( n==3 && strcmp(z,"day")==0 ){
   15301         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
   15302       }else if( n==4 && strcmp(z,"hour")==0 ){
   15303         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
   15304       }else if( n==6 && strcmp(z,"minute")==0 ){
   15305         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
   15306       }else if( n==6 && strcmp(z,"second")==0 ){
   15307         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
   15308       }else if( n==5 && strcmp(z,"month")==0 ){
   15309         int x, y;
   15310         computeYMD_HMS(p);
   15311         p->M += (int)r;
   15312         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
   15313         p->Y += x;
   15314         p->M -= x*12;
   15315         p->validJD = 0;
   15316         computeJD(p);
   15317         y = (int)r;
   15318         if( y!=r ){
   15319           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
   15320         }
   15321       }else if( n==4 && strcmp(z,"year")==0 ){
   15322         int y = (int)r;
   15323         computeYMD_HMS(p);
   15324         p->Y += y;
   15325         p->validJD = 0;
   15326         computeJD(p);
   15327         if( y!=r ){
   15328           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
   15329         }
   15330       }else{
   15331         rc = 1;
   15332       }
   15333       clearYMD_HMS_TZ(p);
   15334       break;
   15335     }
   15336     default: {
   15337       break;
   15338     }
   15339   }
   15340   return rc;
   15341 }
   15342 
   15343 /*
   15344 ** Process time function arguments.  argv[0] is a date-time stamp.
   15345 ** argv[1] and following are modifiers.  Parse them all and write
   15346 ** the resulting time into the DateTime structure p.  Return 0
   15347 ** on success and 1 if there are any errors.
   15348 **
   15349 ** If there are zero parameters (if even argv[0] is undefined)
   15350 ** then assume a default value of "now" for argv[0].
   15351 */
   15352 static int isDate(
   15353   sqlite3_context *context,
   15354   int argc,
   15355   sqlite3_value **argv,
   15356   DateTime *p
   15357 ){
   15358   int i;
   15359   const unsigned char *z;
   15360   int eType;
   15361   memset(p, 0, sizeof(*p));
   15362   if( argc==0 ){
   15363     return setDateTimeToCurrent(context, p);
   15364   }
   15365   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
   15366                    || eType==SQLITE_INTEGER ){
   15367     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
   15368     p->validJD = 1;
   15369   }else{
   15370     z = sqlite3_value_text(argv[0]);
   15371     if( !z || parseDateOrTime(context, (char*)z, p) ){
   15372       return 1;
   15373     }
   15374   }
   15375   for(i=1; i<argc; i++){
   15376     z = sqlite3_value_text(argv[i]);
   15377     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
   15378   }
   15379   return 0;
   15380 }
   15381 
   15382 
   15383 /*
   15384 ** The following routines implement the various date and time functions
   15385 ** of SQLite.
   15386 */
   15387 
   15388 /*
   15389 **    julianday( TIMESTRING, MOD, MOD, ...)
   15390 **
   15391 ** Return the julian day number of the date specified in the arguments
   15392 */
   15393 static void juliandayFunc(
   15394   sqlite3_context *context,
   15395   int argc,
   15396   sqlite3_value **argv
   15397 ){
   15398   DateTime x;
   15399   if( isDate(context, argc, argv, &x)==0 ){
   15400     computeJD(&x);
   15401     sqlite3_result_double(context, x.iJD/86400000.0);
   15402   }
   15403 }
   15404 
   15405 /*
   15406 **    datetime( TIMESTRING, MOD, MOD, ...)
   15407 **
   15408 ** Return YYYY-MM-DD HH:MM:SS
   15409 */
   15410 static void datetimeFunc(
   15411   sqlite3_context *context,
   15412   int argc,
   15413   sqlite3_value **argv
   15414 ){
   15415   DateTime x;
   15416   if( isDate(context, argc, argv, &x)==0 ){
   15417     char zBuf[100];
   15418     computeYMD_HMS(&x);
   15419     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
   15420                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
   15421     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   15422   }
   15423 }
   15424 
   15425 /*
   15426 **    time( TIMESTRING, MOD, MOD, ...)
   15427 **
   15428 ** Return HH:MM:SS
   15429 */
   15430 static void timeFunc(
   15431   sqlite3_context *context,
   15432   int argc,
   15433   sqlite3_value **argv
   15434 ){
   15435   DateTime x;
   15436   if( isDate(context, argc, argv, &x)==0 ){
   15437     char zBuf[100];
   15438     computeHMS(&x);
   15439     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
   15440     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   15441   }
   15442 }
   15443 
   15444 /*
   15445 **    date( TIMESTRING, MOD, MOD, ...)
   15446 **
   15447 ** Return YYYY-MM-DD
   15448 */
   15449 static void dateFunc(
   15450   sqlite3_context *context,
   15451   int argc,
   15452   sqlite3_value **argv
   15453 ){
   15454   DateTime x;
   15455   if( isDate(context, argc, argv, &x)==0 ){
   15456     char zBuf[100];
   15457     computeYMD(&x);
   15458     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
   15459     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   15460   }
   15461 }
   15462 
   15463 /*
   15464 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
   15465 **
   15466 ** Return a string described by FORMAT.  Conversions as follows:
   15467 **
   15468 **   %d  day of month
   15469 **   %f  ** fractional seconds  SS.SSS
   15470 **   %H  hour 00-24
   15471 **   %j  day of year 000-366
   15472 **   %J  ** Julian day number
   15473 **   %m  month 01-12
   15474 **   %M  minute 00-59
   15475 **   %s  seconds since 1970-01-01
   15476 **   %S  seconds 00-59
   15477 **   %w  day of week 0-6  sunday==0
   15478 **   %W  week of year 00-53
   15479 **   %Y  year 0000-9999
   15480 **   %%  %
   15481 */
   15482 static void strftimeFunc(
   15483   sqlite3_context *context,
   15484   int argc,
   15485   sqlite3_value **argv
   15486 ){
   15487   DateTime x;
   15488   u64 n;
   15489   size_t i,j;
   15490   char *z;
   15491   sqlite3 *db;
   15492   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
   15493   char zBuf[100];
   15494   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
   15495   db = sqlite3_context_db_handle(context);
   15496   for(i=0, n=1; zFmt[i]; i++, n++){
   15497     if( zFmt[i]=='%' ){
   15498       switch( zFmt[i+1] ){
   15499         case 'd':
   15500         case 'H':
   15501         case 'm':
   15502         case 'M':
   15503         case 'S':
   15504         case 'W':
   15505           n++;
   15506           /* fall thru */
   15507         case 'w':
   15508         case '%':
   15509           break;
   15510         case 'f':
   15511           n += 8;
   15512           break;
   15513         case 'j':
   15514           n += 3;
   15515           break;
   15516         case 'Y':
   15517           n += 8;
   15518           break;
   15519         case 's':
   15520         case 'J':
   15521           n += 50;
   15522           break;
   15523         default:
   15524           return;  /* ERROR.  return a NULL */
   15525       }
   15526       i++;
   15527     }
   15528   }
   15529   testcase( n==sizeof(zBuf)-1 );
   15530   testcase( n==sizeof(zBuf) );
   15531   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   15532   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
   15533   if( n<sizeof(zBuf) ){
   15534     z = zBuf;
   15535   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   15536     sqlite3_result_error_toobig(context);
   15537     return;
   15538   }else{
   15539     z = sqlite3DbMallocRaw(db, (int)n);
   15540     if( z==0 ){
   15541       sqlite3_result_error_nomem(context);
   15542       return;
   15543     }
   15544   }
   15545   computeJD(&x);
   15546   computeYMD_HMS(&x);
   15547   for(i=j=0; zFmt[i]; i++){
   15548     if( zFmt[i]!='%' ){
   15549       z[j++] = zFmt[i];
   15550     }else{
   15551       i++;
   15552       switch( zFmt[i] ){
   15553         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
   15554         case 'f': {
   15555           double s = x.s;
   15556           if( s>59.999 ) s = 59.999;
   15557           sqlite3_snprintf(7, &z[j],"%06.3f", s);
   15558           j += sqlite3Strlen30(&z[j]);
   15559           break;
   15560         }
   15561         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
   15562         case 'W': /* Fall thru */
   15563         case 'j': {
   15564           int nDay;             /* Number of days since 1st day of year */
   15565           DateTime y = x;
   15566           y.validJD = 0;
   15567           y.M = 1;
   15568           y.D = 1;
   15569           computeJD(&y);
   15570           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
   15571           if( zFmt[i]=='W' ){
   15572             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
   15573             wd = (int)(((x.iJD+43200000)/86400000)%7);
   15574             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
   15575             j += 2;
   15576           }else{
   15577             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
   15578             j += 3;
   15579           }
   15580           break;
   15581         }
   15582         case 'J': {
   15583           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
   15584           j+=sqlite3Strlen30(&z[j]);
   15585           break;
   15586         }
   15587         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
   15588         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
   15589         case 's': {
   15590           sqlite3_snprintf(30,&z[j],"%lld",
   15591                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
   15592           j += sqlite3Strlen30(&z[j]);
   15593           break;
   15594         }
   15595         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
   15596         case 'w': {
   15597           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
   15598           break;
   15599         }
   15600         case 'Y': {
   15601           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
   15602           break;
   15603         }
   15604         default:   z[j++] = '%'; break;
   15605       }
   15606     }
   15607   }
   15608   z[j] = 0;
   15609   sqlite3_result_text(context, z, -1,
   15610                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
   15611 }
   15612 
   15613 /*
   15614 ** current_time()
   15615 **
   15616 ** This function returns the same value as time('now').
   15617 */
   15618 static void ctimeFunc(
   15619   sqlite3_context *context,
   15620   int NotUsed,
   15621   sqlite3_value **NotUsed2
   15622 ){
   15623   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   15624   timeFunc(context, 0, 0);
   15625 }
   15626 
   15627 /*
   15628 ** current_date()
   15629 **
   15630 ** This function returns the same value as date('now').
   15631 */
   15632 static void cdateFunc(
   15633   sqlite3_context *context,
   15634   int NotUsed,
   15635   sqlite3_value **NotUsed2
   15636 ){
   15637   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   15638   dateFunc(context, 0, 0);
   15639 }
   15640 
   15641 /*
   15642 ** current_timestamp()
   15643 **
   15644 ** This function returns the same value as datetime('now').
   15645 */
   15646 static void ctimestampFunc(
   15647   sqlite3_context *context,
   15648   int NotUsed,
   15649   sqlite3_value **NotUsed2
   15650 ){
   15651   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   15652   datetimeFunc(context, 0, 0);
   15653 }
   15654 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
   15655 
   15656 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   15657 /*
   15658 ** If the library is compiled to omit the full-scale date and time
   15659 ** handling (to get a smaller binary), the following minimal version
   15660 ** of the functions current_time(), current_date() and current_timestamp()
   15661 ** are included instead. This is to support column declarations that
   15662 ** include "DEFAULT CURRENT_TIME" etc.
   15663 **
   15664 ** This function uses the C-library functions time(), gmtime()
   15665 ** and strftime(). The format string to pass to strftime() is supplied
   15666 ** as the user-data for the function.
   15667 */
   15668 static void currentTimeFunc(
   15669   sqlite3_context *context,
   15670   int argc,
   15671   sqlite3_value **argv
   15672 ){
   15673   time_t t;
   15674   char *zFormat = (char *)sqlite3_user_data(context);
   15675   sqlite3 *db;
   15676   sqlite3_int64 iT;
   15677   struct tm *pTm;
   15678   struct tm sNow;
   15679   char zBuf[20];
   15680 
   15681   UNUSED_PARAMETER(argc);
   15682   UNUSED_PARAMETER(argv);
   15683 
   15684   iT = sqlite3StmtCurrentTime(context);
   15685   if( iT<=0 ) return;
   15686   t = iT/1000 - 10000*(sqlite3_int64)21086676;
   15687 #ifdef HAVE_GMTIME_R
   15688   pTm = gmtime_r(&t, &sNow);
   15689 #else
   15690   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   15691   pTm = gmtime(&t);
   15692   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
   15693   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   15694 #endif
   15695   if( pTm ){
   15696     strftime(zBuf, 20, zFormat, &sNow);
   15697     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   15698   }
   15699 }
   15700 #endif
   15701 
   15702 /*
   15703 ** This function registered all of the above C functions as SQL
   15704 ** functions.  This should be the only routine in this file with
   15705 ** external linkage.
   15706 */
   15707 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
   15708   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
   15709 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   15710     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
   15711     FUNCTION(date,             -1, 0, 0, dateFunc      ),
   15712     FUNCTION(time,             -1, 0, 0, timeFunc      ),
   15713     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
   15714     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
   15715     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
   15716     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
   15717     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
   15718 #else
   15719     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
   15720     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
   15721     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
   15722 #endif
   15723   };
   15724   int i;
   15725   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   15726   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
   15727 
   15728   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
   15729     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   15730   }
   15731 }
   15732 
   15733 /************** End of date.c ************************************************/
   15734 /************** Begin file os.c **********************************************/
   15735 /*
   15736 ** 2005 November 29
   15737 **
   15738 ** The author disclaims copyright to this source code.  In place of
   15739 ** a legal notice, here is a blessing:
   15740 **
   15741 **    May you do good and not evil.
   15742 **    May you find forgiveness for yourself and forgive others.
   15743 **    May you share freely, never taking more than you give.
   15744 **
   15745 ******************************************************************************
   15746 **
   15747 ** This file contains OS interface code that is common to all
   15748 ** architectures.
   15749 */
   15750 #define _SQLITE_OS_C_ 1
   15751 #undef _SQLITE_OS_C_
   15752 
   15753 /*
   15754 ** The default SQLite sqlite3_vfs implementations do not allocate
   15755 ** memory (actually, os_unix.c allocates a small amount of memory
   15756 ** from within OsOpen()), but some third-party implementations may.
   15757 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
   15758 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
   15759 **
   15760 ** The following functions are instrumented for malloc() failure
   15761 ** testing:
   15762 **
   15763 **     sqlite3OsRead()
   15764 **     sqlite3OsWrite()
   15765 **     sqlite3OsSync()
   15766 **     sqlite3OsFileSize()
   15767 **     sqlite3OsLock()
   15768 **     sqlite3OsCheckReservedLock()
   15769 **     sqlite3OsFileControl()
   15770 **     sqlite3OsShmMap()
   15771 **     sqlite3OsOpen()
   15772 **     sqlite3OsDelete()
   15773 **     sqlite3OsAccess()
   15774 **     sqlite3OsFullPathname()
   15775 **
   15776 */
   15777 #if defined(SQLITE_TEST)
   15778 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
   15779   #define DO_OS_MALLOC_TEST(x)                                       \
   15780   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
   15781     void *pTstAlloc = sqlite3Malloc(10);                             \
   15782     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
   15783     sqlite3_free(pTstAlloc);                                         \
   15784   }
   15785 #else
   15786   #define DO_OS_MALLOC_TEST(x)
   15787 #endif
   15788 
   15789 /*
   15790 ** The following routines are convenience wrappers around methods
   15791 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
   15792 ** of this would be completely automatic if SQLite were coded using
   15793 ** C++ instead of plain old C.
   15794 */
   15795 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
   15796   int rc = SQLITE_OK;
   15797   if( pId->pMethods ){
   15798     rc = pId->pMethods->xClose(pId);
   15799     pId->pMethods = 0;
   15800   }
   15801   return rc;
   15802 }
   15803 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
   15804   DO_OS_MALLOC_TEST(id);
   15805   return id->pMethods->xRead(id, pBuf, amt, offset);
   15806 }
   15807 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
   15808   DO_OS_MALLOC_TEST(id);
   15809   return id->pMethods->xWrite(id, pBuf, amt, offset);
   15810 }
   15811 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
   15812   return id->pMethods->xTruncate(id, size);
   15813 }
   15814 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
   15815   DO_OS_MALLOC_TEST(id);
   15816   return id->pMethods->xSync(id, flags);
   15817 }
   15818 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
   15819   DO_OS_MALLOC_TEST(id);
   15820   return id->pMethods->xFileSize(id, pSize);
   15821 }
   15822 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
   15823   DO_OS_MALLOC_TEST(id);
   15824   return id->pMethods->xLock(id, lockType);
   15825 }
   15826 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
   15827   return id->pMethods->xUnlock(id, lockType);
   15828 }
   15829 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
   15830   DO_OS_MALLOC_TEST(id);
   15831   return id->pMethods->xCheckReservedLock(id, pResOut);
   15832 }
   15833 
   15834 /*
   15835 ** Use sqlite3OsFileControl() when we are doing something that might fail
   15836 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
   15837 ** when simply tossing information over the wall to the VFS and we do not
   15838 ** really care if the VFS receives and understands the information since it
   15839 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
   15840 ** routine has no return value since the return value would be meaningless.
   15841 */
   15842 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
   15843 #ifdef SQLITE_TEST
   15844   if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
   15845     /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
   15846     ** is using a regular VFS, it is called after the corresponding
   15847     ** transaction has been committed. Injecting a fault at this point
   15848     ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
   15849     ** but the transaction is committed anyway.
   15850     **
   15851     ** The core must call OsFileControl() though, not OsFileControlHint(),
   15852     ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
   15853     ** means the commit really has failed and an error should be returned
   15854     ** to the user.  */
   15855     DO_OS_MALLOC_TEST(id);
   15856   }
   15857 #endif
   15858   return id->pMethods->xFileControl(id, op, pArg);
   15859 }
   15860 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
   15861   (void)id->pMethods->xFileControl(id, op, pArg);
   15862 }
   15863 
   15864 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
   15865   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
   15866   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
   15867 }
   15868 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
   15869   return id->pMethods->xDeviceCharacteristics(id);
   15870 }
   15871 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
   15872   return id->pMethods->xShmLock(id, offset, n, flags);
   15873 }
   15874 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
   15875   id->pMethods->xShmBarrier(id);
   15876 }
   15877 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
   15878   return id->pMethods->xShmUnmap(id, deleteFlag);
   15879 }
   15880 SQLITE_PRIVATE int sqlite3OsShmMap(
   15881   sqlite3_file *id,               /* Database file handle */
   15882   int iPage,
   15883   int pgsz,
   15884   int bExtend,                    /* True to extend file if necessary */
   15885   void volatile **pp              /* OUT: Pointer to mapping */
   15886 ){
   15887   DO_OS_MALLOC_TEST(id);
   15888   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
   15889 }
   15890 
   15891 #if SQLITE_MAX_MMAP_SIZE>0
   15892 /* The real implementation of xFetch and xUnfetch */
   15893 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
   15894   DO_OS_MALLOC_TEST(id);
   15895   return id->pMethods->xFetch(id, iOff, iAmt, pp);
   15896 }
   15897 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
   15898   return id->pMethods->xUnfetch(id, iOff, p);
   15899 }
   15900 #else
   15901 /* No-op stubs to use when memory-mapped I/O is disabled */
   15902 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
   15903   *pp = 0;
   15904   return SQLITE_OK;
   15905 }
   15906 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
   15907   return SQLITE_OK;
   15908 }
   15909 #endif
   15910 
   15911 /*
   15912 ** The next group of routines are convenience wrappers around the
   15913 ** VFS methods.
   15914 */
   15915 SQLITE_PRIVATE int sqlite3OsOpen(
   15916   sqlite3_vfs *pVfs,
   15917   const char *zPath,
   15918   sqlite3_file *pFile,
   15919   int flags,
   15920   int *pFlagsOut
   15921 ){
   15922   int rc;
   15923   DO_OS_MALLOC_TEST(0);
   15924   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
   15925   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
   15926   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
   15927   ** reaching the VFS. */
   15928   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
   15929   assert( rc==SQLITE_OK || pFile->pMethods==0 );
   15930   return rc;
   15931 }
   15932 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   15933   DO_OS_MALLOC_TEST(0);
   15934   assert( dirSync==0 || dirSync==1 );
   15935   return pVfs->xDelete(pVfs, zPath, dirSync);
   15936 }
   15937 SQLITE_PRIVATE int sqlite3OsAccess(
   15938   sqlite3_vfs *pVfs,
   15939   const char *zPath,
   15940   int flags,
   15941   int *pResOut
   15942 ){
   15943   DO_OS_MALLOC_TEST(0);
   15944   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
   15945 }
   15946 SQLITE_PRIVATE int sqlite3OsFullPathname(
   15947   sqlite3_vfs *pVfs,
   15948   const char *zPath,
   15949   int nPathOut,
   15950   char *zPathOut
   15951 ){
   15952   DO_OS_MALLOC_TEST(0);
   15953   zPathOut[0] = 0;
   15954   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
   15955 }
   15956 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   15957 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   15958   return pVfs->xDlOpen(pVfs, zPath);
   15959 }
   15960 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   15961   pVfs->xDlError(pVfs, nByte, zBufOut);
   15962 }
   15963 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
   15964   return pVfs->xDlSym(pVfs, pHdle, zSym);
   15965 }
   15966 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
   15967   pVfs->xDlClose(pVfs, pHandle);
   15968 }
   15969 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   15970 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   15971   return pVfs->xRandomness(pVfs, nByte, zBufOut);
   15972 }
   15973 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
   15974   return pVfs->xSleep(pVfs, nMicro);
   15975 }
   15976 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
   15977   int rc;
   15978   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
   15979   ** method to get the current date and time if that method is available
   15980   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
   15981   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
   15982   ** unavailable.
   15983   */
   15984   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
   15985     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
   15986   }else{
   15987     double r;
   15988     rc = pVfs->xCurrentTime(pVfs, &r);
   15989     *pTimeOut = (sqlite3_int64)(r*86400000.0);
   15990   }
   15991   return rc;
   15992 }
   15993 
   15994 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
   15995   sqlite3_vfs *pVfs,
   15996   const char *zFile,
   15997   sqlite3_file **ppFile,
   15998   int flags,
   15999   int *pOutFlags
   16000 ){
   16001   int rc = SQLITE_NOMEM;
   16002   sqlite3_file *pFile;
   16003   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
   16004   if( pFile ){
   16005     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
   16006     if( rc!=SQLITE_OK ){
   16007       sqlite3_free(pFile);
   16008     }else{
   16009       *ppFile = pFile;
   16010     }
   16011   }
   16012   return rc;
   16013 }
   16014 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
   16015   int rc = SQLITE_OK;
   16016   assert( pFile );
   16017   rc = sqlite3OsClose(pFile);
   16018   sqlite3_free(pFile);
   16019   return rc;
   16020 }
   16021 
   16022 /*
   16023 ** This function is a wrapper around the OS specific implementation of
   16024 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
   16025 ** ability to simulate a malloc failure, so that the handling of an
   16026 ** error in sqlite3_os_init() by the upper layers can be tested.
   16027 */
   16028 SQLITE_PRIVATE int sqlite3OsInit(void){
   16029   void *p = sqlite3_malloc(10);
   16030   if( p==0 ) return SQLITE_NOMEM;
   16031   sqlite3_free(p);
   16032   return sqlite3_os_init();
   16033 }
   16034 
   16035 /*
   16036 ** The list of all registered VFS implementations.
   16037 */
   16038 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
   16039 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
   16040 
   16041 /*
   16042 ** Locate a VFS by name.  If no name is given, simply return the
   16043 ** first VFS on the list.
   16044 */
   16045 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
   16046   sqlite3_vfs *pVfs = 0;
   16047 #if SQLITE_THREADSAFE
   16048   sqlite3_mutex *mutex;
   16049 #endif
   16050 #ifndef SQLITE_OMIT_AUTOINIT
   16051   int rc = sqlite3_initialize();
   16052   if( rc ) return 0;
   16053 #endif
   16054 #if SQLITE_THREADSAFE
   16055   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   16056 #endif
   16057   sqlite3_mutex_enter(mutex);
   16058   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
   16059     if( zVfs==0 ) break;
   16060     if( strcmp(zVfs, pVfs->zName)==0 ) break;
   16061   }
   16062   sqlite3_mutex_leave(mutex);
   16063   return pVfs;
   16064 }
   16065 
   16066 /*
   16067 ** Unlink a VFS from the linked list
   16068 */
   16069 static void vfsUnlink(sqlite3_vfs *pVfs){
   16070   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
   16071   if( pVfs==0 ){
   16072     /* No-op */
   16073   }else if( vfsList==pVfs ){
   16074     vfsList = pVfs->pNext;
   16075   }else if( vfsList ){
   16076     sqlite3_vfs *p = vfsList;
   16077     while( p->pNext && p->pNext!=pVfs ){
   16078       p = p->pNext;
   16079     }
   16080     if( p->pNext==pVfs ){
   16081       p->pNext = pVfs->pNext;
   16082     }
   16083   }
   16084 }
   16085 
   16086 /*
   16087 ** Register a VFS with the system.  It is harmless to register the same
   16088 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
   16089 ** true.
   16090 */
   16091 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
   16092   MUTEX_LOGIC(sqlite3_mutex *mutex;)
   16093 #ifndef SQLITE_OMIT_AUTOINIT
   16094   int rc = sqlite3_initialize();
   16095   if( rc ) return rc;
   16096 #endif
   16097   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   16098   sqlite3_mutex_enter(mutex);
   16099   vfsUnlink(pVfs);
   16100   if( makeDflt || vfsList==0 ){
   16101     pVfs->pNext = vfsList;
   16102     vfsList = pVfs;
   16103   }else{
   16104     pVfs->pNext = vfsList->pNext;
   16105     vfsList->pNext = pVfs;
   16106   }
   16107   assert(vfsList);
   16108   sqlite3_mutex_leave(mutex);
   16109   return SQLITE_OK;
   16110 }
   16111 
   16112 /*
   16113 ** Unregister a VFS so that it is no longer accessible.
   16114 */
   16115 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
   16116 #if SQLITE_THREADSAFE
   16117   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   16118 #endif
   16119   sqlite3_mutex_enter(mutex);
   16120   vfsUnlink(pVfs);
   16121   sqlite3_mutex_leave(mutex);
   16122   return SQLITE_OK;
   16123 }
   16124 
   16125 /************** End of os.c **************************************************/
   16126 /************** Begin file fault.c *******************************************/
   16127 /*
   16128 ** 2008 Jan 22
   16129 **
   16130 ** The author disclaims copyright to this source code.  In place of
   16131 ** a legal notice, here is a blessing:
   16132 **
   16133 **    May you do good and not evil.
   16134 **    May you find forgiveness for yourself and forgive others.
   16135 **    May you share freely, never taking more than you give.
   16136 **
   16137 *************************************************************************
   16138 **
   16139 ** This file contains code to support the concept of "benign"
   16140 ** malloc failures (when the xMalloc() or xRealloc() method of the
   16141 ** sqlite3_mem_methods structure fails to allocate a block of memory
   16142 ** and returns 0).
   16143 **
   16144 ** Most malloc failures are non-benign. After they occur, SQLite
   16145 ** abandons the current operation and returns an error code (usually
   16146 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
   16147 ** fatal. For example, if a malloc fails while resizing a hash table, this
   16148 ** is completely recoverable simply by not carrying out the resize. The
   16149 ** hash table will continue to function normally.  So a malloc failure
   16150 ** during a hash table resize is a benign fault.
   16151 */
   16152 
   16153 
   16154 #ifndef SQLITE_OMIT_BUILTIN_TEST
   16155 
   16156 /*
   16157 ** Global variables.
   16158 */
   16159 typedef struct BenignMallocHooks BenignMallocHooks;
   16160 static SQLITE_WSD struct BenignMallocHooks {
   16161   void (*xBenignBegin)(void);
   16162   void (*xBenignEnd)(void);
   16163 } sqlite3Hooks = { 0, 0 };
   16164 
   16165 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
   16166 ** structure.  If writable static data is unsupported on the target,
   16167 ** we have to locate the state vector at run-time.  In the more common
   16168 ** case where writable static data is supported, wsdHooks can refer directly
   16169 ** to the "sqlite3Hooks" state vector declared above.
   16170 */
   16171 #ifdef SQLITE_OMIT_WSD
   16172 # define wsdHooksInit \
   16173   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
   16174 # define wsdHooks x[0]
   16175 #else
   16176 # define wsdHooksInit
   16177 # define wsdHooks sqlite3Hooks
   16178 #endif
   16179 
   16180 
   16181 /*
   16182 ** Register hooks to call when sqlite3BeginBenignMalloc() and
   16183 ** sqlite3EndBenignMalloc() are called, respectively.
   16184 */
   16185 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
   16186   void (*xBenignBegin)(void),
   16187   void (*xBenignEnd)(void)
   16188 ){
   16189   wsdHooksInit;
   16190   wsdHooks.xBenignBegin = xBenignBegin;
   16191   wsdHooks.xBenignEnd = xBenignEnd;
   16192 }
   16193 
   16194 /*
   16195 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
   16196 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
   16197 ** indicates that subsequent malloc failures are non-benign.
   16198 */
   16199 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
   16200   wsdHooksInit;
   16201   if( wsdHooks.xBenignBegin ){
   16202     wsdHooks.xBenignBegin();
   16203   }
   16204 }
   16205 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
   16206   wsdHooksInit;
   16207   if( wsdHooks.xBenignEnd ){
   16208     wsdHooks.xBenignEnd();
   16209   }
   16210 }
   16211 
   16212 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
   16213 
   16214 /************** End of fault.c ***********************************************/
   16215 /************** Begin file mem0.c ********************************************/
   16216 /*
   16217 ** 2008 October 28
   16218 **
   16219 ** The author disclaims copyright to this source code.  In place of
   16220 ** a legal notice, here is a blessing:
   16221 **
   16222 **    May you do good and not evil.
   16223 **    May you find forgiveness for yourself and forgive others.
   16224 **    May you share freely, never taking more than you give.
   16225 **
   16226 *************************************************************************
   16227 **
   16228 ** This file contains a no-op memory allocation drivers for use when
   16229 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
   16230 ** here always fail.  SQLite will not operate with these drivers.  These
   16231 ** are merely placeholders.  Real drivers must be substituted using
   16232 ** sqlite3_config() before SQLite will operate.
   16233 */
   16234 
   16235 /*
   16236 ** This version of the memory allocator is the default.  It is
   16237 ** used when no other memory allocator is specified using compile-time
   16238 ** macros.
   16239 */
   16240 #ifdef SQLITE_ZERO_MALLOC
   16241 
   16242 /*
   16243 ** No-op versions of all memory allocation routines
   16244 */
   16245 static void *sqlite3MemMalloc(int nByte){ return 0; }
   16246 static void sqlite3MemFree(void *pPrior){ return; }
   16247 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
   16248 static int sqlite3MemSize(void *pPrior){ return 0; }
   16249 static int sqlite3MemRoundup(int n){ return n; }
   16250 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
   16251 static void sqlite3MemShutdown(void *NotUsed){ return; }
   16252 
   16253 /*
   16254 ** This routine is the only routine in this file with external linkage.
   16255 **
   16256 ** Populate the low-level memory allocation function pointers in
   16257 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   16258 */
   16259 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   16260   static const sqlite3_mem_methods defaultMethods = {
   16261      sqlite3MemMalloc,
   16262      sqlite3MemFree,
   16263      sqlite3MemRealloc,
   16264      sqlite3MemSize,
   16265      sqlite3MemRoundup,
   16266      sqlite3MemInit,
   16267      sqlite3MemShutdown,
   16268      0
   16269   };
   16270   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   16271 }
   16272 
   16273 #endif /* SQLITE_ZERO_MALLOC */
   16274 
   16275 /************** End of mem0.c ************************************************/
   16276 /************** Begin file mem1.c ********************************************/
   16277 /*
   16278 ** 2007 August 14
   16279 **
   16280 ** The author disclaims copyright to this source code.  In place of
   16281 ** a legal notice, here is a blessing:
   16282 **
   16283 **    May you do good and not evil.
   16284 **    May you find forgiveness for yourself and forgive others.
   16285 **    May you share freely, never taking more than you give.
   16286 **
   16287 *************************************************************************
   16288 **
   16289 ** This file contains low-level memory allocation drivers for when
   16290 ** SQLite will use the standard C-library malloc/realloc/free interface
   16291 ** to obtain the memory it needs.
   16292 **
   16293 ** This file contains implementations of the low-level memory allocation
   16294 ** routines specified in the sqlite3_mem_methods object.  The content of
   16295 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
   16296 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
   16297 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
   16298 ** default configuration is to use memory allocation routines in this
   16299 ** file.
   16300 **
   16301 ** C-preprocessor macro summary:
   16302 **
   16303 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
   16304 **                                the malloc_usable_size() interface exists
   16305 **                                on the target platform.  Or, this symbol
   16306 **                                can be set manually, if desired.
   16307 **                                If an equivalent interface exists by
   16308 **                                a different name, using a separate -D
   16309 **                                option to rename it.
   16310 **
   16311 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
   16312 **                                memory allocator.  Set this symbol to enable
   16313 **                                building on older macs.
   16314 **
   16315 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
   16316 **                                _msize() on windows systems.  This might
   16317 **                                be necessary when compiling for Delphi,
   16318 **                                for example.
   16319 */
   16320 
   16321 /*
   16322 ** This version of the memory allocator is the default.  It is
   16323 ** used when no other memory allocator is specified using compile-time
   16324 ** macros.
   16325 */
   16326 #ifdef SQLITE_SYSTEM_MALLOC
   16327 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
   16328 
   16329 /*
   16330 ** Use the zone allocator available on apple products unless the
   16331 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
   16332 */
   16333 #include <sys/sysctl.h>
   16334 #include <malloc/malloc.h>
   16335 #include <libkern/OSAtomic.h>
   16336 static malloc_zone_t* _sqliteZone_;
   16337 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
   16338 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
   16339 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
   16340 #define SQLITE_MALLOCSIZE(x) \
   16341         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
   16342 
   16343 #else /* if not __APPLE__ */
   16344 
   16345 /*
   16346 ** Use standard C library malloc and free on non-Apple systems.
   16347 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
   16348 */
   16349 #define SQLITE_MALLOC(x)             malloc(x)
   16350 #define SQLITE_FREE(x)               free(x)
   16351 #define SQLITE_REALLOC(x,y)          realloc((x),(y))
   16352 
   16353 /*
   16354 ** The malloc.h header file is needed for malloc_usable_size() function
   16355 ** on some systems (e.g. Linux).
   16356 */
   16357 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
   16358 #  define SQLITE_USE_MALLOC_H
   16359 #  define SQLITE_USE_MALLOC_USABLE_SIZE
   16360 /*
   16361 ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
   16362 ** use of _msize() is automatic, but can be disabled by compiling with
   16363 ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
   16364 ** the malloc.h header file.
   16365 */
   16366 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
   16367 #  define SQLITE_USE_MALLOC_H
   16368 #  define SQLITE_USE_MSIZE
   16369 #endif
   16370 
   16371 /*
   16372 ** Include the malloc.h header file, if necessary.  Also set define macro
   16373 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
   16374 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
   16375 ** The memory size function can always be overridden manually by defining
   16376 ** the macro SQLITE_MALLOCSIZE to the desired function name.
   16377 */
   16378 #if defined(SQLITE_USE_MALLOC_H)
   16379 #  include <malloc.h>
   16380 #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
   16381 #    if !defined(SQLITE_MALLOCSIZE)
   16382 #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
   16383 #    endif
   16384 #  elif defined(SQLITE_USE_MSIZE)
   16385 #    if !defined(SQLITE_MALLOCSIZE)
   16386 #      define SQLITE_MALLOCSIZE      _msize
   16387 #    endif
   16388 #  endif
   16389 #endif /* defined(SQLITE_USE_MALLOC_H) */
   16390 
   16391 #endif /* __APPLE__ or not __APPLE__ */
   16392 
   16393 /*
   16394 ** Like malloc(), but remember the size of the allocation
   16395 ** so that we can find it later using sqlite3MemSize().
   16396 **
   16397 ** For this low-level routine, we are guaranteed that nByte>0 because
   16398 ** cases of nByte<=0 will be intercepted and dealt with by higher level
   16399 ** routines.
   16400 */
   16401 static void *sqlite3MemMalloc(int nByte){
   16402 #ifdef SQLITE_MALLOCSIZE
   16403   void *p = SQLITE_MALLOC( nByte );
   16404   if( p==0 ){
   16405     testcase( sqlite3GlobalConfig.xLog!=0 );
   16406     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   16407   }
   16408   return p;
   16409 #else
   16410   sqlite3_int64 *p;
   16411   assert( nByte>0 );
   16412   nByte = ROUND8(nByte);
   16413   p = SQLITE_MALLOC( nByte+8 );
   16414   if( p ){
   16415     p[0] = nByte;
   16416     p++;
   16417   }else{
   16418     testcase( sqlite3GlobalConfig.xLog!=0 );
   16419     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   16420   }
   16421   return (void *)p;
   16422 #endif
   16423 }
   16424 
   16425 /*
   16426 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
   16427 ** or sqlite3MemRealloc().
   16428 **
   16429 ** For this low-level routine, we already know that pPrior!=0 since
   16430 ** cases where pPrior==0 will have been intecepted and dealt with
   16431 ** by higher-level routines.
   16432 */
   16433 static void sqlite3MemFree(void *pPrior){
   16434 #ifdef SQLITE_MALLOCSIZE
   16435   SQLITE_FREE(pPrior);
   16436 #else
   16437   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   16438   assert( pPrior!=0 );
   16439   p--;
   16440   SQLITE_FREE(p);
   16441 #endif
   16442 }
   16443 
   16444 /*
   16445 ** Report the allocated size of a prior return from xMalloc()
   16446 ** or xRealloc().
   16447 */
   16448 static int sqlite3MemSize(void *pPrior){
   16449 #ifdef SQLITE_MALLOCSIZE
   16450   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
   16451 #else
   16452   sqlite3_int64 *p;
   16453   if( pPrior==0 ) return 0;
   16454   p = (sqlite3_int64*)pPrior;
   16455   p--;
   16456   return (int)p[0];
   16457 #endif
   16458 }
   16459 
   16460 /*
   16461 ** Like realloc().  Resize an allocation previously obtained from
   16462 ** sqlite3MemMalloc().
   16463 **
   16464 ** For this low-level interface, we know that pPrior!=0.  Cases where
   16465 ** pPrior==0 while have been intercepted by higher-level routine and
   16466 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
   16467 ** cases where nByte<=0 will have been intercepted by higher-level
   16468 ** routines and redirected to xFree.
   16469 */
   16470 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   16471 #ifdef SQLITE_MALLOCSIZE
   16472   void *p = SQLITE_REALLOC(pPrior, nByte);
   16473   if( p==0 ){
   16474     testcase( sqlite3GlobalConfig.xLog!=0 );
   16475     sqlite3_log(SQLITE_NOMEM,
   16476       "failed memory resize %u to %u bytes",
   16477       SQLITE_MALLOCSIZE(pPrior), nByte);
   16478   }
   16479   return p;
   16480 #else
   16481   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   16482   assert( pPrior!=0 && nByte>0 );
   16483   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
   16484   p--;
   16485   p = SQLITE_REALLOC(p, nByte+8 );
   16486   if( p ){
   16487     p[0] = nByte;
   16488     p++;
   16489   }else{
   16490     testcase( sqlite3GlobalConfig.xLog!=0 );
   16491     sqlite3_log(SQLITE_NOMEM,
   16492       "failed memory resize %u to %u bytes",
   16493       sqlite3MemSize(pPrior), nByte);
   16494   }
   16495   return (void*)p;
   16496 #endif
   16497 }
   16498 
   16499 /*
   16500 ** Round up a request size to the next valid allocation size.
   16501 */
   16502 static int sqlite3MemRoundup(int n){
   16503   return ROUND8(n);
   16504 }
   16505 
   16506 /*
   16507 ** Initialize this module.
   16508 */
   16509 static int sqlite3MemInit(void *NotUsed){
   16510 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
   16511   int cpuCount;
   16512   size_t len;
   16513   if( _sqliteZone_ ){
   16514     return SQLITE_OK;
   16515   }
   16516   len = sizeof(cpuCount);
   16517   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
   16518   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
   16519   if( cpuCount>1 ){
   16520     /* defer MT decisions to system malloc */
   16521     _sqliteZone_ = malloc_default_zone();
   16522   }else{
   16523     /* only 1 core, use our own zone to contention over global locks,
   16524     ** e.g. we have our own dedicated locks */
   16525     bool success;
   16526     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
   16527     malloc_set_zone_name(newzone, "Sqlite_Heap");
   16528     do{
   16529       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
   16530                                  (void * volatile *)&_sqliteZone_);
   16531     }while(!_sqliteZone_);
   16532     if( !success ){
   16533       /* somebody registered a zone first */
   16534       malloc_destroy_zone(newzone);
   16535     }
   16536   }
   16537 #endif
   16538   UNUSED_PARAMETER(NotUsed);
   16539   return SQLITE_OK;
   16540 }
   16541 
   16542 /*
   16543 ** Deinitialize this module.
   16544 */
   16545 static void sqlite3MemShutdown(void *NotUsed){
   16546   UNUSED_PARAMETER(NotUsed);
   16547   return;
   16548 }
   16549 
   16550 /*
   16551 ** This routine is the only routine in this file with external linkage.
   16552 **
   16553 ** Populate the low-level memory allocation function pointers in
   16554 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   16555 */
   16556 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   16557   static const sqlite3_mem_methods defaultMethods = {
   16558      sqlite3MemMalloc,
   16559      sqlite3MemFree,
   16560      sqlite3MemRealloc,
   16561      sqlite3MemSize,
   16562      sqlite3MemRoundup,
   16563      sqlite3MemInit,
   16564      sqlite3MemShutdown,
   16565      0
   16566   };
   16567   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   16568 }
   16569 
   16570 #endif /* SQLITE_SYSTEM_MALLOC */
   16571 
   16572 /************** End of mem1.c ************************************************/
   16573 /************** Begin file mem2.c ********************************************/
   16574 /*
   16575 ** 2007 August 15
   16576 **
   16577 ** The author disclaims copyright to this source code.  In place of
   16578 ** a legal notice, here is a blessing:
   16579 **
   16580 **    May you do good and not evil.
   16581 **    May you find forgiveness for yourself and forgive others.
   16582 **    May you share freely, never taking more than you give.
   16583 **
   16584 *************************************************************************
   16585 **
   16586 ** This file contains low-level memory allocation drivers for when
   16587 ** SQLite will use the standard C-library malloc/realloc/free interface
   16588 ** to obtain the memory it needs while adding lots of additional debugging
   16589 ** information to each allocation in order to help detect and fix memory
   16590 ** leaks and memory usage errors.
   16591 **
   16592 ** This file contains implementations of the low-level memory allocation
   16593 ** routines specified in the sqlite3_mem_methods object.
   16594 */
   16595 
   16596 /*
   16597 ** This version of the memory allocator is used only if the
   16598 ** SQLITE_MEMDEBUG macro is defined
   16599 */
   16600 #ifdef SQLITE_MEMDEBUG
   16601 
   16602 /*
   16603 ** The backtrace functionality is only available with GLIBC
   16604 */
   16605 #ifdef __GLIBC__
   16606   extern int backtrace(void**,int);
   16607   extern void backtrace_symbols_fd(void*const*,int,int);
   16608 #else
   16609 # define backtrace(A,B) 1
   16610 # define backtrace_symbols_fd(A,B,C)
   16611 #endif
   16612 /* #include <stdio.h> */
   16613 
   16614 /*
   16615 ** Each memory allocation looks like this:
   16616 **
   16617 **  ------------------------------------------------------------------------
   16618 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
   16619 **  ------------------------------------------------------------------------
   16620 **
   16621 ** The application code sees only a pointer to the allocation.  We have
   16622 ** to back up from the allocation pointer to find the MemBlockHdr.  The
   16623 ** MemBlockHdr tells us the size of the allocation and the number of
   16624 ** backtrace pointers.  There is also a guard word at the end of the
   16625 ** MemBlockHdr.
   16626 */
   16627 struct MemBlockHdr {
   16628   i64 iSize;                          /* Size of this allocation */
   16629   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
   16630   char nBacktrace;                    /* Number of backtraces on this alloc */
   16631   char nBacktraceSlots;               /* Available backtrace slots */
   16632   u8 nTitle;                          /* Bytes of title; includes '\0' */
   16633   u8 eType;                           /* Allocation type code */
   16634   int iForeGuard;                     /* Guard word for sanity */
   16635 };
   16636 
   16637 /*
   16638 ** Guard words
   16639 */
   16640 #define FOREGUARD 0x80F5E153
   16641 #define REARGUARD 0xE4676B53
   16642 
   16643 /*
   16644 ** Number of malloc size increments to track.
   16645 */
   16646 #define NCSIZE  1000
   16647 
   16648 /*
   16649 ** All of the static variables used by this module are collected
   16650 ** into a single structure named "mem".  This is to keep the
   16651 ** static variables organized and to reduce namespace pollution
   16652 ** when this module is combined with other in the amalgamation.
   16653 */
   16654 static struct {
   16655 
   16656   /*
   16657   ** Mutex to control access to the memory allocation subsystem.
   16658   */
   16659   sqlite3_mutex *mutex;
   16660 
   16661   /*
   16662   ** Head and tail of a linked list of all outstanding allocations
   16663   */
   16664   struct MemBlockHdr *pFirst;
   16665   struct MemBlockHdr *pLast;
   16666 
   16667   /*
   16668   ** The number of levels of backtrace to save in new allocations.
   16669   */
   16670   int nBacktrace;
   16671   void (*xBacktrace)(int, int, void **);
   16672 
   16673   /*
   16674   ** Title text to insert in front of each block
   16675   */
   16676   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
   16677   char zTitle[100];  /* The title text */
   16678 
   16679   /*
   16680   ** sqlite3MallocDisallow() increments the following counter.
   16681   ** sqlite3MallocAllow() decrements it.
   16682   */
   16683   int disallow; /* Do not allow memory allocation */
   16684 
   16685   /*
   16686   ** Gather statistics on the sizes of memory allocations.
   16687   ** nAlloc[i] is the number of allocation attempts of i*8
   16688   ** bytes.  i==NCSIZE is the number of allocation attempts for
   16689   ** sizes more than NCSIZE*8 bytes.
   16690   */
   16691   int nAlloc[NCSIZE];      /* Total number of allocations */
   16692   int nCurrent[NCSIZE];    /* Current number of allocations */
   16693   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
   16694 
   16695 } mem;
   16696 
   16697 
   16698 /*
   16699 ** Adjust memory usage statistics
   16700 */
   16701 static void adjustStats(int iSize, int increment){
   16702   int i = ROUND8(iSize)/8;
   16703   if( i>NCSIZE-1 ){
   16704     i = NCSIZE - 1;
   16705   }
   16706   if( increment>0 ){
   16707     mem.nAlloc[i]++;
   16708     mem.nCurrent[i]++;
   16709     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
   16710       mem.mxCurrent[i] = mem.nCurrent[i];
   16711     }
   16712   }else{
   16713     mem.nCurrent[i]--;
   16714     assert( mem.nCurrent[i]>=0 );
   16715   }
   16716 }
   16717 
   16718 /*
   16719 ** Given an allocation, find the MemBlockHdr for that allocation.
   16720 **
   16721 ** This routine checks the guards at either end of the allocation and
   16722 ** if they are incorrect it asserts.
   16723 */
   16724 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
   16725   struct MemBlockHdr *p;
   16726   int *pInt;
   16727   u8 *pU8;
   16728   int nReserve;
   16729 
   16730   p = (struct MemBlockHdr*)pAllocation;
   16731   p--;
   16732   assert( p->iForeGuard==(int)FOREGUARD );
   16733   nReserve = ROUND8(p->iSize);
   16734   pInt = (int*)pAllocation;
   16735   pU8 = (u8*)pAllocation;
   16736   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
   16737   /* This checks any of the "extra" bytes allocated due
   16738   ** to rounding up to an 8 byte boundary to ensure
   16739   ** they haven't been overwritten.
   16740   */
   16741   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
   16742   return p;
   16743 }
   16744 
   16745 /*
   16746 ** Return the number of bytes currently allocated at address p.
   16747 */
   16748 static int sqlite3MemSize(void *p){
   16749   struct MemBlockHdr *pHdr;
   16750   if( !p ){
   16751     return 0;
   16752   }
   16753   pHdr = sqlite3MemsysGetHeader(p);
   16754   return (int)pHdr->iSize;
   16755 }
   16756 
   16757 /*
   16758 ** Initialize the memory allocation subsystem.
   16759 */
   16760 static int sqlite3MemInit(void *NotUsed){
   16761   UNUSED_PARAMETER(NotUsed);
   16762   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
   16763   if( !sqlite3GlobalConfig.bMemstat ){
   16764     /* If memory status is enabled, then the malloc.c wrapper will already
   16765     ** hold the STATIC_MEM mutex when the routines here are invoked. */
   16766     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   16767   }
   16768   return SQLITE_OK;
   16769 }
   16770 
   16771 /*
   16772 ** Deinitialize the memory allocation subsystem.
   16773 */
   16774 static void sqlite3MemShutdown(void *NotUsed){
   16775   UNUSED_PARAMETER(NotUsed);
   16776   mem.mutex = 0;
   16777 }
   16778 
   16779 /*
   16780 ** Round up a request size to the next valid allocation size.
   16781 */
   16782 static int sqlite3MemRoundup(int n){
   16783   return ROUND8(n);
   16784 }
   16785 
   16786 /*
   16787 ** Fill a buffer with pseudo-random bytes.  This is used to preset
   16788 ** the content of a new memory allocation to unpredictable values and
   16789 ** to clear the content of a freed allocation to unpredictable values.
   16790 */
   16791 static void randomFill(char *pBuf, int nByte){
   16792   unsigned int x, y, r;
   16793   x = SQLITE_PTR_TO_INT(pBuf);
   16794   y = nByte | 1;
   16795   while( nByte >= 4 ){
   16796     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
   16797     y = y*1103515245 + 12345;
   16798     r = x ^ y;
   16799     *(int*)pBuf = r;
   16800     pBuf += 4;
   16801     nByte -= 4;
   16802   }
   16803   while( nByte-- > 0 ){
   16804     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
   16805     y = y*1103515245 + 12345;
   16806     r = x ^ y;
   16807     *(pBuf++) = r & 0xff;
   16808   }
   16809 }
   16810 
   16811 /*
   16812 ** Allocate nByte bytes of memory.
   16813 */
   16814 static void *sqlite3MemMalloc(int nByte){
   16815   struct MemBlockHdr *pHdr;
   16816   void **pBt;
   16817   char *z;
   16818   int *pInt;
   16819   void *p = 0;
   16820   int totalSize;
   16821   int nReserve;
   16822   sqlite3_mutex_enter(mem.mutex);
   16823   assert( mem.disallow==0 );
   16824   nReserve = ROUND8(nByte);
   16825   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
   16826                mem.nBacktrace*sizeof(void*) + mem.nTitle;
   16827   p = malloc(totalSize);
   16828   if( p ){
   16829     z = p;
   16830     pBt = (void**)&z[mem.nTitle];
   16831     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
   16832     pHdr->pNext = 0;
   16833     pHdr->pPrev = mem.pLast;
   16834     if( mem.pLast ){
   16835       mem.pLast->pNext = pHdr;
   16836     }else{
   16837       mem.pFirst = pHdr;
   16838     }
   16839     mem.pLast = pHdr;
   16840     pHdr->iForeGuard = FOREGUARD;
   16841     pHdr->eType = MEMTYPE_HEAP;
   16842     pHdr->nBacktraceSlots = mem.nBacktrace;
   16843     pHdr->nTitle = mem.nTitle;
   16844     if( mem.nBacktrace ){
   16845       void *aAddr[40];
   16846       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
   16847       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
   16848       assert(pBt[0]);
   16849       if( mem.xBacktrace ){
   16850         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
   16851       }
   16852     }else{
   16853       pHdr->nBacktrace = 0;
   16854     }
   16855     if( mem.nTitle ){
   16856       memcpy(z, mem.zTitle, mem.nTitle);
   16857     }
   16858     pHdr->iSize = nByte;
   16859     adjustStats(nByte, +1);
   16860     pInt = (int*)&pHdr[1];
   16861     pInt[nReserve/sizeof(int)] = REARGUARD;
   16862     randomFill((char*)pInt, nByte);
   16863     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
   16864     p = (void*)pInt;
   16865   }
   16866   sqlite3_mutex_leave(mem.mutex);
   16867   return p;
   16868 }
   16869 
   16870 /*
   16871 ** Free memory.
   16872 */
   16873 static void sqlite3MemFree(void *pPrior){
   16874   struct MemBlockHdr *pHdr;
   16875   void **pBt;
   16876   char *z;
   16877   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
   16878        || mem.mutex!=0 );
   16879   pHdr = sqlite3MemsysGetHeader(pPrior);
   16880   pBt = (void**)pHdr;
   16881   pBt -= pHdr->nBacktraceSlots;
   16882   sqlite3_mutex_enter(mem.mutex);
   16883   if( pHdr->pPrev ){
   16884     assert( pHdr->pPrev->pNext==pHdr );
   16885     pHdr->pPrev->pNext = pHdr->pNext;
   16886   }else{
   16887     assert( mem.pFirst==pHdr );
   16888     mem.pFirst = pHdr->pNext;
   16889   }
   16890   if( pHdr->pNext ){
   16891     assert( pHdr->pNext->pPrev==pHdr );
   16892     pHdr->pNext->pPrev = pHdr->pPrev;
   16893   }else{
   16894     assert( mem.pLast==pHdr );
   16895     mem.pLast = pHdr->pPrev;
   16896   }
   16897   z = (char*)pBt;
   16898   z -= pHdr->nTitle;
   16899   adjustStats((int)pHdr->iSize, -1);
   16900   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
   16901                 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
   16902   free(z);
   16903   sqlite3_mutex_leave(mem.mutex);
   16904 }
   16905 
   16906 /*
   16907 ** Change the size of an existing memory allocation.
   16908 **
   16909 ** For this debugging implementation, we *always* make a copy of the
   16910 ** allocation into a new place in memory.  In this way, if the
   16911 ** higher level code is using pointer to the old allocation, it is
   16912 ** much more likely to break and we are much more liking to find
   16913 ** the error.
   16914 */
   16915 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   16916   struct MemBlockHdr *pOldHdr;
   16917   void *pNew;
   16918   assert( mem.disallow==0 );
   16919   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
   16920   pOldHdr = sqlite3MemsysGetHeader(pPrior);
   16921   pNew = sqlite3MemMalloc(nByte);
   16922   if( pNew ){
   16923     memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
   16924     if( nByte>pOldHdr->iSize ){
   16925       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
   16926     }
   16927     sqlite3MemFree(pPrior);
   16928   }
   16929   return pNew;
   16930 }
   16931 
   16932 /*
   16933 ** Populate the low-level memory allocation function pointers in
   16934 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   16935 */
   16936 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   16937   static const sqlite3_mem_methods defaultMethods = {
   16938      sqlite3MemMalloc,
   16939      sqlite3MemFree,
   16940      sqlite3MemRealloc,
   16941      sqlite3MemSize,
   16942      sqlite3MemRoundup,
   16943      sqlite3MemInit,
   16944      sqlite3MemShutdown,
   16945      0
   16946   };
   16947   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   16948 }
   16949 
   16950 /*
   16951 ** Set the "type" of an allocation.
   16952 */
   16953 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
   16954   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   16955     struct MemBlockHdr *pHdr;
   16956     pHdr = sqlite3MemsysGetHeader(p);
   16957     assert( pHdr->iForeGuard==FOREGUARD );
   16958     pHdr->eType = eType;
   16959   }
   16960 }
   16961 
   16962 /*
   16963 ** Return TRUE if the mask of type in eType matches the type of the
   16964 ** allocation p.  Also return true if p==NULL.
   16965 **
   16966 ** This routine is designed for use within an assert() statement, to
   16967 ** verify the type of an allocation.  For example:
   16968 **
   16969 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   16970 */
   16971 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
   16972   int rc = 1;
   16973   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   16974     struct MemBlockHdr *pHdr;
   16975     pHdr = sqlite3MemsysGetHeader(p);
   16976     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
   16977     if( (pHdr->eType&eType)==0 ){
   16978       rc = 0;
   16979     }
   16980   }
   16981   return rc;
   16982 }
   16983 
   16984 /*
   16985 ** Return TRUE if the mask of type in eType matches no bits of the type of the
   16986 ** allocation p.  Also return true if p==NULL.
   16987 **
   16988 ** This routine is designed for use within an assert() statement, to
   16989 ** verify the type of an allocation.  For example:
   16990 **
   16991 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   16992 */
   16993 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
   16994   int rc = 1;
   16995   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   16996     struct MemBlockHdr *pHdr;
   16997     pHdr = sqlite3MemsysGetHeader(p);
   16998     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
   16999     if( (pHdr->eType&eType)!=0 ){
   17000       rc = 0;
   17001     }
   17002   }
   17003   return rc;
   17004 }
   17005 
   17006 /*
   17007 ** Set the number of backtrace levels kept for each allocation.
   17008 ** A value of zero turns off backtracing.  The number is always rounded
   17009 ** up to a multiple of 2.
   17010 */
   17011 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
   17012   if( depth<0 ){ depth = 0; }
   17013   if( depth>20 ){ depth = 20; }
   17014   depth = (depth+1)&0xfe;
   17015   mem.nBacktrace = depth;
   17016 }
   17017 
   17018 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
   17019   mem.xBacktrace = xBacktrace;
   17020 }
   17021 
   17022 /*
   17023 ** Set the title string for subsequent allocations.
   17024 */
   17025 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
   17026   unsigned int n = sqlite3Strlen30(zTitle) + 1;
   17027   sqlite3_mutex_enter(mem.mutex);
   17028   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
   17029   memcpy(mem.zTitle, zTitle, n);
   17030   mem.zTitle[n] = 0;
   17031   mem.nTitle = ROUND8(n);
   17032   sqlite3_mutex_leave(mem.mutex);
   17033 }
   17034 
   17035 SQLITE_PRIVATE void sqlite3MemdebugSync(){
   17036   struct MemBlockHdr *pHdr;
   17037   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   17038     void **pBt = (void**)pHdr;
   17039     pBt -= pHdr->nBacktraceSlots;
   17040     mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
   17041   }
   17042 }
   17043 
   17044 /*
   17045 ** Open the file indicated and write a log of all unfreed memory
   17046 ** allocations into that log.
   17047 */
   17048 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
   17049   FILE *out;
   17050   struct MemBlockHdr *pHdr;
   17051   void **pBt;
   17052   int i;
   17053   out = fopen(zFilename, "w");
   17054   if( out==0 ){
   17055     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   17056                     zFilename);
   17057     return;
   17058   }
   17059   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   17060     char *z = (char*)pHdr;
   17061     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
   17062     fprintf(out, "**** %lld bytes at %p from %s ****\n",
   17063             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
   17064     if( pHdr->nBacktrace ){
   17065       fflush(out);
   17066       pBt = (void**)pHdr;
   17067       pBt -= pHdr->nBacktraceSlots;
   17068       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
   17069       fprintf(out, "\n");
   17070     }
   17071   }
   17072   fprintf(out, "COUNTS:\n");
   17073   for(i=0; i<NCSIZE-1; i++){
   17074     if( mem.nAlloc[i] ){
   17075       fprintf(out, "   %5d: %10d %10d %10d\n",
   17076             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
   17077     }
   17078   }
   17079   if( mem.nAlloc[NCSIZE-1] ){
   17080     fprintf(out, "   %5d: %10d %10d %10d\n",
   17081              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
   17082              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
   17083   }
   17084   fclose(out);
   17085 }
   17086 
   17087 /*
   17088 ** Return the number of times sqlite3MemMalloc() has been called.
   17089 */
   17090 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
   17091   int i;
   17092   int nTotal = 0;
   17093   for(i=0; i<NCSIZE; i++){
   17094     nTotal += mem.nAlloc[i];
   17095   }
   17096   return nTotal;
   17097 }
   17098 
   17099 
   17100 #endif /* SQLITE_MEMDEBUG */
   17101 
   17102 /************** End of mem2.c ************************************************/
   17103 /************** Begin file mem3.c ********************************************/
   17104 /*
   17105 ** 2007 October 14
   17106 **
   17107 ** The author disclaims copyright to this source code.  In place of
   17108 ** a legal notice, here is a blessing:
   17109 **
   17110 **    May you do good and not evil.
   17111 **    May you find forgiveness for yourself and forgive others.
   17112 **    May you share freely, never taking more than you give.
   17113 **
   17114 *************************************************************************
   17115 ** This file contains the C functions that implement a memory
   17116 ** allocation subsystem for use by SQLite.
   17117 **
   17118 ** This version of the memory allocation subsystem omits all
   17119 ** use of malloc(). The SQLite user supplies a block of memory
   17120 ** before calling sqlite3_initialize() from which allocations
   17121 ** are made and returned by the xMalloc() and xRealloc()
   17122 ** implementations. Once sqlite3_initialize() has been called,
   17123 ** the amount of memory available to SQLite is fixed and cannot
   17124 ** be changed.
   17125 **
   17126 ** This version of the memory allocation subsystem is included
   17127 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
   17128 */
   17129 
   17130 /*
   17131 ** This version of the memory allocator is only built into the library
   17132 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
   17133 ** mean that the library will use a memory-pool by default, just that
   17134 ** it is available. The mempool allocator is activated by calling
   17135 ** sqlite3_config().
   17136 */
   17137 #ifdef SQLITE_ENABLE_MEMSYS3
   17138 
   17139 /*
   17140 ** Maximum size (in Mem3Blocks) of a "small" chunk.
   17141 */
   17142 #define MX_SMALL 10
   17143 
   17144 
   17145 /*
   17146 ** Number of freelist hash slots
   17147 */
   17148 #define N_HASH  61
   17149 
   17150 /*
   17151 ** A memory allocation (also called a "chunk") consists of two or
   17152 ** more blocks where each block is 8 bytes.  The first 8 bytes are
   17153 ** a header that is not returned to the user.
   17154 **
   17155 ** A chunk is two or more blocks that is either checked out or
   17156 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
   17157 ** size of the allocation in blocks if the allocation is free.
   17158 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
   17159 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
   17160 ** is true if the previous chunk is checked out and false if the
   17161 ** previous chunk is free.  The u.hdr.prevSize field is the size of
   17162 ** the previous chunk in blocks if the previous chunk is on the
   17163 ** freelist. If the previous chunk is checked out, then
   17164 ** u.hdr.prevSize can be part of the data for that chunk and should
   17165 ** not be read or written.
   17166 **
   17167 ** We often identify a chunk by its index in mem3.aPool[].  When
   17168 ** this is done, the chunk index refers to the second block of
   17169 ** the chunk.  In this way, the first chunk has an index of 1.
   17170 ** A chunk index of 0 means "no such chunk" and is the equivalent
   17171 ** of a NULL pointer.
   17172 **
   17173 ** The second block of free chunks is of the form u.list.  The
   17174 ** two fields form a double-linked list of chunks of related sizes.
   17175 ** Pointers to the head of the list are stored in mem3.aiSmall[]
   17176 ** for smaller chunks and mem3.aiHash[] for larger chunks.
   17177 **
   17178 ** The second block of a chunk is user data if the chunk is checked
   17179 ** out.  If a chunk is checked out, the user data may extend into
   17180 ** the u.hdr.prevSize value of the following chunk.
   17181 */
   17182 typedef struct Mem3Block Mem3Block;
   17183 struct Mem3Block {
   17184   union {
   17185     struct {
   17186       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
   17187       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
   17188     } hdr;
   17189     struct {
   17190       u32 next;       /* Index in mem3.aPool[] of next free chunk */
   17191       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
   17192     } list;
   17193   } u;
   17194 };
   17195 
   17196 /*
   17197 ** All of the static variables used by this module are collected
   17198 ** into a single structure named "mem3".  This is to keep the
   17199 ** static variables organized and to reduce namespace pollution
   17200 ** when this module is combined with other in the amalgamation.
   17201 */
   17202 static SQLITE_WSD struct Mem3Global {
   17203   /*
   17204   ** Memory available for allocation. nPool is the size of the array
   17205   ** (in Mem3Blocks) pointed to by aPool less 2.
   17206   */
   17207   u32 nPool;
   17208   Mem3Block *aPool;
   17209 
   17210   /*
   17211   ** True if we are evaluating an out-of-memory callback.
   17212   */
   17213   int alarmBusy;
   17214 
   17215   /*
   17216   ** Mutex to control access to the memory allocation subsystem.
   17217   */
   17218   sqlite3_mutex *mutex;
   17219 
   17220   /*
   17221   ** The minimum amount of free space that we have seen.
   17222   */
   17223   u32 mnMaster;
   17224 
   17225   /*
   17226   ** iMaster is the index of the master chunk.  Most new allocations
   17227   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
   17228   ** of the current master.  iMaster is 0 if there is not master chunk.
   17229   ** The master chunk is not in either the aiHash[] or aiSmall[].
   17230   */
   17231   u32 iMaster;
   17232   u32 szMaster;
   17233 
   17234   /*
   17235   ** Array of lists of free blocks according to the block size
   17236   ** for smaller chunks, or a hash on the block size for larger
   17237   ** chunks.
   17238   */
   17239   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
   17240   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
   17241 } mem3 = { 97535575 };
   17242 
   17243 #define mem3 GLOBAL(struct Mem3Global, mem3)
   17244 
   17245 /*
   17246 ** Unlink the chunk at mem3.aPool[i] from list it is currently
   17247 ** on.  *pRoot is the list that i is a member of.
   17248 */
   17249 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
   17250   u32 next = mem3.aPool[i].u.list.next;
   17251   u32 prev = mem3.aPool[i].u.list.prev;
   17252   assert( sqlite3_mutex_held(mem3.mutex) );
   17253   if( prev==0 ){
   17254     *pRoot = next;
   17255   }else{
   17256     mem3.aPool[prev].u.list.next = next;
   17257   }
   17258   if( next ){
   17259     mem3.aPool[next].u.list.prev = prev;
   17260   }
   17261   mem3.aPool[i].u.list.next = 0;
   17262   mem3.aPool[i].u.list.prev = 0;
   17263 }
   17264 
   17265 /*
   17266 ** Unlink the chunk at index i from
   17267 ** whatever list is currently a member of.
   17268 */
   17269 static void memsys3Unlink(u32 i){
   17270   u32 size, hash;
   17271   assert( sqlite3_mutex_held(mem3.mutex) );
   17272   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   17273   assert( i>=1 );
   17274   size = mem3.aPool[i-1].u.hdr.size4x/4;
   17275   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   17276   assert( size>=2 );
   17277   if( size <= MX_SMALL ){
   17278     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
   17279   }else{
   17280     hash = size % N_HASH;
   17281     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   17282   }
   17283 }
   17284 
   17285 /*
   17286 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
   17287 ** at *pRoot.
   17288 */
   17289 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
   17290   assert( sqlite3_mutex_held(mem3.mutex) );
   17291   mem3.aPool[i].u.list.next = *pRoot;
   17292   mem3.aPool[i].u.list.prev = 0;
   17293   if( *pRoot ){
   17294     mem3.aPool[*pRoot].u.list.prev = i;
   17295   }
   17296   *pRoot = i;
   17297 }
   17298 
   17299 /*
   17300 ** Link the chunk at index i into either the appropriate
   17301 ** small chunk list, or into the large chunk hash table.
   17302 */
   17303 static void memsys3Link(u32 i){
   17304   u32 size, hash;
   17305   assert( sqlite3_mutex_held(mem3.mutex) );
   17306   assert( i>=1 );
   17307   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   17308   size = mem3.aPool[i-1].u.hdr.size4x/4;
   17309   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   17310   assert( size>=2 );
   17311   if( size <= MX_SMALL ){
   17312     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
   17313   }else{
   17314     hash = size % N_HASH;
   17315     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
   17316   }
   17317 }
   17318 
   17319 /*
   17320 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   17321 ** will already be held (obtained by code in malloc.c) if
   17322 ** sqlite3GlobalConfig.bMemStat is true.
   17323 */
   17324 static void memsys3Enter(void){
   17325   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
   17326     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   17327   }
   17328   sqlite3_mutex_enter(mem3.mutex);
   17329 }
   17330 static void memsys3Leave(void){
   17331   sqlite3_mutex_leave(mem3.mutex);
   17332 }
   17333 
   17334 /*
   17335 ** Called when we are unable to satisfy an allocation of nBytes.
   17336 */
   17337 static void memsys3OutOfMemory(int nByte){
   17338   if( !mem3.alarmBusy ){
   17339     mem3.alarmBusy = 1;
   17340     assert( sqlite3_mutex_held(mem3.mutex) );
   17341     sqlite3_mutex_leave(mem3.mutex);
   17342     sqlite3_release_memory(nByte);
   17343     sqlite3_mutex_enter(mem3.mutex);
   17344     mem3.alarmBusy = 0;
   17345   }
   17346 }
   17347 
   17348 
   17349 /*
   17350 ** Chunk i is a free chunk that has been unlinked.  Adjust its
   17351 ** size parameters for check-out and return a pointer to the
   17352 ** user portion of the chunk.
   17353 */
   17354 static void *memsys3Checkout(u32 i, u32 nBlock){
   17355   u32 x;
   17356   assert( sqlite3_mutex_held(mem3.mutex) );
   17357   assert( i>=1 );
   17358   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
   17359   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
   17360   x = mem3.aPool[i-1].u.hdr.size4x;
   17361   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
   17362   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
   17363   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
   17364   return &mem3.aPool[i];
   17365 }
   17366 
   17367 /*
   17368 ** Carve a piece off of the end of the mem3.iMaster free chunk.
   17369 ** Return a pointer to the new allocation.  Or, if the master chunk
   17370 ** is not large enough, return 0.
   17371 */
   17372 static void *memsys3FromMaster(u32 nBlock){
   17373   assert( sqlite3_mutex_held(mem3.mutex) );
   17374   assert( mem3.szMaster>=nBlock );
   17375   if( nBlock>=mem3.szMaster-1 ){
   17376     /* Use the entire master */
   17377     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
   17378     mem3.iMaster = 0;
   17379     mem3.szMaster = 0;
   17380     mem3.mnMaster = 0;
   17381     return p;
   17382   }else{
   17383     /* Split the master block.  Return the tail. */
   17384     u32 newi, x;
   17385     newi = mem3.iMaster + mem3.szMaster - nBlock;
   17386     assert( newi > mem3.iMaster+1 );
   17387     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
   17388     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
   17389     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
   17390     mem3.szMaster -= nBlock;
   17391     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
   17392     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   17393     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   17394     if( mem3.szMaster < mem3.mnMaster ){
   17395       mem3.mnMaster = mem3.szMaster;
   17396     }
   17397     return (void*)&mem3.aPool[newi];
   17398   }
   17399 }
   17400 
   17401 /*
   17402 ** *pRoot is the head of a list of free chunks of the same size
   17403 ** or same size hash.  In other words, *pRoot is an entry in either
   17404 ** mem3.aiSmall[] or mem3.aiHash[].
   17405 **
   17406 ** This routine examines all entries on the given list and tries
   17407 ** to coalesce each entries with adjacent free chunks.
   17408 **
   17409 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
   17410 ** the current mem3.iMaster with the new larger chunk.  In order for
   17411 ** this mem3.iMaster replacement to work, the master chunk must be
   17412 ** linked into the hash tables.  That is not the normal state of
   17413 ** affairs, of course.  The calling routine must link the master
   17414 ** chunk before invoking this routine, then must unlink the (possibly
   17415 ** changed) master chunk once this routine has finished.
   17416 */
   17417 static void memsys3Merge(u32 *pRoot){
   17418   u32 iNext, prev, size, i, x;
   17419 
   17420   assert( sqlite3_mutex_held(mem3.mutex) );
   17421   for(i=*pRoot; i>0; i=iNext){
   17422     iNext = mem3.aPool[i].u.list.next;
   17423     size = mem3.aPool[i-1].u.hdr.size4x;
   17424     assert( (size&1)==0 );
   17425     if( (size&2)==0 ){
   17426       memsys3UnlinkFromList(i, pRoot);
   17427       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
   17428       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
   17429       if( prev==iNext ){
   17430         iNext = mem3.aPool[prev].u.list.next;
   17431       }
   17432       memsys3Unlink(prev);
   17433       size = i + size/4 - prev;
   17434       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
   17435       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
   17436       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
   17437       memsys3Link(prev);
   17438       i = prev;
   17439     }else{
   17440       size /= 4;
   17441     }
   17442     if( size>mem3.szMaster ){
   17443       mem3.iMaster = i;
   17444       mem3.szMaster = size;
   17445     }
   17446   }
   17447 }
   17448 
   17449 /*
   17450 ** Return a block of memory of at least nBytes in size.
   17451 ** Return NULL if unable.
   17452 **
   17453 ** This function assumes that the necessary mutexes, if any, are
   17454 ** already held by the caller. Hence "Unsafe".
   17455 */
   17456 static void *memsys3MallocUnsafe(int nByte){
   17457   u32 i;
   17458   u32 nBlock;
   17459   u32 toFree;
   17460 
   17461   assert( sqlite3_mutex_held(mem3.mutex) );
   17462   assert( sizeof(Mem3Block)==8 );
   17463   if( nByte<=12 ){
   17464     nBlock = 2;
   17465   }else{
   17466     nBlock = (nByte + 11)/8;
   17467   }
   17468   assert( nBlock>=2 );
   17469 
   17470   /* STEP 1:
   17471   ** Look for an entry of the correct size in either the small
   17472   ** chunk table or in the large chunk hash table.  This is
   17473   ** successful most of the time (about 9 times out of 10).
   17474   */
   17475   if( nBlock <= MX_SMALL ){
   17476     i = mem3.aiSmall[nBlock-2];
   17477     if( i>0 ){
   17478       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
   17479       return memsys3Checkout(i, nBlock);
   17480     }
   17481   }else{
   17482     int hash = nBlock % N_HASH;
   17483     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
   17484       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
   17485         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   17486         return memsys3Checkout(i, nBlock);
   17487       }
   17488     }
   17489   }
   17490 
   17491   /* STEP 2:
   17492   ** Try to satisfy the allocation by carving a piece off of the end
   17493   ** of the master chunk.  This step usually works if step 1 fails.
   17494   */
   17495   if( mem3.szMaster>=nBlock ){
   17496     return memsys3FromMaster(nBlock);
   17497   }
   17498 
   17499 
   17500   /* STEP 3:
   17501   ** Loop through the entire memory pool.  Coalesce adjacent free
   17502   ** chunks.  Recompute the master chunk as the largest free chunk.
   17503   ** Then try again to satisfy the allocation by carving a piece off
   17504   ** of the end of the master chunk.  This step happens very
   17505   ** rarely (we hope!)
   17506   */
   17507   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
   17508     memsys3OutOfMemory(toFree);
   17509     if( mem3.iMaster ){
   17510       memsys3Link(mem3.iMaster);
   17511       mem3.iMaster = 0;
   17512       mem3.szMaster = 0;
   17513     }
   17514     for(i=0; i<N_HASH; i++){
   17515       memsys3Merge(&mem3.aiHash[i]);
   17516     }
   17517     for(i=0; i<MX_SMALL-1; i++){
   17518       memsys3Merge(&mem3.aiSmall[i]);
   17519     }
   17520     if( mem3.szMaster ){
   17521       memsys3Unlink(mem3.iMaster);
   17522       if( mem3.szMaster>=nBlock ){
   17523         return memsys3FromMaster(nBlock);
   17524       }
   17525     }
   17526   }
   17527 
   17528   /* If none of the above worked, then we fail. */
   17529   return 0;
   17530 }
   17531 
   17532 /*
   17533 ** Free an outstanding memory allocation.
   17534 **
   17535 ** This function assumes that the necessary mutexes, if any, are
   17536 ** already held by the caller. Hence "Unsafe".
   17537 */
   17538 static void memsys3FreeUnsafe(void *pOld){
   17539   Mem3Block *p = (Mem3Block*)pOld;
   17540   int i;
   17541   u32 size, x;
   17542   assert( sqlite3_mutex_held(mem3.mutex) );
   17543   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
   17544   i = p - mem3.aPool;
   17545   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
   17546   size = mem3.aPool[i-1].u.hdr.size4x/4;
   17547   assert( i+size<=mem3.nPool+1 );
   17548   mem3.aPool[i-1].u.hdr.size4x &= ~1;
   17549   mem3.aPool[i+size-1].u.hdr.prevSize = size;
   17550   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
   17551   memsys3Link(i);
   17552 
   17553   /* Try to expand the master using the newly freed chunk */
   17554   if( mem3.iMaster ){
   17555     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
   17556       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
   17557       mem3.iMaster -= size;
   17558       mem3.szMaster += size;
   17559       memsys3Unlink(mem3.iMaster);
   17560       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   17561       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   17562       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   17563     }
   17564     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   17565     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
   17566       memsys3Unlink(mem3.iMaster+mem3.szMaster);
   17567       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
   17568       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   17569       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   17570     }
   17571   }
   17572 }
   17573 
   17574 /*
   17575 ** Return the size of an outstanding allocation, in bytes.  The
   17576 ** size returned omits the 8-byte header overhead.  This only
   17577 ** works for chunks that are currently checked out.
   17578 */
   17579 static int memsys3Size(void *p){
   17580   Mem3Block *pBlock;
   17581   if( p==0 ) return 0;
   17582   pBlock = (Mem3Block*)p;
   17583   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
   17584   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
   17585 }
   17586 
   17587 /*
   17588 ** Round up a request size to the next valid allocation size.
   17589 */
   17590 static int memsys3Roundup(int n){
   17591   if( n<=12 ){
   17592     return 12;
   17593   }else{
   17594     return ((n+11)&~7) - 4;
   17595   }
   17596 }
   17597 
   17598 /*
   17599 ** Allocate nBytes of memory.
   17600 */
   17601 static void *memsys3Malloc(int nBytes){
   17602   sqlite3_int64 *p;
   17603   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
   17604   memsys3Enter();
   17605   p = memsys3MallocUnsafe(nBytes);
   17606   memsys3Leave();
   17607   return (void*)p;
   17608 }
   17609 
   17610 /*
   17611 ** Free memory.
   17612 */
   17613 static void memsys3Free(void *pPrior){
   17614   assert( pPrior );
   17615   memsys3Enter();
   17616   memsys3FreeUnsafe(pPrior);
   17617   memsys3Leave();
   17618 }
   17619 
   17620 /*
   17621 ** Change the size of an existing memory allocation
   17622 */
   17623 static void *memsys3Realloc(void *pPrior, int nBytes){
   17624   int nOld;
   17625   void *p;
   17626   if( pPrior==0 ){
   17627     return sqlite3_malloc(nBytes);
   17628   }
   17629   if( nBytes<=0 ){
   17630     sqlite3_free(pPrior);
   17631     return 0;
   17632   }
   17633   nOld = memsys3Size(pPrior);
   17634   if( nBytes<=nOld && nBytes>=nOld-128 ){
   17635     return pPrior;
   17636   }
   17637   memsys3Enter();
   17638   p = memsys3MallocUnsafe(nBytes);
   17639   if( p ){
   17640     if( nOld<nBytes ){
   17641       memcpy(p, pPrior, nOld);
   17642     }else{
   17643       memcpy(p, pPrior, nBytes);
   17644     }
   17645     memsys3FreeUnsafe(pPrior);
   17646   }
   17647   memsys3Leave();
   17648   return p;
   17649 }
   17650 
   17651 /*
   17652 ** Initialize this module.
   17653 */
   17654 static int memsys3Init(void *NotUsed){
   17655   UNUSED_PARAMETER(NotUsed);
   17656   if( !sqlite3GlobalConfig.pHeap ){
   17657     return SQLITE_ERROR;
   17658   }
   17659 
   17660   /* Store a pointer to the memory block in global structure mem3. */
   17661   assert( sizeof(Mem3Block)==8 );
   17662   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
   17663   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
   17664 
   17665   /* Initialize the master block. */
   17666   mem3.szMaster = mem3.nPool;
   17667   mem3.mnMaster = mem3.szMaster;
   17668   mem3.iMaster = 1;
   17669   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
   17670   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
   17671   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
   17672 
   17673   return SQLITE_OK;
   17674 }
   17675 
   17676 /*
   17677 ** Deinitialize this module.
   17678 */
   17679 static void memsys3Shutdown(void *NotUsed){
   17680   UNUSED_PARAMETER(NotUsed);
   17681   mem3.mutex = 0;
   17682   return;
   17683 }
   17684 
   17685 
   17686 
   17687 /*
   17688 ** Open the file indicated and write a log of all unfreed memory
   17689 ** allocations into that log.
   17690 */
   17691 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
   17692 #ifdef SQLITE_DEBUG
   17693   FILE *out;
   17694   u32 i, j;
   17695   u32 size;
   17696   if( zFilename==0 || zFilename[0]==0 ){
   17697     out = stdout;
   17698   }else{
   17699     out = fopen(zFilename, "w");
   17700     if( out==0 ){
   17701       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   17702                       zFilename);
   17703       return;
   17704     }
   17705   }
   17706   memsys3Enter();
   17707   fprintf(out, "CHUNKS:\n");
   17708   for(i=1; i<=mem3.nPool; i+=size/4){
   17709     size = mem3.aPool[i-1].u.hdr.size4x;
   17710     if( size/4<=1 ){
   17711       fprintf(out, "%p size error\n", &mem3.aPool[i]);
   17712       assert( 0 );
   17713       break;
   17714     }
   17715     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
   17716       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
   17717       assert( 0 );
   17718       break;
   17719     }
   17720     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
   17721       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
   17722       assert( 0 );
   17723       break;
   17724     }
   17725     if( size&1 ){
   17726       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
   17727     }else{
   17728       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
   17729                   i==mem3.iMaster ? " **master**" : "");
   17730     }
   17731   }
   17732   for(i=0; i<MX_SMALL-1; i++){
   17733     if( mem3.aiSmall[i]==0 ) continue;
   17734     fprintf(out, "small(%2d):", i);
   17735     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
   17736       fprintf(out, " %p(%d)", &mem3.aPool[j],
   17737               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   17738     }
   17739     fprintf(out, "\n");
   17740   }
   17741   for(i=0; i<N_HASH; i++){
   17742     if( mem3.aiHash[i]==0 ) continue;
   17743     fprintf(out, "hash(%2d):", i);
   17744     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
   17745       fprintf(out, " %p(%d)", &mem3.aPool[j],
   17746               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   17747     }
   17748     fprintf(out, "\n");
   17749   }
   17750   fprintf(out, "master=%d\n", mem3.iMaster);
   17751   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
   17752   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
   17753   sqlite3_mutex_leave(mem3.mutex);
   17754   if( out==stdout ){
   17755     fflush(stdout);
   17756   }else{
   17757     fclose(out);
   17758   }
   17759 #else
   17760   UNUSED_PARAMETER(zFilename);
   17761 #endif
   17762 }
   17763 
   17764 /*
   17765 ** This routine is the only routine in this file with external
   17766 ** linkage.
   17767 **
   17768 ** Populate the low-level memory allocation function pointers in
   17769 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   17770 ** arguments specify the block of memory to manage.
   17771 **
   17772 ** This routine is only called by sqlite3_config(), and therefore
   17773 ** is not required to be threadsafe (it is not).
   17774 */
   17775 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
   17776   static const sqlite3_mem_methods mempoolMethods = {
   17777      memsys3Malloc,
   17778      memsys3Free,
   17779      memsys3Realloc,
   17780      memsys3Size,
   17781      memsys3Roundup,
   17782      memsys3Init,
   17783      memsys3Shutdown,
   17784      0
   17785   };
   17786   return &mempoolMethods;
   17787 }
   17788 
   17789 #endif /* SQLITE_ENABLE_MEMSYS3 */
   17790 
   17791 /************** End of mem3.c ************************************************/
   17792 /************** Begin file mem5.c ********************************************/
   17793 /*
   17794 ** 2007 October 14
   17795 **
   17796 ** The author disclaims copyright to this source code.  In place of
   17797 ** a legal notice, here is a blessing:
   17798 **
   17799 **    May you do good and not evil.
   17800 **    May you find forgiveness for yourself and forgive others.
   17801 **    May you share freely, never taking more than you give.
   17802 **
   17803 *************************************************************************
   17804 ** This file contains the C functions that implement a memory
   17805 ** allocation subsystem for use by SQLite.
   17806 **
   17807 ** This version of the memory allocation subsystem omits all
   17808 ** use of malloc(). The application gives SQLite a block of memory
   17809 ** before calling sqlite3_initialize() from which allocations
   17810 ** are made and returned by the xMalloc() and xRealloc()
   17811 ** implementations. Once sqlite3_initialize() has been called,
   17812 ** the amount of memory available to SQLite is fixed and cannot
   17813 ** be changed.
   17814 **
   17815 ** This version of the memory allocation subsystem is included
   17816 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
   17817 **
   17818 ** This memory allocator uses the following algorithm:
   17819 **
   17820 **   1.  All memory allocations sizes are rounded up to a power of 2.
   17821 **
   17822 **   2.  If two adjacent free blocks are the halves of a larger block,
   17823 **       then the two blocks are coalesed into the single larger block.
   17824 **
   17825 **   3.  New memory is allocated from the first available free block.
   17826 **
   17827 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
   17828 ** Concerning Dynamic Storage Allocation". Journal of the Association for
   17829 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
   17830 **
   17831 ** Let n be the size of the largest allocation divided by the minimum
   17832 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
   17833 ** be the maximum amount of memory ever outstanding at one time.  Let
   17834 ** N be the total amount of memory available for allocation.  Robson
   17835 ** proved that this memory allocator will never breakdown due to
   17836 ** fragmentation as long as the following constraint holds:
   17837 **
   17838 **      N >=  M*(1 + log2(n)/2) - n + 1
   17839 **
   17840 ** The sqlite3_status() logic tracks the maximum values of n and M so
   17841 ** that an application can, at any time, verify this constraint.
   17842 */
   17843 
   17844 /*
   17845 ** This version of the memory allocator is used only when
   17846 ** SQLITE_ENABLE_MEMSYS5 is defined.
   17847 */
   17848 #ifdef SQLITE_ENABLE_MEMSYS5
   17849 
   17850 /*
   17851 ** A minimum allocation is an instance of the following structure.
   17852 ** Larger allocations are an array of these structures where the
   17853 ** size of the array is a power of 2.
   17854 **
   17855 ** The size of this object must be a power of two.  That fact is
   17856 ** verified in memsys5Init().
   17857 */
   17858 typedef struct Mem5Link Mem5Link;
   17859 struct Mem5Link {
   17860   int next;       /* Index of next free chunk */
   17861   int prev;       /* Index of previous free chunk */
   17862 };
   17863 
   17864 /*
   17865 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
   17866 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
   17867 ** it is not actually possible to reach this limit.
   17868 */
   17869 #define LOGMAX 30
   17870 
   17871 /*
   17872 ** Masks used for mem5.aCtrl[] elements.
   17873 */
   17874 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
   17875 #define CTRL_FREE     0x20    /* True if not checked out */
   17876 
   17877 /*
   17878 ** All of the static variables used by this module are collected
   17879 ** into a single structure named "mem5".  This is to keep the
   17880 ** static variables organized and to reduce namespace pollution
   17881 ** when this module is combined with other in the amalgamation.
   17882 */
   17883 static SQLITE_WSD struct Mem5Global {
   17884   /*
   17885   ** Memory available for allocation
   17886   */
   17887   int szAtom;      /* Smallest possible allocation in bytes */
   17888   int nBlock;      /* Number of szAtom sized blocks in zPool */
   17889   u8 *zPool;       /* Memory available to be allocated */
   17890 
   17891   /*
   17892   ** Mutex to control access to the memory allocation subsystem.
   17893   */
   17894   sqlite3_mutex *mutex;
   17895 
   17896   /*
   17897   ** Performance statistics
   17898   */
   17899   u64 nAlloc;         /* Total number of calls to malloc */
   17900   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
   17901   u64 totalExcess;    /* Total internal fragmentation */
   17902   u32 currentOut;     /* Current checkout, including internal fragmentation */
   17903   u32 currentCount;   /* Current number of distinct checkouts */
   17904   u32 maxOut;         /* Maximum instantaneous currentOut */
   17905   u32 maxCount;       /* Maximum instantaneous currentCount */
   17906   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
   17907 
   17908   /*
   17909   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
   17910   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
   17911   ** and so forth.
   17912   */
   17913   int aiFreelist[LOGMAX+1];
   17914 
   17915   /*
   17916   ** Space for tracking which blocks are checked out and the size
   17917   ** of each block.  One byte per block.
   17918   */
   17919   u8 *aCtrl;
   17920 
   17921 } mem5;
   17922 
   17923 /*
   17924 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
   17925 */
   17926 #define mem5 GLOBAL(struct Mem5Global, mem5)
   17927 
   17928 /*
   17929 ** Assuming mem5.zPool is divided up into an array of Mem5Link
   17930 ** structures, return a pointer to the idx-th such link.
   17931 */
   17932 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
   17933 
   17934 /*
   17935 ** Unlink the chunk at mem5.aPool[i] from list it is currently
   17936 ** on.  It should be found on mem5.aiFreelist[iLogsize].
   17937 */
   17938 static void memsys5Unlink(int i, int iLogsize){
   17939   int next, prev;
   17940   assert( i>=0 && i<mem5.nBlock );
   17941   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   17942   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   17943 
   17944   next = MEM5LINK(i)->next;
   17945   prev = MEM5LINK(i)->prev;
   17946   if( prev<0 ){
   17947     mem5.aiFreelist[iLogsize] = next;
   17948   }else{
   17949     MEM5LINK(prev)->next = next;
   17950   }
   17951   if( next>=0 ){
   17952     MEM5LINK(next)->prev = prev;
   17953   }
   17954 }
   17955 
   17956 /*
   17957 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
   17958 ** free list.
   17959 */
   17960 static void memsys5Link(int i, int iLogsize){
   17961   int x;
   17962   assert( sqlite3_mutex_held(mem5.mutex) );
   17963   assert( i>=0 && i<mem5.nBlock );
   17964   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   17965   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   17966 
   17967   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
   17968   MEM5LINK(i)->prev = -1;
   17969   if( x>=0 ){
   17970     assert( x<mem5.nBlock );
   17971     MEM5LINK(x)->prev = i;
   17972   }
   17973   mem5.aiFreelist[iLogsize] = i;
   17974 }
   17975 
   17976 /*
   17977 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   17978 ** will already be held (obtained by code in malloc.c) if
   17979 ** sqlite3GlobalConfig.bMemStat is true.
   17980 */
   17981 static void memsys5Enter(void){
   17982   sqlite3_mutex_enter(mem5.mutex);
   17983 }
   17984 static void memsys5Leave(void){
   17985   sqlite3_mutex_leave(mem5.mutex);
   17986 }
   17987 
   17988 /*
   17989 ** Return the size of an outstanding allocation, in bytes.  The
   17990 ** size returned omits the 8-byte header overhead.  This only
   17991 ** works for chunks that are currently checked out.
   17992 */
   17993 static int memsys5Size(void *p){
   17994   int iSize = 0;
   17995   if( p ){
   17996     int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
   17997     assert( i>=0 && i<mem5.nBlock );
   17998     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
   17999   }
   18000   return iSize;
   18001 }
   18002 
   18003 /*
   18004 ** Return a block of memory of at least nBytes in size.
   18005 ** Return NULL if unable.  Return NULL if nBytes==0.
   18006 **
   18007 ** The caller guarantees that nByte is positive.
   18008 **
   18009 ** The caller has obtained a mutex prior to invoking this
   18010 ** routine so there is never any chance that two or more
   18011 ** threads can be in this routine at the same time.
   18012 */
   18013 static void *memsys5MallocUnsafe(int nByte){
   18014   int i;           /* Index of a mem5.aPool[] slot */
   18015   int iBin;        /* Index into mem5.aiFreelist[] */
   18016   int iFullSz;     /* Size of allocation rounded up to power of 2 */
   18017   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
   18018 
   18019   /* nByte must be a positive */
   18020   assert( nByte>0 );
   18021 
   18022   /* Keep track of the maximum allocation request.  Even unfulfilled
   18023   ** requests are counted */
   18024   if( (u32)nByte>mem5.maxRequest ){
   18025     mem5.maxRequest = nByte;
   18026   }
   18027 
   18028   /* Abort if the requested allocation size is larger than the largest
   18029   ** power of two that we can represent using 32-bit signed integers.
   18030   */
   18031   if( nByte > 0x40000000 ){
   18032     return 0;
   18033   }
   18034 
   18035   /* Round nByte up to the next valid power of two */
   18036   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
   18037 
   18038   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
   18039   ** block.  If not, then split a block of the next larger power of
   18040   ** two in order to create a new free block of size iLogsize.
   18041   */
   18042   for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
   18043   if( iBin>LOGMAX ){
   18044     testcase( sqlite3GlobalConfig.xLog!=0 );
   18045     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
   18046     return 0;
   18047   }
   18048   i = mem5.aiFreelist[iBin];
   18049   memsys5Unlink(i, iBin);
   18050   while( iBin>iLogsize ){
   18051     int newSize;
   18052 
   18053     iBin--;
   18054     newSize = 1 << iBin;
   18055     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
   18056     memsys5Link(i+newSize, iBin);
   18057   }
   18058   mem5.aCtrl[i] = iLogsize;
   18059 
   18060   /* Update allocator performance statistics. */
   18061   mem5.nAlloc++;
   18062   mem5.totalAlloc += iFullSz;
   18063   mem5.totalExcess += iFullSz - nByte;
   18064   mem5.currentCount++;
   18065   mem5.currentOut += iFullSz;
   18066   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
   18067   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
   18068 
   18069 #ifdef SQLITE_DEBUG
   18070   /* Make sure the allocated memory does not assume that it is set to zero
   18071   ** or retains a value from a previous allocation */
   18072   memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
   18073 #endif
   18074 
   18075   /* Return a pointer to the allocated memory. */
   18076   return (void*)&mem5.zPool[i*mem5.szAtom];
   18077 }
   18078 
   18079 /*
   18080 ** Free an outstanding memory allocation.
   18081 */
   18082 static void memsys5FreeUnsafe(void *pOld){
   18083   u32 size, iLogsize;
   18084   int iBlock;
   18085 
   18086   /* Set iBlock to the index of the block pointed to by pOld in
   18087   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
   18088   */
   18089   iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
   18090 
   18091   /* Check that the pointer pOld points to a valid, non-free block. */
   18092   assert( iBlock>=0 && iBlock<mem5.nBlock );
   18093   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
   18094   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
   18095 
   18096   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
   18097   size = 1<<iLogsize;
   18098   assert( iBlock+size-1<(u32)mem5.nBlock );
   18099 
   18100   mem5.aCtrl[iBlock] |= CTRL_FREE;
   18101   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
   18102   assert( mem5.currentCount>0 );
   18103   assert( mem5.currentOut>=(size*mem5.szAtom) );
   18104   mem5.currentCount--;
   18105   mem5.currentOut -= size*mem5.szAtom;
   18106   assert( mem5.currentOut>0 || mem5.currentCount==0 );
   18107   assert( mem5.currentCount>0 || mem5.currentOut==0 );
   18108 
   18109   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   18110   while( ALWAYS(iLogsize<LOGMAX) ){
   18111     int iBuddy;
   18112     if( (iBlock>>iLogsize) & 1 ){
   18113       iBuddy = iBlock - size;
   18114     }else{
   18115       iBuddy = iBlock + size;
   18116     }
   18117     assert( iBuddy>=0 );
   18118     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
   18119     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
   18120     memsys5Unlink(iBuddy, iLogsize);
   18121     iLogsize++;
   18122     if( iBuddy<iBlock ){
   18123       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
   18124       mem5.aCtrl[iBlock] = 0;
   18125       iBlock = iBuddy;
   18126     }else{
   18127       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   18128       mem5.aCtrl[iBuddy] = 0;
   18129     }
   18130     size *= 2;
   18131   }
   18132 
   18133 #ifdef SQLITE_DEBUG
   18134   /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
   18135   ** not used after being freed */
   18136   memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
   18137 #endif
   18138 
   18139   memsys5Link(iBlock, iLogsize);
   18140 }
   18141 
   18142 /*
   18143 ** Allocate nBytes of memory.
   18144 */
   18145 static void *memsys5Malloc(int nBytes){
   18146   sqlite3_int64 *p = 0;
   18147   if( nBytes>0 ){
   18148     memsys5Enter();
   18149     p = memsys5MallocUnsafe(nBytes);
   18150     memsys5Leave();
   18151   }
   18152   return (void*)p;
   18153 }
   18154 
   18155 /*
   18156 ** Free memory.
   18157 **
   18158 ** The outer layer memory allocator prevents this routine from
   18159 ** being called with pPrior==0.
   18160 */
   18161 static void memsys5Free(void *pPrior){
   18162   assert( pPrior!=0 );
   18163   memsys5Enter();
   18164   memsys5FreeUnsafe(pPrior);
   18165   memsys5Leave();
   18166 }
   18167 
   18168 /*
   18169 ** Change the size of an existing memory allocation.
   18170 **
   18171 ** The outer layer memory allocator prevents this routine from
   18172 ** being called with pPrior==0.
   18173 **
   18174 ** nBytes is always a value obtained from a prior call to
   18175 ** memsys5Round().  Hence nBytes is always a non-negative power
   18176 ** of two.  If nBytes==0 that means that an oversize allocation
   18177 ** (an allocation larger than 0x40000000) was requested and this
   18178 ** routine should return 0 without freeing pPrior.
   18179 */
   18180 static void *memsys5Realloc(void *pPrior, int nBytes){
   18181   int nOld;
   18182   void *p;
   18183   assert( pPrior!=0 );
   18184   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
   18185   assert( nBytes>=0 );
   18186   if( nBytes==0 ){
   18187     return 0;
   18188   }
   18189   nOld = memsys5Size(pPrior);
   18190   if( nBytes<=nOld ){
   18191     return pPrior;
   18192   }
   18193   memsys5Enter();
   18194   p = memsys5MallocUnsafe(nBytes);
   18195   if( p ){
   18196     memcpy(p, pPrior, nOld);
   18197     memsys5FreeUnsafe(pPrior);
   18198   }
   18199   memsys5Leave();
   18200   return p;
   18201 }
   18202 
   18203 /*
   18204 ** Round up a request size to the next valid allocation size.  If
   18205 ** the allocation is too large to be handled by this allocation system,
   18206 ** return 0.
   18207 **
   18208 ** All allocations must be a power of two and must be expressed by a
   18209 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
   18210 ** or 1073741824 bytes.
   18211 */
   18212 static int memsys5Roundup(int n){
   18213   int iFullSz;
   18214   if( n > 0x40000000 ) return 0;
   18215   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
   18216   return iFullSz;
   18217 }
   18218 
   18219 /*
   18220 ** Return the ceiling of the logarithm base 2 of iValue.
   18221 **
   18222 ** Examples:   memsys5Log(1) -> 0
   18223 **             memsys5Log(2) -> 1
   18224 **             memsys5Log(4) -> 2
   18225 **             memsys5Log(5) -> 3
   18226 **             memsys5Log(8) -> 3
   18227 **             memsys5Log(9) -> 4
   18228 */
   18229 static int memsys5Log(int iValue){
   18230   int iLog;
   18231   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
   18232   return iLog;
   18233 }
   18234 
   18235 /*
   18236 ** Initialize the memory allocator.
   18237 **
   18238 ** This routine is not threadsafe.  The caller must be holding a mutex
   18239 ** to prevent multiple threads from entering at the same time.
   18240 */
   18241 static int memsys5Init(void *NotUsed){
   18242   int ii;            /* Loop counter */
   18243   int nByte;         /* Number of bytes of memory available to this allocator */
   18244   u8 *zByte;         /* Memory usable by this allocator */
   18245   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
   18246   int iOffset;       /* An offset into mem5.aCtrl[] */
   18247 
   18248   UNUSED_PARAMETER(NotUsed);
   18249 
   18250   /* For the purposes of this routine, disable the mutex */
   18251   mem5.mutex = 0;
   18252 
   18253   /* The size of a Mem5Link object must be a power of two.  Verify that
   18254   ** this is case.
   18255   */
   18256   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
   18257 
   18258   nByte = sqlite3GlobalConfig.nHeap;
   18259   zByte = (u8*)sqlite3GlobalConfig.pHeap;
   18260   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
   18261 
   18262   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
   18263   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
   18264   mem5.szAtom = (1<<nMinLog);
   18265   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
   18266     mem5.szAtom = mem5.szAtom << 1;
   18267   }
   18268 
   18269   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
   18270   mem5.zPool = zByte;
   18271   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
   18272 
   18273   for(ii=0; ii<=LOGMAX; ii++){
   18274     mem5.aiFreelist[ii] = -1;
   18275   }
   18276 
   18277   iOffset = 0;
   18278   for(ii=LOGMAX; ii>=0; ii--){
   18279     int nAlloc = (1<<ii);
   18280     if( (iOffset+nAlloc)<=mem5.nBlock ){
   18281       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
   18282       memsys5Link(iOffset, ii);
   18283       iOffset += nAlloc;
   18284     }
   18285     assert((iOffset+nAlloc)>mem5.nBlock);
   18286   }
   18287 
   18288   /* If a mutex is required for normal operation, allocate one */
   18289   if( sqlite3GlobalConfig.bMemstat==0 ){
   18290     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   18291   }
   18292 
   18293   return SQLITE_OK;
   18294 }
   18295 
   18296 /*
   18297 ** Deinitialize this module.
   18298 */
   18299 static void memsys5Shutdown(void *NotUsed){
   18300   UNUSED_PARAMETER(NotUsed);
   18301   mem5.mutex = 0;
   18302   return;
   18303 }
   18304 
   18305 #ifdef SQLITE_TEST
   18306 /*
   18307 ** Open the file indicated and write a log of all unfreed memory
   18308 ** allocations into that log.
   18309 */
   18310 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
   18311   FILE *out;
   18312   int i, j, n;
   18313   int nMinLog;
   18314 
   18315   if( zFilename==0 || zFilename[0]==0 ){
   18316     out = stdout;
   18317   }else{
   18318     out = fopen(zFilename, "w");
   18319     if( out==0 ){
   18320       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   18321                       zFilename);
   18322       return;
   18323     }
   18324   }
   18325   memsys5Enter();
   18326   nMinLog = memsys5Log(mem5.szAtom);
   18327   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
   18328     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
   18329     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
   18330   }
   18331   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
   18332   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
   18333   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
   18334   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
   18335   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
   18336   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
   18337   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
   18338   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
   18339   memsys5Leave();
   18340   if( out==stdout ){
   18341     fflush(stdout);
   18342   }else{
   18343     fclose(out);
   18344   }
   18345 }
   18346 #endif
   18347 
   18348 /*
   18349 ** This routine is the only routine in this file with external
   18350 ** linkage. It returns a pointer to a static sqlite3_mem_methods
   18351 ** struct populated with the memsys5 methods.
   18352 */
   18353 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
   18354   static const sqlite3_mem_methods memsys5Methods = {
   18355      memsys5Malloc,
   18356      memsys5Free,
   18357      memsys5Realloc,
   18358      memsys5Size,
   18359      memsys5Roundup,
   18360      memsys5Init,
   18361      memsys5Shutdown,
   18362      0
   18363   };
   18364   return &memsys5Methods;
   18365 }
   18366 
   18367 #endif /* SQLITE_ENABLE_MEMSYS5 */
   18368 
   18369 /************** End of mem5.c ************************************************/
   18370 /************** Begin file mutex.c *******************************************/
   18371 /*
   18372 ** 2007 August 14
   18373 **
   18374 ** The author disclaims copyright to this source code.  In place of
   18375 ** a legal notice, here is a blessing:
   18376 **
   18377 **    May you do good and not evil.
   18378 **    May you find forgiveness for yourself and forgive others.
   18379 **    May you share freely, never taking more than you give.
   18380 **
   18381 *************************************************************************
   18382 ** This file contains the C functions that implement mutexes.
   18383 **
   18384 ** This file contains code that is common across all mutex implementations.
   18385 */
   18386 
   18387 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
   18388 /*
   18389 ** For debugging purposes, record when the mutex subsystem is initialized
   18390 ** and uninitialized so that we can assert() if there is an attempt to
   18391 ** allocate a mutex while the system is uninitialized.
   18392 */
   18393 static SQLITE_WSD int mutexIsInit = 0;
   18394 #endif /* SQLITE_DEBUG */
   18395 
   18396 
   18397 #ifndef SQLITE_MUTEX_OMIT
   18398 /*
   18399 ** Initialize the mutex system.
   18400 */
   18401 SQLITE_PRIVATE int sqlite3MutexInit(void){
   18402   int rc = SQLITE_OK;
   18403   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
   18404     /* If the xMutexAlloc method has not been set, then the user did not
   18405     ** install a mutex implementation via sqlite3_config() prior to
   18406     ** sqlite3_initialize() being called. This block copies pointers to
   18407     ** the default implementation into the sqlite3GlobalConfig structure.
   18408     */
   18409     sqlite3_mutex_methods const *pFrom;
   18410     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
   18411 
   18412     if( sqlite3GlobalConfig.bCoreMutex ){
   18413       pFrom = sqlite3DefaultMutex();
   18414     }else{
   18415       pFrom = sqlite3NoopMutex();
   18416     }
   18417     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
   18418     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
   18419            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
   18420     pTo->xMutexAlloc = pFrom->xMutexAlloc;
   18421   }
   18422   rc = sqlite3GlobalConfig.mutex.xMutexInit();
   18423 
   18424 #ifdef SQLITE_DEBUG
   18425   GLOBAL(int, mutexIsInit) = 1;
   18426 #endif
   18427 
   18428   return rc;
   18429 }
   18430 
   18431 /*
   18432 ** Shutdown the mutex system. This call frees resources allocated by
   18433 ** sqlite3MutexInit().
   18434 */
   18435 SQLITE_PRIVATE int sqlite3MutexEnd(void){
   18436   int rc = SQLITE_OK;
   18437   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
   18438     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
   18439   }
   18440 
   18441 #ifdef SQLITE_DEBUG
   18442   GLOBAL(int, mutexIsInit) = 0;
   18443 #endif
   18444 
   18445   return rc;
   18446 }
   18447 
   18448 /*
   18449 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
   18450 */
   18451 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
   18452 #ifndef SQLITE_OMIT_AUTOINIT
   18453   if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
   18454 #endif
   18455   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   18456 }
   18457 
   18458 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
   18459   if( !sqlite3GlobalConfig.bCoreMutex ){
   18460     return 0;
   18461   }
   18462   assert( GLOBAL(int, mutexIsInit) );
   18463   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   18464 }
   18465 
   18466 /*
   18467 ** Free a dynamic mutex.
   18468 */
   18469 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
   18470   if( p ){
   18471     sqlite3GlobalConfig.mutex.xMutexFree(p);
   18472   }
   18473 }
   18474 
   18475 /*
   18476 ** Obtain the mutex p. If some other thread already has the mutex, block
   18477 ** until it can be obtained.
   18478 */
   18479 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
   18480   if( p ){
   18481     sqlite3GlobalConfig.mutex.xMutexEnter(p);
   18482   }
   18483 }
   18484 
   18485 /*
   18486 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
   18487 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
   18488 */
   18489 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
   18490   int rc = SQLITE_OK;
   18491   if( p ){
   18492     return sqlite3GlobalConfig.mutex.xMutexTry(p);
   18493   }
   18494   return rc;
   18495 }
   18496 
   18497 /*
   18498 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
   18499 ** entered by the same thread.  The behavior is undefined if the mutex
   18500 ** is not currently entered. If a NULL pointer is passed as an argument
   18501 ** this function is a no-op.
   18502 */
   18503 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
   18504   if( p ){
   18505     sqlite3GlobalConfig.mutex.xMutexLeave(p);
   18506   }
   18507 }
   18508 
   18509 #ifndef NDEBUG
   18510 /*
   18511 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   18512 ** intended for use inside assert() statements.
   18513 */
   18514 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
   18515   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
   18516 }
   18517 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
   18518   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
   18519 }
   18520 #endif
   18521 
   18522 #endif /* !defined(SQLITE_MUTEX_OMIT) */
   18523 
   18524 /************** End of mutex.c ***********************************************/
   18525 /************** Begin file mutex_noop.c **************************************/
   18526 /*
   18527 ** 2008 October 07
   18528 **
   18529 ** The author disclaims copyright to this source code.  In place of
   18530 ** a legal notice, here is a blessing:
   18531 **
   18532 **    May you do good and not evil.
   18533 **    May you find forgiveness for yourself and forgive others.
   18534 **    May you share freely, never taking more than you give.
   18535 **
   18536 *************************************************************************
   18537 ** This file contains the C functions that implement mutexes.
   18538 **
   18539 ** This implementation in this file does not provide any mutual
   18540 ** exclusion and is thus suitable for use only in applications
   18541 ** that use SQLite in a single thread.  The routines defined
   18542 ** here are place-holders.  Applications can substitute working
   18543 ** mutex routines at start-time using the
   18544 **
   18545 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
   18546 **
   18547 ** interface.
   18548 **
   18549 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
   18550 ** that does error checking on mutexes to make sure they are being
   18551 ** called correctly.
   18552 */
   18553 
   18554 #ifndef SQLITE_MUTEX_OMIT
   18555 
   18556 #ifndef SQLITE_DEBUG
   18557 /*
   18558 ** Stub routines for all mutex methods.
   18559 **
   18560 ** This routines provide no mutual exclusion or error checking.
   18561 */
   18562 static int noopMutexInit(void){ return SQLITE_OK; }
   18563 static int noopMutexEnd(void){ return SQLITE_OK; }
   18564 static sqlite3_mutex *noopMutexAlloc(int id){
   18565   UNUSED_PARAMETER(id);
   18566   return (sqlite3_mutex*)8;
   18567 }
   18568 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   18569 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   18570 static int noopMutexTry(sqlite3_mutex *p){
   18571   UNUSED_PARAMETER(p);
   18572   return SQLITE_OK;
   18573 }
   18574 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   18575 
   18576 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
   18577   static const sqlite3_mutex_methods sMutex = {
   18578     noopMutexInit,
   18579     noopMutexEnd,
   18580     noopMutexAlloc,
   18581     noopMutexFree,
   18582     noopMutexEnter,
   18583     noopMutexTry,
   18584     noopMutexLeave,
   18585 
   18586     0,
   18587     0,
   18588   };
   18589 
   18590   return &sMutex;
   18591 }
   18592 #endif /* !SQLITE_DEBUG */
   18593 
   18594 #ifdef SQLITE_DEBUG
   18595 /*
   18596 ** In this implementation, error checking is provided for testing
   18597 ** and debugging purposes.  The mutexes still do not provide any
   18598 ** mutual exclusion.
   18599 */
   18600 
   18601 /*
   18602 ** The mutex object
   18603 */
   18604 typedef struct sqlite3_debug_mutex {
   18605   int id;     /* The mutex type */
   18606   int cnt;    /* Number of entries without a matching leave */
   18607 } sqlite3_debug_mutex;
   18608 
   18609 /*
   18610 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   18611 ** intended for use inside assert() statements.
   18612 */
   18613 static int debugMutexHeld(sqlite3_mutex *pX){
   18614   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   18615   return p==0 || p->cnt>0;
   18616 }
   18617 static int debugMutexNotheld(sqlite3_mutex *pX){
   18618   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   18619   return p==0 || p->cnt==0;
   18620 }
   18621 
   18622 /*
   18623 ** Initialize and deinitialize the mutex subsystem.
   18624 */
   18625 static int debugMutexInit(void){ return SQLITE_OK; }
   18626 static int debugMutexEnd(void){ return SQLITE_OK; }
   18627 
   18628 /*
   18629 ** The sqlite3_mutex_alloc() routine allocates a new
   18630 ** mutex and returns a pointer to it.  If it returns NULL
   18631 ** that means that a mutex could not be allocated.
   18632 */
   18633 static sqlite3_mutex *debugMutexAlloc(int id){
   18634   static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
   18635   sqlite3_debug_mutex *pNew = 0;
   18636   switch( id ){
   18637     case SQLITE_MUTEX_FAST:
   18638     case SQLITE_MUTEX_RECURSIVE: {
   18639       pNew = sqlite3Malloc(sizeof(*pNew));
   18640       if( pNew ){
   18641         pNew->id = id;
   18642         pNew->cnt = 0;
   18643       }
   18644       break;
   18645     }
   18646     default: {
   18647       assert( id-2 >= 0 );
   18648       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
   18649       pNew = &aStatic[id-2];
   18650       pNew->id = id;
   18651       break;
   18652     }
   18653   }
   18654   return (sqlite3_mutex*)pNew;
   18655 }
   18656 
   18657 /*
   18658 ** This routine deallocates a previously allocated mutex.
   18659 */
   18660 static void debugMutexFree(sqlite3_mutex *pX){
   18661   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   18662   assert( p->cnt==0 );
   18663   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   18664   sqlite3_free(p);
   18665 }
   18666 
   18667 /*
   18668 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   18669 ** to enter a mutex.  If another thread is already within the mutex,
   18670 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   18671 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   18672 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   18673 ** be entered multiple times by the same thread.  In such cases the,
   18674 ** mutex must be exited an equal number of times before another thread
   18675 ** can enter.  If the same thread tries to enter any other kind of mutex
   18676 ** more than once, the behavior is undefined.
   18677 */
   18678 static void debugMutexEnter(sqlite3_mutex *pX){
   18679   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   18680   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   18681   p->cnt++;
   18682 }
   18683 static int debugMutexTry(sqlite3_mutex *pX){
   18684   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   18685   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   18686   p->cnt++;
   18687   return SQLITE_OK;
   18688 }
   18689 
   18690 /*
   18691 ** The sqlite3_mutex_leave() routine exits a mutex that was
   18692 ** previously entered by the same thread.  The behavior
   18693 ** is undefined if the mutex is not currently entered or
   18694 ** is not currently allocated.  SQLite will never do either.
   18695 */
   18696 static void debugMutexLeave(sqlite3_mutex *pX){
   18697   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   18698   assert( debugMutexHeld(pX) );
   18699   p->cnt--;
   18700   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   18701 }
   18702 
   18703 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
   18704   static const sqlite3_mutex_methods sMutex = {
   18705     debugMutexInit,
   18706     debugMutexEnd,
   18707     debugMutexAlloc,
   18708     debugMutexFree,
   18709     debugMutexEnter,
   18710     debugMutexTry,
   18711     debugMutexLeave,
   18712 
   18713     debugMutexHeld,
   18714     debugMutexNotheld
   18715   };
   18716 
   18717   return &sMutex;
   18718 }
   18719 #endif /* SQLITE_DEBUG */
   18720 
   18721 /*
   18722 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
   18723 ** is used regardless of the run-time threadsafety setting.
   18724 */
   18725 #ifdef SQLITE_MUTEX_NOOP
   18726 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   18727   return sqlite3NoopMutex();
   18728 }
   18729 #endif /* defined(SQLITE_MUTEX_NOOP) */
   18730 #endif /* !defined(SQLITE_MUTEX_OMIT) */
   18731 
   18732 /************** End of mutex_noop.c ******************************************/
   18733 /************** Begin file mutex_unix.c **************************************/
   18734 /*
   18735 ** 2007 August 28
   18736 **
   18737 ** The author disclaims copyright to this source code.  In place of
   18738 ** a legal notice, here is a blessing:
   18739 **
   18740 **    May you do good and not evil.
   18741 **    May you find forgiveness for yourself and forgive others.
   18742 **    May you share freely, never taking more than you give.
   18743 **
   18744 *************************************************************************
   18745 ** This file contains the C functions that implement mutexes for pthreads
   18746 */
   18747 
   18748 /*
   18749 ** The code in this file is only used if we are compiling threadsafe
   18750 ** under unix with pthreads.
   18751 **
   18752 ** Note that this implementation requires a version of pthreads that
   18753 ** supports recursive mutexes.
   18754 */
   18755 #ifdef SQLITE_MUTEX_PTHREADS
   18756 
   18757 #include <pthread.h>
   18758 
   18759 /*
   18760 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
   18761 ** are necessary under two condidtions:  (1) Debug builds and (2) using
   18762 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
   18763 */
   18764 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
   18765 # define SQLITE_MUTEX_NREF 1
   18766 #else
   18767 # define SQLITE_MUTEX_NREF 0
   18768 #endif
   18769 
   18770 /*
   18771 ** Each recursive mutex is an instance of the following structure.
   18772 */
   18773 struct sqlite3_mutex {
   18774   pthread_mutex_t mutex;     /* Mutex controlling the lock */
   18775 #if SQLITE_MUTEX_NREF
   18776   int id;                    /* Mutex type */
   18777   volatile int nRef;         /* Number of entrances */
   18778   volatile pthread_t owner;  /* Thread that is within this mutex */
   18779   int trace;                 /* True to trace changes */
   18780 #endif
   18781 };
   18782 #if SQLITE_MUTEX_NREF
   18783 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
   18784 #else
   18785 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
   18786 #endif
   18787 
   18788 /*
   18789 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   18790 ** intended for use only inside assert() statements.  On some platforms,
   18791 ** there might be race conditions that can cause these routines to
   18792 ** deliver incorrect results.  In particular, if pthread_equal() is
   18793 ** not an atomic operation, then these routines might delivery
   18794 ** incorrect results.  On most platforms, pthread_equal() is a
   18795 ** comparison of two integers and is therefore atomic.  But we are
   18796 ** told that HPUX is not such a platform.  If so, then these routines
   18797 ** will not always work correctly on HPUX.
   18798 **
   18799 ** On those platforms where pthread_equal() is not atomic, SQLite
   18800 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
   18801 ** make sure no assert() statements are evaluated and hence these
   18802 ** routines are never called.
   18803 */
   18804 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
   18805 static int pthreadMutexHeld(sqlite3_mutex *p){
   18806   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
   18807 }
   18808 static int pthreadMutexNotheld(sqlite3_mutex *p){
   18809   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
   18810 }
   18811 #endif
   18812 
   18813 /*
   18814 ** Initialize and deinitialize the mutex subsystem.
   18815 */
   18816 static int pthreadMutexInit(void){ return SQLITE_OK; }
   18817 static int pthreadMutexEnd(void){ return SQLITE_OK; }
   18818 
   18819 /*
   18820 ** The sqlite3_mutex_alloc() routine allocates a new
   18821 ** mutex and returns a pointer to it.  If it returns NULL
   18822 ** that means that a mutex could not be allocated.  SQLite
   18823 ** will unwind its stack and return an error.  The argument
   18824 ** to sqlite3_mutex_alloc() is one of these integer constants:
   18825 **
   18826 ** <ul>
   18827 ** <li>  SQLITE_MUTEX_FAST
   18828 ** <li>  SQLITE_MUTEX_RECURSIVE
   18829 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   18830 ** <li>  SQLITE_MUTEX_STATIC_MEM
   18831 ** <li>  SQLITE_MUTEX_STATIC_OPEN
   18832 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   18833 ** <li>  SQLITE_MUTEX_STATIC_LRU
   18834 ** <li>  SQLITE_MUTEX_STATIC_PMEM
   18835 ** <li>  SQLITE_MUTEX_STATIC_APP1
   18836 ** <li>  SQLITE_MUTEX_STATIC_APP2
   18837 ** <li>  SQLITE_MUTEX_STATIC_APP3
   18838 ** </ul>
   18839 **
   18840 ** The first two constants cause sqlite3_mutex_alloc() to create
   18841 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   18842 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   18843 ** The mutex implementation does not need to make a distinction
   18844 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   18845 ** not want to.  But SQLite will only request a recursive mutex in
   18846 ** cases where it really needs one.  If a faster non-recursive mutex
   18847 ** implementation is available on the host platform, the mutex subsystem
   18848 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   18849 **
   18850 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   18851 ** a pointer to a static preexisting mutex.  Six static mutexes are
   18852 ** used by the current version of SQLite.  Future versions of SQLite
   18853 ** may add additional static mutexes.  Static mutexes are for internal
   18854 ** use by SQLite only.  Applications that use SQLite mutexes should
   18855 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   18856 ** SQLITE_MUTEX_RECURSIVE.
   18857 **
   18858 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   18859 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   18860 ** returns a different mutex on every call.  But for the static
   18861 ** mutex types, the same mutex is returned on every call that has
   18862 ** the same type number.
   18863 */
   18864 static sqlite3_mutex *pthreadMutexAlloc(int iType){
   18865   static sqlite3_mutex staticMutexes[] = {
   18866     SQLITE3_MUTEX_INITIALIZER,
   18867     SQLITE3_MUTEX_INITIALIZER,
   18868     SQLITE3_MUTEX_INITIALIZER,
   18869     SQLITE3_MUTEX_INITIALIZER,
   18870     SQLITE3_MUTEX_INITIALIZER,
   18871     SQLITE3_MUTEX_INITIALIZER,
   18872     SQLITE3_MUTEX_INITIALIZER,
   18873     SQLITE3_MUTEX_INITIALIZER,
   18874     SQLITE3_MUTEX_INITIALIZER
   18875   };
   18876   sqlite3_mutex *p;
   18877   switch( iType ){
   18878     case SQLITE_MUTEX_RECURSIVE: {
   18879       p = sqlite3MallocZero( sizeof(*p) );
   18880       if( p ){
   18881 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   18882         /* If recursive mutexes are not available, we will have to
   18883         ** build our own.  See below. */
   18884         pthread_mutex_init(&p->mutex, 0);
   18885 #else
   18886         /* Use a recursive mutex if it is available */
   18887         pthread_mutexattr_t recursiveAttr;
   18888         pthread_mutexattr_init(&recursiveAttr);
   18889         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
   18890         pthread_mutex_init(&p->mutex, &recursiveAttr);
   18891         pthread_mutexattr_destroy(&recursiveAttr);
   18892 #endif
   18893 #if SQLITE_MUTEX_NREF
   18894         p->id = iType;
   18895 #endif
   18896       }
   18897       break;
   18898     }
   18899     case SQLITE_MUTEX_FAST: {
   18900       p = sqlite3MallocZero( sizeof(*p) );
   18901       if( p ){
   18902 #if SQLITE_MUTEX_NREF
   18903         p->id = iType;
   18904 #endif
   18905         pthread_mutex_init(&p->mutex, 0);
   18906       }
   18907       break;
   18908     }
   18909     default: {
   18910       assert( iType-2 >= 0 );
   18911       assert( iType-2 < ArraySize(staticMutexes) );
   18912       p = &staticMutexes[iType-2];
   18913 #if SQLITE_MUTEX_NREF
   18914       p->id = iType;
   18915 #endif
   18916       break;
   18917     }
   18918   }
   18919   return p;
   18920 }
   18921 
   18922 
   18923 /*
   18924 ** This routine deallocates a previously
   18925 ** allocated mutex.  SQLite is careful to deallocate every
   18926 ** mutex that it allocates.
   18927 */
   18928 static void pthreadMutexFree(sqlite3_mutex *p){
   18929   assert( p->nRef==0 );
   18930   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   18931   pthread_mutex_destroy(&p->mutex);
   18932   sqlite3_free(p);
   18933 }
   18934 
   18935 /*
   18936 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   18937 ** to enter a mutex.  If another thread is already within the mutex,
   18938 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   18939 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   18940 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   18941 ** be entered multiple times by the same thread.  In such cases the,
   18942 ** mutex must be exited an equal number of times before another thread
   18943 ** can enter.  If the same thread tries to enter any other kind of mutex
   18944 ** more than once, the behavior is undefined.
   18945 */
   18946 static void pthreadMutexEnter(sqlite3_mutex *p){
   18947   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   18948 
   18949 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   18950   /* If recursive mutexes are not available, then we have to grow
   18951   ** our own.  This implementation assumes that pthread_equal()
   18952   ** is atomic - that it cannot be deceived into thinking self
   18953   ** and p->owner are equal if p->owner changes between two values
   18954   ** that are not equal to self while the comparison is taking place.
   18955   ** This implementation also assumes a coherent cache - that
   18956   ** separate processes cannot read different values from the same
   18957   ** address at the same time.  If either of these two conditions
   18958   ** are not met, then the mutexes will fail and problems will result.
   18959   */
   18960   {
   18961     pthread_t self = pthread_self();
   18962     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   18963       p->nRef++;
   18964     }else{
   18965       pthread_mutex_lock(&p->mutex);
   18966       assert( p->nRef==0 );
   18967       p->owner = self;
   18968       p->nRef = 1;
   18969     }
   18970   }
   18971 #else
   18972   /* Use the built-in recursive mutexes if they are available.
   18973   */
   18974   pthread_mutex_lock(&p->mutex);
   18975 #if SQLITE_MUTEX_NREF
   18976   assert( p->nRef>0 || p->owner==0 );
   18977   p->owner = pthread_self();
   18978   p->nRef++;
   18979 #endif
   18980 #endif
   18981 
   18982 #ifdef SQLITE_DEBUG
   18983   if( p->trace ){
   18984     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   18985   }
   18986 #endif
   18987 }
   18988 static int pthreadMutexTry(sqlite3_mutex *p){
   18989   int rc;
   18990   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   18991 
   18992 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   18993   /* If recursive mutexes are not available, then we have to grow
   18994   ** our own.  This implementation assumes that pthread_equal()
   18995   ** is atomic - that it cannot be deceived into thinking self
   18996   ** and p->owner are equal if p->owner changes between two values
   18997   ** that are not equal to self while the comparison is taking place.
   18998   ** This implementation also assumes a coherent cache - that
   18999   ** separate processes cannot read different values from the same
   19000   ** address at the same time.  If either of these two conditions
   19001   ** are not met, then the mutexes will fail and problems will result.
   19002   */
   19003   {
   19004     pthread_t self = pthread_self();
   19005     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   19006       p->nRef++;
   19007       rc = SQLITE_OK;
   19008     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
   19009       assert( p->nRef==0 );
   19010       p->owner = self;
   19011       p->nRef = 1;
   19012       rc = SQLITE_OK;
   19013     }else{
   19014       rc = SQLITE_BUSY;
   19015     }
   19016   }
   19017 #else
   19018   /* Use the built-in recursive mutexes if they are available.
   19019   */
   19020   if( pthread_mutex_trylock(&p->mutex)==0 ){
   19021 #if SQLITE_MUTEX_NREF
   19022     p->owner = pthread_self();
   19023     p->nRef++;
   19024 #endif
   19025     rc = SQLITE_OK;
   19026   }else{
   19027     rc = SQLITE_BUSY;
   19028   }
   19029 #endif
   19030 
   19031 #ifdef SQLITE_DEBUG
   19032   if( rc==SQLITE_OK && p->trace ){
   19033     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   19034   }
   19035 #endif
   19036   return rc;
   19037 }
   19038 
   19039 /*
   19040 ** The sqlite3_mutex_leave() routine exits a mutex that was
   19041 ** previously entered by the same thread.  The behavior
   19042 ** is undefined if the mutex is not currently entered or
   19043 ** is not currently allocated.  SQLite will never do either.
   19044 */
   19045 static void pthreadMutexLeave(sqlite3_mutex *p){
   19046   assert( pthreadMutexHeld(p) );
   19047 #if SQLITE_MUTEX_NREF
   19048   p->nRef--;
   19049   if( p->nRef==0 ) p->owner = 0;
   19050 #endif
   19051   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   19052 
   19053 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   19054   if( p->nRef==0 ){
   19055     pthread_mutex_unlock(&p->mutex);
   19056   }
   19057 #else
   19058   pthread_mutex_unlock(&p->mutex);
   19059 #endif
   19060 
   19061 #ifdef SQLITE_DEBUG
   19062   if( p->trace ){
   19063     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   19064   }
   19065 #endif
   19066 }
   19067 
   19068 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   19069   static const sqlite3_mutex_methods sMutex = {
   19070     pthreadMutexInit,
   19071     pthreadMutexEnd,
   19072     pthreadMutexAlloc,
   19073     pthreadMutexFree,
   19074     pthreadMutexEnter,
   19075     pthreadMutexTry,
   19076     pthreadMutexLeave,
   19077 #ifdef SQLITE_DEBUG
   19078     pthreadMutexHeld,
   19079     pthreadMutexNotheld
   19080 #else
   19081     0,
   19082     0
   19083 #endif
   19084   };
   19085 
   19086   return &sMutex;
   19087 }
   19088 
   19089 #endif /* SQLITE_MUTEX_PTHREADS */
   19090 
   19091 /************** End of mutex_unix.c ******************************************/
   19092 /************** Begin file mutex_w32.c ***************************************/
   19093 /*
   19094 ** 2007 August 14
   19095 **
   19096 ** The author disclaims copyright to this source code.  In place of
   19097 ** a legal notice, here is a blessing:
   19098 **
   19099 **    May you do good and not evil.
   19100 **    May you find forgiveness for yourself and forgive others.
   19101 **    May you share freely, never taking more than you give.
   19102 **
   19103 *************************************************************************
   19104 ** This file contains the C functions that implement mutexes for Win32.
   19105 */
   19106 
   19107 #if SQLITE_OS_WIN
   19108 /*
   19109 ** Include code that is common to all os_*.c files
   19110 */
   19111 /************** Include os_common.h in the middle of mutex_w32.c *************/
   19112 /************** Begin file os_common.h ***************************************/
   19113 /*
   19114 ** 2004 May 22
   19115 **
   19116 ** The author disclaims copyright to this source code.  In place of
   19117 ** a legal notice, here is a blessing:
   19118 **
   19119 **    May you do good and not evil.
   19120 **    May you find forgiveness for yourself and forgive others.
   19121 **    May you share freely, never taking more than you give.
   19122 **
   19123 ******************************************************************************
   19124 **
   19125 ** This file contains macros and a little bit of code that is common to
   19126 ** all of the platform-specific files (os_*.c) and is #included into those
   19127 ** files.
   19128 **
   19129 ** This file should be #included by the os_*.c files only.  It is not a
   19130 ** general purpose header file.
   19131 */
   19132 #ifndef _OS_COMMON_H_
   19133 #define _OS_COMMON_H_
   19134 
   19135 /*
   19136 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   19137 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   19138 ** switch.  The following code should catch this problem at compile-time.
   19139 */
   19140 #ifdef MEMORY_DEBUG
   19141 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   19142 #endif
   19143 
   19144 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   19145 # ifndef SQLITE_DEBUG_OS_TRACE
   19146 #   define SQLITE_DEBUG_OS_TRACE 0
   19147 # endif
   19148   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   19149 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   19150 #else
   19151 # define OSTRACE(X)
   19152 #endif
   19153 
   19154 /*
   19155 ** Macros for performance tracing.  Normally turned off.  Only works
   19156 ** on i486 hardware.
   19157 */
   19158 #ifdef SQLITE_PERFORMANCE_TRACE
   19159 
   19160 /*
   19161 ** hwtime.h contains inline assembler code for implementing
   19162 ** high-performance timing routines.
   19163 */
   19164 /************** Include hwtime.h in the middle of os_common.h ****************/
   19165 /************** Begin file hwtime.h ******************************************/
   19166 /*
   19167 ** 2008 May 27
   19168 **
   19169 ** The author disclaims copyright to this source code.  In place of
   19170 ** a legal notice, here is a blessing:
   19171 **
   19172 **    May you do good and not evil.
   19173 **    May you find forgiveness for yourself and forgive others.
   19174 **    May you share freely, never taking more than you give.
   19175 **
   19176 ******************************************************************************
   19177 **
   19178 ** This file contains inline asm code for retrieving "high-performance"
   19179 ** counters for x86 class CPUs.
   19180 */
   19181 #ifndef _HWTIME_H_
   19182 #define _HWTIME_H_
   19183 
   19184 /*
   19185 ** The following routine only works on pentium-class (or newer) processors.
   19186 ** It uses the RDTSC opcode to read the cycle count value out of the
   19187 ** processor and returns that value.  This can be used for high-res
   19188 ** profiling.
   19189 */
   19190 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   19191       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   19192 
   19193   #if defined(__GNUC__)
   19194 
   19195   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   19196      unsigned int lo, hi;
   19197      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   19198      return (sqlite_uint64)hi << 32 | lo;
   19199   }
   19200 
   19201   #elif defined(_MSC_VER)
   19202 
   19203   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   19204      __asm {
   19205         rdtsc
   19206         ret       ; return value at EDX:EAX
   19207      }
   19208   }
   19209 
   19210   #endif
   19211 
   19212 #elif (defined(__GNUC__) && defined(__x86_64__))
   19213 
   19214   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   19215       unsigned long val;
   19216       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   19217       return val;
   19218   }
   19219 
   19220 #elif (defined(__GNUC__) && defined(__ppc__))
   19221 
   19222   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   19223       unsigned long long retval;
   19224       unsigned long junk;
   19225       __asm__ __volatile__ ("\n\
   19226           1:      mftbu   %1\n\
   19227                   mftb    %L0\n\
   19228                   mftbu   %0\n\
   19229                   cmpw    %0,%1\n\
   19230                   bne     1b"
   19231                   : "=r" (retval), "=r" (junk));
   19232       return retval;
   19233   }
   19234 
   19235 #else
   19236 
   19237   #error Need implementation of sqlite3Hwtime() for your platform.
   19238 
   19239   /*
   19240   ** To compile without implementing sqlite3Hwtime() for your platform,
   19241   ** you can remove the above #error and use the following
   19242   ** stub function.  You will lose timing support for many
   19243   ** of the debugging and testing utilities, but it should at
   19244   ** least compile and run.
   19245   */
   19246 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   19247 
   19248 #endif
   19249 
   19250 #endif /* !defined(_HWTIME_H_) */
   19251 
   19252 /************** End of hwtime.h **********************************************/
   19253 /************** Continuing where we left off in os_common.h ******************/
   19254 
   19255 static sqlite_uint64 g_start;
   19256 static sqlite_uint64 g_elapsed;
   19257 #define TIMER_START       g_start=sqlite3Hwtime()
   19258 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   19259 #define TIMER_ELAPSED     g_elapsed
   19260 #else
   19261 #define TIMER_START
   19262 #define TIMER_END
   19263 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   19264 #endif
   19265 
   19266 /*
   19267 ** If we compile with the SQLITE_TEST macro set, then the following block
   19268 ** of code will give us the ability to simulate a disk I/O error.  This
   19269 ** is used for testing the I/O recovery logic.
   19270 */
   19271 #ifdef SQLITE_TEST
   19272 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   19273 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   19274 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   19275 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   19276 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   19277 SQLITE_API int sqlite3_diskfull_pending = 0;
   19278 SQLITE_API int sqlite3_diskfull = 0;
   19279 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   19280 #define SimulateIOError(CODE)  \
   19281   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   19282        || sqlite3_io_error_pending-- == 1 )  \
   19283               { local_ioerr(); CODE; }
   19284 static void local_ioerr(){
   19285   IOTRACE(("IOERR\n"));
   19286   sqlite3_io_error_hit++;
   19287   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   19288 }
   19289 #define SimulateDiskfullError(CODE) \
   19290    if( sqlite3_diskfull_pending ){ \
   19291      if( sqlite3_diskfull_pending == 1 ){ \
   19292        local_ioerr(); \
   19293        sqlite3_diskfull = 1; \
   19294        sqlite3_io_error_hit = 1; \
   19295        CODE; \
   19296      }else{ \
   19297        sqlite3_diskfull_pending--; \
   19298      } \
   19299    }
   19300 #else
   19301 #define SimulateIOErrorBenign(X)
   19302 #define SimulateIOError(A)
   19303 #define SimulateDiskfullError(A)
   19304 #endif
   19305 
   19306 /*
   19307 ** When testing, keep a count of the number of open files.
   19308 */
   19309 #ifdef SQLITE_TEST
   19310 SQLITE_API int sqlite3_open_file_count = 0;
   19311 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   19312 #else
   19313 #define OpenCounter(X)
   19314 #endif
   19315 
   19316 #endif /* !defined(_OS_COMMON_H_) */
   19317 
   19318 /************** End of os_common.h *******************************************/
   19319 /************** Continuing where we left off in mutex_w32.c ******************/
   19320 
   19321 /*
   19322 ** Include the header file for the Windows VFS.
   19323 */
   19324 /************** Include os_win.h in the middle of mutex_w32.c ****************/
   19325 /************** Begin file os_win.h ******************************************/
   19326 /*
   19327 ** 2013 November 25
   19328 **
   19329 ** The author disclaims copyright to this source code.  In place of
   19330 ** a legal notice, here is a blessing:
   19331 **
   19332 **    May you do good and not evil.
   19333 **    May you find forgiveness for yourself and forgive others.
   19334 **    May you share freely, never taking more than you give.
   19335 **
   19336 ******************************************************************************
   19337 **
   19338 ** This file contains code that is specific to Windows.
   19339 */
   19340 #ifndef _OS_WIN_H_
   19341 #define _OS_WIN_H_
   19342 
   19343 /*
   19344 ** Include the primary Windows SDK header file.
   19345 */
   19346 #include "windows.h"
   19347 
   19348 #ifdef __CYGWIN__
   19349 # include <sys/cygwin.h>
   19350 # include <errno.h> /* amalgamator: dontcache */
   19351 #endif
   19352 
   19353 /*
   19354 ** Determine if we are dealing with Windows NT.
   19355 **
   19356 ** We ought to be able to determine if we are compiling for Windows 9x or
   19357 ** Windows NT using the _WIN32_WINNT macro as follows:
   19358 **
   19359 ** #if defined(_WIN32_WINNT)
   19360 ** # define SQLITE_OS_WINNT 1
   19361 ** #else
   19362 ** # define SQLITE_OS_WINNT 0
   19363 ** #endif
   19364 **
   19365 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
   19366 ** it ought to, so the above test does not work.  We'll just assume that
   19367 ** everything is Windows NT unless the programmer explicitly says otherwise
   19368 ** by setting SQLITE_OS_WINNT to 0.
   19369 */
   19370 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
   19371 # define SQLITE_OS_WINNT 1
   19372 #endif
   19373 
   19374 /*
   19375 ** Determine if we are dealing with Windows CE - which has a much reduced
   19376 ** API.
   19377 */
   19378 #if defined(_WIN32_WCE)
   19379 # define SQLITE_OS_WINCE 1
   19380 #else
   19381 # define SQLITE_OS_WINCE 0
   19382 #endif
   19383 
   19384 /*
   19385 ** Determine if we are dealing with WinRT, which provides only a subset of
   19386 ** the full Win32 API.
   19387 */
   19388 #if !defined(SQLITE_OS_WINRT)
   19389 # define SQLITE_OS_WINRT 0
   19390 #endif
   19391 
   19392 #endif /* _OS_WIN_H_ */
   19393 
   19394 /************** End of os_win.h **********************************************/
   19395 /************** Continuing where we left off in mutex_w32.c ******************/
   19396 #endif
   19397 
   19398 /*
   19399 ** The code in this file is only used if we are compiling multithreaded
   19400 ** on a Win32 system.
   19401 */
   19402 #ifdef SQLITE_MUTEX_W32
   19403 
   19404 /*
   19405 ** Each recursive mutex is an instance of the following structure.
   19406 */
   19407 struct sqlite3_mutex {
   19408   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
   19409   int id;                    /* Mutex type */
   19410 #ifdef SQLITE_DEBUG
   19411   volatile int nRef;         /* Number of enterances */
   19412   volatile DWORD owner;      /* Thread holding this mutex */
   19413   volatile int trace;        /* True to trace changes */
   19414 #endif
   19415 };
   19416 
   19417 /*
   19418 ** These are the initializer values used when declaring a "static" mutex
   19419 ** on Win32.  It should be noted that all mutexes require initialization
   19420 ** on the Win32 platform.
   19421 */
   19422 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
   19423 
   19424 #ifdef SQLITE_DEBUG
   19425 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
   19426                                     0L, (DWORD)0, 0 }
   19427 #else
   19428 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
   19429 #endif
   19430 
   19431 #ifdef SQLITE_DEBUG
   19432 /*
   19433 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   19434 ** intended for use only inside assert() statements.
   19435 */
   19436 static int winMutexHeld(sqlite3_mutex *p){
   19437   return p->nRef!=0 && p->owner==GetCurrentThreadId();
   19438 }
   19439 
   19440 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
   19441   return p->nRef==0 || p->owner!=tid;
   19442 }
   19443 
   19444 static int winMutexNotheld(sqlite3_mutex *p){
   19445   DWORD tid = GetCurrentThreadId();
   19446   return winMutexNotheld2(p, tid);
   19447 }
   19448 #endif
   19449 
   19450 /*
   19451 ** Initialize and deinitialize the mutex subsystem.
   19452 */
   19453 static sqlite3_mutex winMutex_staticMutexes[] = {
   19454   SQLITE3_MUTEX_INITIALIZER,
   19455   SQLITE3_MUTEX_INITIALIZER,
   19456   SQLITE3_MUTEX_INITIALIZER,
   19457   SQLITE3_MUTEX_INITIALIZER,
   19458   SQLITE3_MUTEX_INITIALIZER,
   19459   SQLITE3_MUTEX_INITIALIZER,
   19460   SQLITE3_MUTEX_INITIALIZER,
   19461   SQLITE3_MUTEX_INITIALIZER,
   19462   SQLITE3_MUTEX_INITIALIZER
   19463 };
   19464 
   19465 static int winMutex_isInit = 0;
   19466 static int winMutex_isNt = -1; /* <0 means "need to query" */
   19467 
   19468 /* As the winMutexInit() and winMutexEnd() functions are called as part
   19469 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
   19470 ** "interlocked" magic used here is probably not strictly necessary.
   19471 */
   19472 static LONG volatile winMutex_lock = 0;
   19473 
   19474 SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
   19475 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
   19476 
   19477 static int winMutexInit(void){
   19478   /* The first to increment to 1 does actual initialization */
   19479   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
   19480     int i;
   19481     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   19482 #if SQLITE_OS_WINRT
   19483       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
   19484 #else
   19485       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
   19486 #endif
   19487     }
   19488     winMutex_isInit = 1;
   19489   }else{
   19490     /* Another thread is (in the process of) initializing the static
   19491     ** mutexes */
   19492     while( !winMutex_isInit ){
   19493       sqlite3_win32_sleep(1);
   19494     }
   19495   }
   19496   return SQLITE_OK;
   19497 }
   19498 
   19499 static int winMutexEnd(void){
   19500   /* The first to decrement to 0 does actual shutdown
   19501   ** (which should be the last to shutdown.) */
   19502   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
   19503     if( winMutex_isInit==1 ){
   19504       int i;
   19505       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   19506         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
   19507       }
   19508       winMutex_isInit = 0;
   19509     }
   19510   }
   19511   return SQLITE_OK;
   19512 }
   19513 
   19514 /*
   19515 ** The sqlite3_mutex_alloc() routine allocates a new
   19516 ** mutex and returns a pointer to it.  If it returns NULL
   19517 ** that means that a mutex could not be allocated.  SQLite
   19518 ** will unwind its stack and return an error.  The argument
   19519 ** to sqlite3_mutex_alloc() is one of these integer constants:
   19520 **
   19521 ** <ul>
   19522 ** <li>  SQLITE_MUTEX_FAST
   19523 ** <li>  SQLITE_MUTEX_RECURSIVE
   19524 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   19525 ** <li>  SQLITE_MUTEX_STATIC_MEM
   19526 ** <li>  SQLITE_MUTEX_STATIC_OPEN
   19527 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   19528 ** <li>  SQLITE_MUTEX_STATIC_LRU
   19529 ** <li>  SQLITE_MUTEX_STATIC_PMEM
   19530 ** <li>  SQLITE_MUTEX_STATIC_APP1
   19531 ** <li>  SQLITE_MUTEX_STATIC_APP2
   19532 ** <li>  SQLITE_MUTEX_STATIC_APP3
   19533 ** </ul>
   19534 **
   19535 ** The first two constants cause sqlite3_mutex_alloc() to create
   19536 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   19537 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   19538 ** The mutex implementation does not need to make a distinction
   19539 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   19540 ** not want to.  But SQLite will only request a recursive mutex in
   19541 ** cases where it really needs one.  If a faster non-recursive mutex
   19542 ** implementation is available on the host platform, the mutex subsystem
   19543 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   19544 **
   19545 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   19546 ** a pointer to a static preexisting mutex.  Six static mutexes are
   19547 ** used by the current version of SQLite.  Future versions of SQLite
   19548 ** may add additional static mutexes.  Static mutexes are for internal
   19549 ** use by SQLite only.  Applications that use SQLite mutexes should
   19550 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   19551 ** SQLITE_MUTEX_RECURSIVE.
   19552 **
   19553 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   19554 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   19555 ** returns a different mutex on every call.  But for the static
   19556 ** mutex types, the same mutex is returned on every call that has
   19557 ** the same type number.
   19558 */
   19559 static sqlite3_mutex *winMutexAlloc(int iType){
   19560   sqlite3_mutex *p;
   19561 
   19562   switch( iType ){
   19563     case SQLITE_MUTEX_FAST:
   19564     case SQLITE_MUTEX_RECURSIVE: {
   19565       p = sqlite3MallocZero( sizeof(*p) );
   19566       if( p ){
   19567 #ifdef SQLITE_DEBUG
   19568         p->id = iType;
   19569 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
   19570         p->trace = 1;
   19571 #endif
   19572 #endif
   19573 #if SQLITE_OS_WINRT
   19574         InitializeCriticalSectionEx(&p->mutex, 0, 0);
   19575 #else
   19576         InitializeCriticalSection(&p->mutex);
   19577 #endif
   19578       }
   19579       break;
   19580     }
   19581     default: {
   19582       assert( iType-2 >= 0 );
   19583       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
   19584       assert( winMutex_isInit==1 );
   19585       p = &winMutex_staticMutexes[iType-2];
   19586 #ifdef SQLITE_DEBUG
   19587       p->id = iType;
   19588 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
   19589       p->trace = 1;
   19590 #endif
   19591 #endif
   19592       break;
   19593     }
   19594   }
   19595   return p;
   19596 }
   19597 
   19598 
   19599 /*
   19600 ** This routine deallocates a previously
   19601 ** allocated mutex.  SQLite is careful to deallocate every
   19602 ** mutex that it allocates.
   19603 */
   19604 static void winMutexFree(sqlite3_mutex *p){
   19605   assert( p );
   19606 #ifdef SQLITE_DEBUG
   19607   assert( p->nRef==0 && p->owner==0 );
   19608   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   19609 #endif
   19610   assert( winMutex_isInit==1 );
   19611   DeleteCriticalSection(&p->mutex);
   19612   sqlite3_free(p);
   19613 }
   19614 
   19615 /*
   19616 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   19617 ** to enter a mutex.  If another thread is already within the mutex,
   19618 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   19619 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   19620 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   19621 ** be entered multiple times by the same thread.  In such cases the,
   19622 ** mutex must be exited an equal number of times before another thread
   19623 ** can enter.  If the same thread tries to enter any other kind of mutex
   19624 ** more than once, the behavior is undefined.
   19625 */
   19626 static void winMutexEnter(sqlite3_mutex *p){
   19627 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   19628   DWORD tid = GetCurrentThreadId();
   19629 #endif
   19630 #ifdef SQLITE_DEBUG
   19631   assert( p );
   19632   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
   19633 #else
   19634   assert( p );
   19635 #endif
   19636   assert( winMutex_isInit==1 );
   19637   EnterCriticalSection(&p->mutex);
   19638 #ifdef SQLITE_DEBUG
   19639   assert( p->nRef>0 || p->owner==0 );
   19640   p->owner = tid;
   19641   p->nRef++;
   19642   if( p->trace ){
   19643     OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
   19644              tid, p, p->trace, p->nRef));
   19645   }
   19646 #endif
   19647 }
   19648 
   19649 static int winMutexTry(sqlite3_mutex *p){
   19650 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   19651   DWORD tid = GetCurrentThreadId();
   19652 #endif
   19653   int rc = SQLITE_BUSY;
   19654   assert( p );
   19655   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
   19656   /*
   19657   ** The sqlite3_mutex_try() routine is very rarely used, and when it
   19658   ** is used it is merely an optimization.  So it is OK for it to always
   19659   ** fail.
   19660   **
   19661   ** The TryEnterCriticalSection() interface is only available on WinNT.
   19662   ** And some windows compilers complain if you try to use it without
   19663   ** first doing some #defines that prevent SQLite from building on Win98.
   19664   ** For that reason, we will omit this optimization for now.  See
   19665   ** ticket #2685.
   19666   */
   19667 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
   19668   assert( winMutex_isInit==1 );
   19669   assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
   19670   if( winMutex_isNt<0 ){
   19671     winMutex_isNt = sqlite3_win32_is_nt();
   19672   }
   19673   assert( winMutex_isNt==0 || winMutex_isNt==1 );
   19674   if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
   19675 #ifdef SQLITE_DEBUG
   19676     p->owner = tid;
   19677     p->nRef++;
   19678 #endif
   19679     rc = SQLITE_OK;
   19680   }
   19681 #else
   19682   UNUSED_PARAMETER(p);
   19683 #endif
   19684 #ifdef SQLITE_DEBUG
   19685   if( p->trace ){
   19686     OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
   19687              tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
   19688   }
   19689 #endif
   19690   return rc;
   19691 }
   19692 
   19693 /*
   19694 ** The sqlite3_mutex_leave() routine exits a mutex that was
   19695 ** previously entered by the same thread.  The behavior
   19696 ** is undefined if the mutex is not currently entered or
   19697 ** is not currently allocated.  SQLite will never do either.
   19698 */
   19699 static void winMutexLeave(sqlite3_mutex *p){
   19700 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   19701   DWORD tid = GetCurrentThreadId();
   19702 #endif
   19703   assert( p );
   19704 #ifdef SQLITE_DEBUG
   19705   assert( p->nRef>0 );
   19706   assert( p->owner==tid );
   19707   p->nRef--;
   19708   if( p->nRef==0 ) p->owner = 0;
   19709   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   19710 #endif
   19711   assert( winMutex_isInit==1 );
   19712   LeaveCriticalSection(&p->mutex);
   19713 #ifdef SQLITE_DEBUG
   19714   if( p->trace ){
   19715     OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
   19716              tid, p, p->trace, p->nRef));
   19717   }
   19718 #endif
   19719 }
   19720 
   19721 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   19722   static const sqlite3_mutex_methods sMutex = {
   19723     winMutexInit,
   19724     winMutexEnd,
   19725     winMutexAlloc,
   19726     winMutexFree,
   19727     winMutexEnter,
   19728     winMutexTry,
   19729     winMutexLeave,
   19730 #ifdef SQLITE_DEBUG
   19731     winMutexHeld,
   19732     winMutexNotheld
   19733 #else
   19734     0,
   19735     0
   19736 #endif
   19737   };
   19738   return &sMutex;
   19739 }
   19740 
   19741 #endif /* SQLITE_MUTEX_W32 */
   19742 
   19743 /************** End of mutex_w32.c *******************************************/
   19744 /************** Begin file malloc.c ******************************************/
   19745 /*
   19746 ** 2001 September 15
   19747 **
   19748 ** The author disclaims copyright to this source code.  In place of
   19749 ** a legal notice, here is a blessing:
   19750 **
   19751 **    May you do good and not evil.
   19752 **    May you find forgiveness for yourself and forgive others.
   19753 **    May you share freely, never taking more than you give.
   19754 **
   19755 *************************************************************************
   19756 **
   19757 ** Memory allocation functions used throughout sqlite.
   19758 */
   19759 /* #include <stdarg.h> */
   19760 
   19761 /*
   19762 ** Attempt to release up to n bytes of non-essential memory currently
   19763 ** held by SQLite. An example of non-essential memory is memory used to
   19764 ** cache database pages that are not currently in use.
   19765 */
   19766 SQLITE_API int sqlite3_release_memory(int n){
   19767 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   19768   return sqlite3PcacheReleaseMemory(n);
   19769 #else
   19770   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
   19771   ** is a no-op returning zero if SQLite is not compiled with
   19772   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
   19773   UNUSED_PARAMETER(n);
   19774   return 0;
   19775 #endif
   19776 }
   19777 
   19778 /*
   19779 ** An instance of the following object records the location of
   19780 ** each unused scratch buffer.
   19781 */
   19782 typedef struct ScratchFreeslot {
   19783   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
   19784 } ScratchFreeslot;
   19785 
   19786 /*
   19787 ** State information local to the memory allocation subsystem.
   19788 */
   19789 static SQLITE_WSD struct Mem0Global {
   19790   sqlite3_mutex *mutex;         /* Mutex to serialize access */
   19791 
   19792   /*
   19793   ** The alarm callback and its arguments.  The mem0.mutex lock will
   19794   ** be held while the callback is running.  Recursive calls into
   19795   ** the memory subsystem are allowed, but no new callbacks will be
   19796   ** issued.
   19797   */
   19798   sqlite3_int64 alarmThreshold;
   19799   void (*alarmCallback)(void*, sqlite3_int64,int);
   19800   void *alarmArg;
   19801 
   19802   /*
   19803   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
   19804   ** (so that a range test can be used to determine if an allocation
   19805   ** being freed came from pScratch) and a pointer to the list of
   19806   ** unused scratch allocations.
   19807   */
   19808   void *pScratchEnd;
   19809   ScratchFreeslot *pScratchFree;
   19810   u32 nScratchFree;
   19811 
   19812   /*
   19813   ** True if heap is nearly "full" where "full" is defined by the
   19814   ** sqlite3_soft_heap_limit() setting.
   19815   */
   19816   int nearlyFull;
   19817 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
   19818 
   19819 #define mem0 GLOBAL(struct Mem0Global, mem0)
   19820 
   19821 /*
   19822 ** This routine runs when the memory allocator sees that the
   19823 ** total memory allocation is about to exceed the soft heap
   19824 ** limit.
   19825 */
   19826 static void softHeapLimitEnforcer(
   19827   void *NotUsed,
   19828   sqlite3_int64 NotUsed2,
   19829   int allocSize
   19830 ){
   19831   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   19832   sqlite3_release_memory(allocSize);
   19833 }
   19834 
   19835 /*
   19836 ** Change the alarm callback
   19837 */
   19838 static int sqlite3MemoryAlarm(
   19839   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   19840   void *pArg,
   19841   sqlite3_int64 iThreshold
   19842 ){
   19843   int nUsed;
   19844   sqlite3_mutex_enter(mem0.mutex);
   19845   mem0.alarmCallback = xCallback;
   19846   mem0.alarmArg = pArg;
   19847   mem0.alarmThreshold = iThreshold;
   19848   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   19849   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
   19850   sqlite3_mutex_leave(mem0.mutex);
   19851   return SQLITE_OK;
   19852 }
   19853 
   19854 #ifndef SQLITE_OMIT_DEPRECATED
   19855 /*
   19856 ** Deprecated external interface.  Internal/core SQLite code
   19857 ** should call sqlite3MemoryAlarm.
   19858 */
   19859 SQLITE_API int sqlite3_memory_alarm(
   19860   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   19861   void *pArg,
   19862   sqlite3_int64 iThreshold
   19863 ){
   19864   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
   19865 }
   19866 #endif
   19867 
   19868 /*
   19869 ** Set the soft heap-size limit for the library. Passing a zero or
   19870 ** negative value indicates no limit.
   19871 */
   19872 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
   19873   sqlite3_int64 priorLimit;
   19874   sqlite3_int64 excess;
   19875 #ifndef SQLITE_OMIT_AUTOINIT
   19876   int rc = sqlite3_initialize();
   19877   if( rc ) return -1;
   19878 #endif
   19879   sqlite3_mutex_enter(mem0.mutex);
   19880   priorLimit = mem0.alarmThreshold;
   19881   sqlite3_mutex_leave(mem0.mutex);
   19882   if( n<0 ) return priorLimit;
   19883   if( n>0 ){
   19884     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
   19885   }else{
   19886     sqlite3MemoryAlarm(0, 0, 0);
   19887   }
   19888   excess = sqlite3_memory_used() - n;
   19889   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
   19890   return priorLimit;
   19891 }
   19892 SQLITE_API void sqlite3_soft_heap_limit(int n){
   19893   if( n<0 ) n = 0;
   19894   sqlite3_soft_heap_limit64(n);
   19895 }
   19896 
   19897 /*
   19898 ** Initialize the memory allocation subsystem.
   19899 */
   19900 SQLITE_PRIVATE int sqlite3MallocInit(void){
   19901   if( sqlite3GlobalConfig.m.xMalloc==0 ){
   19902     sqlite3MemSetDefault();
   19903   }
   19904   memset(&mem0, 0, sizeof(mem0));
   19905   if( sqlite3GlobalConfig.bCoreMutex ){
   19906     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   19907   }
   19908   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
   19909       && sqlite3GlobalConfig.nScratch>0 ){
   19910     int i, n, sz;
   19911     ScratchFreeslot *pSlot;
   19912     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
   19913     sqlite3GlobalConfig.szScratch = sz;
   19914     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
   19915     n = sqlite3GlobalConfig.nScratch;
   19916     mem0.pScratchFree = pSlot;
   19917     mem0.nScratchFree = n;
   19918     for(i=0; i<n-1; i++){
   19919       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
   19920       pSlot = pSlot->pNext;
   19921     }
   19922     pSlot->pNext = 0;
   19923     mem0.pScratchEnd = (void*)&pSlot[1];
   19924   }else{
   19925     mem0.pScratchEnd = 0;
   19926     sqlite3GlobalConfig.pScratch = 0;
   19927     sqlite3GlobalConfig.szScratch = 0;
   19928     sqlite3GlobalConfig.nScratch = 0;
   19929   }
   19930   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
   19931       || sqlite3GlobalConfig.nPage<1 ){
   19932     sqlite3GlobalConfig.pPage = 0;
   19933     sqlite3GlobalConfig.szPage = 0;
   19934     sqlite3GlobalConfig.nPage = 0;
   19935   }
   19936   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
   19937 }
   19938 
   19939 /*
   19940 ** Return true if the heap is currently under memory pressure - in other
   19941 ** words if the amount of heap used is close to the limit set by
   19942 ** sqlite3_soft_heap_limit().
   19943 */
   19944 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
   19945   return mem0.nearlyFull;
   19946 }
   19947 
   19948 /*
   19949 ** Deinitialize the memory allocation subsystem.
   19950 */
   19951 SQLITE_PRIVATE void sqlite3MallocEnd(void){
   19952   if( sqlite3GlobalConfig.m.xShutdown ){
   19953     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
   19954   }
   19955   memset(&mem0, 0, sizeof(mem0));
   19956 }
   19957 
   19958 /*
   19959 ** Return the amount of memory currently checked out.
   19960 */
   19961 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
   19962   int n, mx;
   19963   sqlite3_int64 res;
   19964   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
   19965   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
   19966   return res;
   19967 }
   19968 
   19969 /*
   19970 ** Return the maximum amount of memory that has ever been
   19971 ** checked out since either the beginning of this process
   19972 ** or since the most recent reset.
   19973 */
   19974 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
   19975   int n, mx;
   19976   sqlite3_int64 res;
   19977   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
   19978   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
   19979   return res;
   19980 }
   19981 
   19982 /*
   19983 ** Trigger the alarm
   19984 */
   19985 static void sqlite3MallocAlarm(int nByte){
   19986   void (*xCallback)(void*,sqlite3_int64,int);
   19987   sqlite3_int64 nowUsed;
   19988   void *pArg;
   19989   if( mem0.alarmCallback==0 ) return;
   19990   xCallback = mem0.alarmCallback;
   19991   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   19992   pArg = mem0.alarmArg;
   19993   mem0.alarmCallback = 0;
   19994   sqlite3_mutex_leave(mem0.mutex);
   19995   xCallback(pArg, nowUsed, nByte);
   19996   sqlite3_mutex_enter(mem0.mutex);
   19997   mem0.alarmCallback = xCallback;
   19998   mem0.alarmArg = pArg;
   19999 }
   20000 
   20001 /*
   20002 ** Do a memory allocation with statistics and alarms.  Assume the
   20003 ** lock is already held.
   20004 */
   20005 static int mallocWithAlarm(int n, void **pp){
   20006   int nFull;
   20007   void *p;
   20008   assert( sqlite3_mutex_held(mem0.mutex) );
   20009   nFull = sqlite3GlobalConfig.m.xRoundup(n);
   20010   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
   20011   if( mem0.alarmCallback!=0 ){
   20012     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   20013     if( nUsed >= mem0.alarmThreshold - nFull ){
   20014       mem0.nearlyFull = 1;
   20015       sqlite3MallocAlarm(nFull);
   20016     }else{
   20017       mem0.nearlyFull = 0;
   20018     }
   20019   }
   20020   p = sqlite3GlobalConfig.m.xMalloc(nFull);
   20021 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   20022   if( p==0 && mem0.alarmCallback ){
   20023     sqlite3MallocAlarm(nFull);
   20024     p = sqlite3GlobalConfig.m.xMalloc(nFull);
   20025   }
   20026 #endif
   20027   if( p ){
   20028     nFull = sqlite3MallocSize(p);
   20029     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
   20030     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
   20031   }
   20032   *pp = p;
   20033   return nFull;
   20034 }
   20035 
   20036 /*
   20037 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
   20038 ** assumes the memory subsystem has already been initialized.
   20039 */
   20040 SQLITE_PRIVATE void *sqlite3Malloc(int n){
   20041   void *p;
   20042   if( n<=0               /* IMP: R-65312-04917 */
   20043    || n>=0x7fffff00
   20044   ){
   20045     /* A memory allocation of a number of bytes which is near the maximum
   20046     ** signed integer value might cause an integer overflow inside of the
   20047     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
   20048     ** 255 bytes of overhead.  SQLite itself will never use anything near
   20049     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
   20050     p = 0;
   20051   }else if( sqlite3GlobalConfig.bMemstat ){
   20052     sqlite3_mutex_enter(mem0.mutex);
   20053     mallocWithAlarm(n, &p);
   20054     sqlite3_mutex_leave(mem0.mutex);
   20055   }else{
   20056     p = sqlite3GlobalConfig.m.xMalloc(n);
   20057   }
   20058   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
   20059   return p;
   20060 }
   20061 
   20062 /*
   20063 ** This version of the memory allocation is for use by the application.
   20064 ** First make sure the memory subsystem is initialized, then do the
   20065 ** allocation.
   20066 */
   20067 SQLITE_API void *sqlite3_malloc(int n){
   20068 #ifndef SQLITE_OMIT_AUTOINIT
   20069   if( sqlite3_initialize() ) return 0;
   20070 #endif
   20071   return sqlite3Malloc(n);
   20072 }
   20073 
   20074 /*
   20075 ** Each thread may only have a single outstanding allocation from
   20076 ** xScratchMalloc().  We verify this constraint in the single-threaded
   20077 ** case by setting scratchAllocOut to 1 when an allocation
   20078 ** is outstanding clearing it when the allocation is freed.
   20079 */
   20080 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   20081 static int scratchAllocOut = 0;
   20082 #endif
   20083 
   20084 
   20085 /*
   20086 ** Allocate memory that is to be used and released right away.
   20087 ** This routine is similar to alloca() in that it is not intended
   20088 ** for situations where the memory might be held long-term.  This
   20089 ** routine is intended to get memory to old large transient data
   20090 ** structures that would not normally fit on the stack of an
   20091 ** embedded processor.
   20092 */
   20093 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
   20094   void *p;
   20095   assert( n>0 );
   20096 
   20097   sqlite3_mutex_enter(mem0.mutex);
   20098   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
   20099     p = mem0.pScratchFree;
   20100     mem0.pScratchFree = mem0.pScratchFree->pNext;
   20101     mem0.nScratchFree--;
   20102     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
   20103     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
   20104     sqlite3_mutex_leave(mem0.mutex);
   20105   }else{
   20106     if( sqlite3GlobalConfig.bMemstat ){
   20107       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
   20108       n = mallocWithAlarm(n, &p);
   20109       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
   20110       sqlite3_mutex_leave(mem0.mutex);
   20111     }else{
   20112       sqlite3_mutex_leave(mem0.mutex);
   20113       p = sqlite3GlobalConfig.m.xMalloc(n);
   20114     }
   20115     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
   20116   }
   20117   assert( sqlite3_mutex_notheld(mem0.mutex) );
   20118 
   20119 
   20120 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   20121   /* Verify that no more than two scratch allocations per thread
   20122   ** are outstanding at one time.  (This is only checked in the
   20123   ** single-threaded case since checking in the multi-threaded case
   20124   ** would be much more complicated.) */
   20125   assert( scratchAllocOut<=1 );
   20126   if( p ) scratchAllocOut++;
   20127 #endif
   20128 
   20129   return p;
   20130 }
   20131 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
   20132   if( p ){
   20133 
   20134 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   20135     /* Verify that no more than two scratch allocation per thread
   20136     ** is outstanding at one time.  (This is only checked in the
   20137     ** single-threaded case since checking in the multi-threaded case
   20138     ** would be much more complicated.) */
   20139     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
   20140     scratchAllocOut--;
   20141 #endif
   20142 
   20143     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
   20144       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
   20145       ScratchFreeslot *pSlot;
   20146       pSlot = (ScratchFreeslot*)p;
   20147       sqlite3_mutex_enter(mem0.mutex);
   20148       pSlot->pNext = mem0.pScratchFree;
   20149       mem0.pScratchFree = pSlot;
   20150       mem0.nScratchFree++;
   20151       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
   20152       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
   20153       sqlite3_mutex_leave(mem0.mutex);
   20154     }else{
   20155       /* Release memory back to the heap */
   20156       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
   20157       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
   20158       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   20159       if( sqlite3GlobalConfig.bMemstat ){
   20160         int iSize = sqlite3MallocSize(p);
   20161         sqlite3_mutex_enter(mem0.mutex);
   20162         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
   20163         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
   20164         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
   20165         sqlite3GlobalConfig.m.xFree(p);
   20166         sqlite3_mutex_leave(mem0.mutex);
   20167       }else{
   20168         sqlite3GlobalConfig.m.xFree(p);
   20169       }
   20170     }
   20171   }
   20172 }
   20173 
   20174 /*
   20175 ** TRUE if p is a lookaside memory allocation from db
   20176 */
   20177 #ifndef SQLITE_OMIT_LOOKASIDE
   20178 static int isLookaside(sqlite3 *db, void *p){
   20179   return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
   20180 }
   20181 #else
   20182 #define isLookaside(A,B) 0
   20183 #endif
   20184 
   20185 /*
   20186 ** Return the size of a memory allocation previously obtained from
   20187 ** sqlite3Malloc() or sqlite3_malloc().
   20188 */
   20189 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
   20190   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   20191   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   20192   return sqlite3GlobalConfig.m.xSize(p);
   20193 }
   20194 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
   20195   assert( db!=0 );
   20196   assert( sqlite3_mutex_held(db->mutex) );
   20197   if( isLookaside(db, p) ){
   20198     return db->lookaside.sz;
   20199   }else{
   20200     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   20201     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   20202     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
   20203     return sqlite3GlobalConfig.m.xSize(p);
   20204   }
   20205 }
   20206 
   20207 /*
   20208 ** Free memory previously obtained from sqlite3Malloc().
   20209 */
   20210 SQLITE_API void sqlite3_free(void *p){
   20211   if( p==0 ) return;  /* IMP: R-49053-54554 */
   20212   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   20213   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   20214   if( sqlite3GlobalConfig.bMemstat ){
   20215     sqlite3_mutex_enter(mem0.mutex);
   20216     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
   20217     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
   20218     sqlite3GlobalConfig.m.xFree(p);
   20219     sqlite3_mutex_leave(mem0.mutex);
   20220   }else{
   20221     sqlite3GlobalConfig.m.xFree(p);
   20222   }
   20223 }
   20224 
   20225 /*
   20226 ** Free memory that might be associated with a particular database
   20227 ** connection.
   20228 */
   20229 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
   20230   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   20231   if( p==0 ) return;
   20232   if( db ){
   20233     if( db->pnBytesFreed ){
   20234       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
   20235       return;
   20236     }
   20237     if( isLookaside(db, p) ){
   20238       LookasideSlot *pBuf = (LookasideSlot*)p;
   20239 #if SQLITE_DEBUG
   20240       /* Trash all content in the buffer being freed */
   20241       memset(p, 0xaa, db->lookaside.sz);
   20242 #endif
   20243       pBuf->pNext = db->lookaside.pFree;
   20244       db->lookaside.pFree = pBuf;
   20245       db->lookaside.nOut--;
   20246       return;
   20247     }
   20248   }
   20249   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   20250   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   20251   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
   20252   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   20253   sqlite3_free(p);
   20254 }
   20255 
   20256 /*
   20257 ** Change the size of an existing memory allocation
   20258 */
   20259 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
   20260   int nOld, nNew, nDiff;
   20261   void *pNew;
   20262   if( pOld==0 ){
   20263     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
   20264   }
   20265   if( nBytes<=0 ){
   20266     sqlite3_free(pOld); /* IMP: R-31593-10574 */
   20267     return 0;
   20268   }
   20269   if( nBytes>=0x7fffff00 ){
   20270     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
   20271     return 0;
   20272   }
   20273   nOld = sqlite3MallocSize(pOld);
   20274   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
   20275   ** argument to xRealloc is always a value returned by a prior call to
   20276   ** xRoundup. */
   20277   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
   20278   if( nOld==nNew ){
   20279     pNew = pOld;
   20280   }else if( sqlite3GlobalConfig.bMemstat ){
   20281     sqlite3_mutex_enter(mem0.mutex);
   20282     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
   20283     nDiff = nNew - nOld;
   20284     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
   20285           mem0.alarmThreshold-nDiff ){
   20286       sqlite3MallocAlarm(nDiff);
   20287     }
   20288     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
   20289     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
   20290     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   20291     if( pNew==0 && mem0.alarmCallback ){
   20292       sqlite3MallocAlarm(nBytes);
   20293       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   20294     }
   20295     if( pNew ){
   20296       nNew = sqlite3MallocSize(pNew);
   20297       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
   20298     }
   20299     sqlite3_mutex_leave(mem0.mutex);
   20300   }else{
   20301     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   20302   }
   20303   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
   20304   return pNew;
   20305 }
   20306 
   20307 /*
   20308 ** The public interface to sqlite3Realloc.  Make sure that the memory
   20309 ** subsystem is initialized prior to invoking sqliteRealloc.
   20310 */
   20311 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
   20312 #ifndef SQLITE_OMIT_AUTOINIT
   20313   if( sqlite3_initialize() ) return 0;
   20314 #endif
   20315   return sqlite3Realloc(pOld, n);
   20316 }
   20317 
   20318 
   20319 /*
   20320 ** Allocate and zero memory.
   20321 */
   20322 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
   20323   void *p = sqlite3Malloc(n);
   20324   if( p ){
   20325     memset(p, 0, n);
   20326   }
   20327   return p;
   20328 }
   20329 
   20330 /*
   20331 ** Allocate and zero memory.  If the allocation fails, make
   20332 ** the mallocFailed flag in the connection pointer.
   20333 */
   20334 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
   20335   void *p = sqlite3DbMallocRaw(db, n);
   20336   if( p ){
   20337     memset(p, 0, n);
   20338   }
   20339   return p;
   20340 }
   20341 
   20342 /*
   20343 ** Allocate and zero memory.  If the allocation fails, make
   20344 ** the mallocFailed flag in the connection pointer.
   20345 **
   20346 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
   20347 ** failure on the same database connection) then always return 0.
   20348 ** Hence for a particular database connection, once malloc starts
   20349 ** failing, it fails consistently until mallocFailed is reset.
   20350 ** This is an important assumption.  There are many places in the
   20351 ** code that do things like this:
   20352 **
   20353 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
   20354 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
   20355 **         if( b ) a[10] = 9;
   20356 **
   20357 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
   20358 ** that all prior mallocs (ex: "a") worked too.
   20359 */
   20360 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
   20361   void *p;
   20362   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   20363   assert( db==0 || db->pnBytesFreed==0 );
   20364 #ifndef SQLITE_OMIT_LOOKASIDE
   20365   if( db ){
   20366     LookasideSlot *pBuf;
   20367     if( db->mallocFailed ){
   20368       return 0;
   20369     }
   20370     if( db->lookaside.bEnabled ){
   20371       if( n>db->lookaside.sz ){
   20372         db->lookaside.anStat[1]++;
   20373       }else if( (pBuf = db->lookaside.pFree)==0 ){
   20374         db->lookaside.anStat[2]++;
   20375       }else{
   20376         db->lookaside.pFree = pBuf->pNext;
   20377         db->lookaside.nOut++;
   20378         db->lookaside.anStat[0]++;
   20379         if( db->lookaside.nOut>db->lookaside.mxOut ){
   20380           db->lookaside.mxOut = db->lookaside.nOut;
   20381         }
   20382         return (void*)pBuf;
   20383       }
   20384     }
   20385   }
   20386 #else
   20387   if( db && db->mallocFailed ){
   20388     return 0;
   20389   }
   20390 #endif
   20391   p = sqlite3Malloc(n);
   20392   if( !p && db ){
   20393     db->mallocFailed = 1;
   20394   }
   20395   sqlite3MemdebugSetType(p, MEMTYPE_DB |
   20396          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
   20397   return p;
   20398 }
   20399 
   20400 /*
   20401 ** Resize the block of memory pointed to by p to n bytes. If the
   20402 ** resize fails, set the mallocFailed flag in the connection object.
   20403 */
   20404 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
   20405   void *pNew = 0;
   20406   assert( db!=0 );
   20407   assert( sqlite3_mutex_held(db->mutex) );
   20408   if( db->mallocFailed==0 ){
   20409     if( p==0 ){
   20410       return sqlite3DbMallocRaw(db, n);
   20411     }
   20412     if( isLookaside(db, p) ){
   20413       if( n<=db->lookaside.sz ){
   20414         return p;
   20415       }
   20416       pNew = sqlite3DbMallocRaw(db, n);
   20417       if( pNew ){
   20418         memcpy(pNew, p, db->lookaside.sz);
   20419         sqlite3DbFree(db, p);
   20420       }
   20421     }else{
   20422       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   20423       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   20424       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   20425       pNew = sqlite3_realloc(p, n);
   20426       if( !pNew ){
   20427         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
   20428         db->mallocFailed = 1;
   20429       }
   20430       sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
   20431             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
   20432     }
   20433   }
   20434   return pNew;
   20435 }
   20436 
   20437 /*
   20438 ** Attempt to reallocate p.  If the reallocation fails, then free p
   20439 ** and set the mallocFailed flag in the database connection.
   20440 */
   20441 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
   20442   void *pNew;
   20443   pNew = sqlite3DbRealloc(db, p, n);
   20444   if( !pNew ){
   20445     sqlite3DbFree(db, p);
   20446   }
   20447   return pNew;
   20448 }
   20449 
   20450 /*
   20451 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
   20452 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
   20453 ** is because when memory debugging is turned on, these two functions are
   20454 ** called via macros that record the current file and line number in the
   20455 ** ThreadData structure.
   20456 */
   20457 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
   20458   char *zNew;
   20459   size_t n;
   20460   if( z==0 ){
   20461     return 0;
   20462   }
   20463   n = sqlite3Strlen30(z) + 1;
   20464   assert( (n&0x7fffffff)==n );
   20465   zNew = sqlite3DbMallocRaw(db, (int)n);
   20466   if( zNew ){
   20467     memcpy(zNew, z, n);
   20468   }
   20469   return zNew;
   20470 }
   20471 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
   20472   char *zNew;
   20473   if( z==0 ){
   20474     return 0;
   20475   }
   20476   assert( (n&0x7fffffff)==n );
   20477   zNew = sqlite3DbMallocRaw(db, n+1);
   20478   if( zNew ){
   20479     memcpy(zNew, z, n);
   20480     zNew[n] = 0;
   20481   }
   20482   return zNew;
   20483 }
   20484 
   20485 /*
   20486 ** Create a string from the zFromat argument and the va_list that follows.
   20487 ** Store the string in memory obtained from sqliteMalloc() and make *pz
   20488 ** point to that string.
   20489 */
   20490 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
   20491   va_list ap;
   20492   char *z;
   20493 
   20494   va_start(ap, zFormat);
   20495   z = sqlite3VMPrintf(db, zFormat, ap);
   20496   va_end(ap);
   20497   sqlite3DbFree(db, *pz);
   20498   *pz = z;
   20499 }
   20500 
   20501 
   20502 /*
   20503 ** This function must be called before exiting any API function (i.e.
   20504 ** returning control to the user) that has called sqlite3_malloc or
   20505 ** sqlite3_realloc.
   20506 **
   20507 ** The returned value is normally a copy of the second argument to this
   20508 ** function. However, if a malloc() failure has occurred since the previous
   20509 ** invocation SQLITE_NOMEM is returned instead.
   20510 **
   20511 ** If the first argument, db, is not NULL and a malloc() error has occurred,
   20512 ** then the connection error-code (the value returned by sqlite3_errcode())
   20513 ** is set to SQLITE_NOMEM.
   20514 */
   20515 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
   20516   /* If the db handle is not NULL, then we must hold the connection handle
   20517   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
   20518   ** is unsafe, as is the call to sqlite3Error().
   20519   */
   20520   assert( !db || sqlite3_mutex_held(db->mutex) );
   20521   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
   20522     sqlite3Error(db, SQLITE_NOMEM, 0);
   20523     db->mallocFailed = 0;
   20524     rc = SQLITE_NOMEM;
   20525   }
   20526   return rc & (db ? db->errMask : 0xff);
   20527 }
   20528 
   20529 /************** End of malloc.c **********************************************/
   20530 /************** Begin file printf.c ******************************************/
   20531 /*
   20532 ** The "printf" code that follows dates from the 1980's.  It is in
   20533 ** the public domain.  The original comments are included here for
   20534 ** completeness.  They are very out-of-date but might be useful as
   20535 ** an historical reference.  Most of the "enhancements" have been backed
   20536 ** out so that the functionality is now the same as standard printf().
   20537 **
   20538 **************************************************************************
   20539 **
   20540 ** This file contains code for a set of "printf"-like routines.  These
   20541 ** routines format strings much like the printf() from the standard C
   20542 ** library, though the implementation here has enhancements to support
   20543 ** SQLlite.
   20544 */
   20545 
   20546 /*
   20547 ** Conversion types fall into various categories as defined by the
   20548 ** following enumeration.
   20549 */
   20550 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
   20551 #define etFLOAT       2 /* Floating point.  %f */
   20552 #define etEXP         3 /* Exponentional notation. %e and %E */
   20553 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
   20554 #define etSIZE        5 /* Return number of characters processed so far. %n */
   20555 #define etSTRING      6 /* Strings. %s */
   20556 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
   20557 #define etPERCENT     8 /* Percent symbol. %% */
   20558 #define etCHARX       9 /* Characters. %c */
   20559 /* The rest are extensions, not normally found in printf() */
   20560 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
   20561 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
   20562                           NULL pointers replaced by SQL NULL.  %Q */
   20563 #define etTOKEN      12 /* a pointer to a Token structure */
   20564 #define etSRCLIST    13 /* a pointer to a SrcList */
   20565 #define etPOINTER    14 /* The %p conversion */
   20566 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
   20567 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
   20568 
   20569 #define etINVALID     0 /* Any unrecognized conversion type */
   20570 
   20571 
   20572 /*
   20573 ** An "etByte" is an 8-bit unsigned value.
   20574 */
   20575 typedef unsigned char etByte;
   20576 
   20577 /*
   20578 ** Each builtin conversion character (ex: the 'd' in "%d") is described
   20579 ** by an instance of the following structure
   20580 */
   20581 typedef struct et_info {   /* Information about each format field */
   20582   char fmttype;            /* The format field code letter */
   20583   etByte base;             /* The base for radix conversion */
   20584   etByte flags;            /* One or more of FLAG_ constants below */
   20585   etByte type;             /* Conversion paradigm */
   20586   etByte charset;          /* Offset into aDigits[] of the digits string */
   20587   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
   20588 } et_info;
   20589 
   20590 /*
   20591 ** Allowed values for et_info.flags
   20592 */
   20593 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
   20594 #define FLAG_INTERN  2     /* True if for internal use only */
   20595 #define FLAG_STRING  4     /* Allow infinity precision */
   20596 
   20597 
   20598 /*
   20599 ** The following table is searched linearly, so it is good to put the
   20600 ** most frequently used conversion types first.
   20601 */
   20602 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
   20603 static const char aPrefix[] = "-x0\000X0";
   20604 static const et_info fmtinfo[] = {
   20605   {  'd', 10, 1, etRADIX,      0,  0 },
   20606   {  's',  0, 4, etSTRING,     0,  0 },
   20607   {  'g',  0, 1, etGENERIC,    30, 0 },
   20608   {  'z',  0, 4, etDYNSTRING,  0,  0 },
   20609   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
   20610   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
   20611   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
   20612   {  'c',  0, 0, etCHARX,      0,  0 },
   20613   {  'o',  8, 0, etRADIX,      0,  2 },
   20614   {  'u', 10, 0, etRADIX,      0,  0 },
   20615   {  'x', 16, 0, etRADIX,      16, 1 },
   20616   {  'X', 16, 0, etRADIX,      0,  4 },
   20617 #ifndef SQLITE_OMIT_FLOATING_POINT
   20618   {  'f',  0, 1, etFLOAT,      0,  0 },
   20619   {  'e',  0, 1, etEXP,        30, 0 },
   20620   {  'E',  0, 1, etEXP,        14, 0 },
   20621   {  'G',  0, 1, etGENERIC,    14, 0 },
   20622 #endif
   20623   {  'i', 10, 1, etRADIX,      0,  0 },
   20624   {  'n',  0, 0, etSIZE,       0,  0 },
   20625   {  '%',  0, 0, etPERCENT,    0,  0 },
   20626   {  'p', 16, 0, etPOINTER,    0,  1 },
   20627 
   20628 /* All the rest have the FLAG_INTERN bit set and are thus for internal
   20629 ** use only */
   20630   {  'T',  0, 2, etTOKEN,      0,  0 },
   20631   {  'S',  0, 2, etSRCLIST,    0,  0 },
   20632   {  'r', 10, 3, etORDINAL,    0,  0 },
   20633 };
   20634 
   20635 /*
   20636 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
   20637 ** conversions will work.
   20638 */
   20639 #ifndef SQLITE_OMIT_FLOATING_POINT
   20640 /*
   20641 ** "*val" is a double such that 0.1 <= *val < 10.0
   20642 ** Return the ascii code for the leading digit of *val, then
   20643 ** multiply "*val" by 10.0 to renormalize.
   20644 **
   20645 ** Example:
   20646 **     input:     *val = 3.14159
   20647 **     output:    *val = 1.4159    function return = '3'
   20648 **
   20649 ** The counter *cnt is incremented each time.  After counter exceeds
   20650 ** 16 (the number of significant digits in a 64-bit float) '0' is
   20651 ** always returned.
   20652 */
   20653 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
   20654   int digit;
   20655   LONGDOUBLE_TYPE d;
   20656   if( (*cnt)<=0 ) return '0';
   20657   (*cnt)--;
   20658   digit = (int)*val;
   20659   d = digit;
   20660   digit += '0';
   20661   *val = (*val - d)*10.0;
   20662   return (char)digit;
   20663 }
   20664 #endif /* SQLITE_OMIT_FLOATING_POINT */
   20665 
   20666 /*
   20667 ** Set the StrAccum object to an error mode.
   20668 */
   20669 static void setStrAccumError(StrAccum *p, u8 eError){
   20670   p->accError = eError;
   20671   p->nAlloc = 0;
   20672 }
   20673 
   20674 /*
   20675 ** Extra argument values from a PrintfArguments object
   20676 */
   20677 static sqlite3_int64 getIntArg(PrintfArguments *p){
   20678   if( p->nArg<=p->nUsed ) return 0;
   20679   return sqlite3_value_int64(p->apArg[p->nUsed++]);
   20680 }
   20681 static double getDoubleArg(PrintfArguments *p){
   20682   if( p->nArg<=p->nUsed ) return 0.0;
   20683   return sqlite3_value_double(p->apArg[p->nUsed++]);
   20684 }
   20685 static char *getTextArg(PrintfArguments *p){
   20686   if( p->nArg<=p->nUsed ) return 0;
   20687   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
   20688 }
   20689 
   20690 
   20691 /*
   20692 ** On machines with a small stack size, you can redefine the
   20693 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
   20694 */
   20695 #ifndef SQLITE_PRINT_BUF_SIZE
   20696 # define SQLITE_PRINT_BUF_SIZE 70
   20697 #endif
   20698 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
   20699 
   20700 /*
   20701 ** Render a string given by "fmt" into the StrAccum object.
   20702 */
   20703 SQLITE_PRIVATE void sqlite3VXPrintf(
   20704   StrAccum *pAccum,          /* Accumulate results here */
   20705   u32 bFlags,                /* SQLITE_PRINTF_* flags */
   20706   const char *fmt,           /* Format string */
   20707   va_list ap                 /* arguments */
   20708 ){
   20709   int c;                     /* Next character in the format string */
   20710   char *bufpt;               /* Pointer to the conversion buffer */
   20711   int precision;             /* Precision of the current field */
   20712   int length;                /* Length of the field */
   20713   int idx;                   /* A general purpose loop counter */
   20714   int width;                 /* Width of the current field */
   20715   etByte flag_leftjustify;   /* True if "-" flag is present */
   20716   etByte flag_plussign;      /* True if "+" flag is present */
   20717   etByte flag_blanksign;     /* True if " " flag is present */
   20718   etByte flag_alternateform; /* True if "#" flag is present */
   20719   etByte flag_altform2;      /* True if "!" flag is present */
   20720   etByte flag_zeropad;       /* True if field width constant starts with zero */
   20721   etByte flag_long;          /* True if "l" flag is present */
   20722   etByte flag_longlong;      /* True if the "ll" flag is present */
   20723   etByte done;               /* Loop termination flag */
   20724   etByte xtype = 0;          /* Conversion paradigm */
   20725   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
   20726   u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
   20727   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
   20728   sqlite_uint64 longvalue;   /* Value for integer types */
   20729   LONGDOUBLE_TYPE realvalue; /* Value for real types */
   20730   const et_info *infop;      /* Pointer to the appropriate info structure */
   20731   char *zOut;                /* Rendering buffer */
   20732   int nOut;                  /* Size of the rendering buffer */
   20733   char *zExtra;              /* Malloced memory used by some conversion */
   20734 #ifndef SQLITE_OMIT_FLOATING_POINT
   20735   int  exp, e2;              /* exponent of real numbers */
   20736   int nsd;                   /* Number of significant digits returned */
   20737   double rounder;            /* Used for rounding floating point values */
   20738   etByte flag_dp;            /* True if decimal point should be shown */
   20739   etByte flag_rtz;           /* True if trailing zeros should be removed */
   20740 #endif
   20741   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
   20742   char buf[etBUFSIZE];       /* Conversion buffer */
   20743 
   20744   bufpt = 0;
   20745   if( bFlags ){
   20746     if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
   20747       pArgList = va_arg(ap, PrintfArguments*);
   20748     }
   20749     useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
   20750   }else{
   20751     bArgList = useIntern = 0;
   20752   }
   20753   for(; (c=(*fmt))!=0; ++fmt){
   20754     if( c!='%' ){
   20755       bufpt = (char *)fmt;
   20756       while( (c=(*++fmt))!='%' && c!=0 ){};
   20757       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
   20758       if( c==0 ) break;
   20759     }
   20760     if( (c=(*++fmt))==0 ){
   20761       sqlite3StrAccumAppend(pAccum, "%", 1);
   20762       break;
   20763     }
   20764     /* Find out what flags are present */
   20765     flag_leftjustify = flag_plussign = flag_blanksign =
   20766      flag_alternateform = flag_altform2 = flag_zeropad = 0;
   20767     done = 0;
   20768     do{
   20769       switch( c ){
   20770         case '-':   flag_leftjustify = 1;     break;
   20771         case '+':   flag_plussign = 1;        break;
   20772         case ' ':   flag_blanksign = 1;       break;
   20773         case '#':   flag_alternateform = 1;   break;
   20774         case '!':   flag_altform2 = 1;        break;
   20775         case '0':   flag_zeropad = 1;         break;
   20776         default:    done = 1;                 break;
   20777       }
   20778     }while( !done && (c=(*++fmt))!=0 );
   20779     /* Get the field width */
   20780     width = 0;
   20781     if( c=='*' ){
   20782       if( bArgList ){
   20783         width = (int)getIntArg(pArgList);
   20784       }else{
   20785         width = va_arg(ap,int);
   20786       }
   20787       if( width<0 ){
   20788         flag_leftjustify = 1;
   20789         width = -width;
   20790       }
   20791       c = *++fmt;
   20792     }else{
   20793       while( c>='0' && c<='9' ){
   20794         width = width*10 + c - '0';
   20795         c = *++fmt;
   20796       }
   20797     }
   20798     /* Get the precision */
   20799     if( c=='.' ){
   20800       precision = 0;
   20801       c = *++fmt;
   20802       if( c=='*' ){
   20803         if( bArgList ){
   20804           precision = (int)getIntArg(pArgList);
   20805         }else{
   20806           precision = va_arg(ap,int);
   20807         }
   20808         if( precision<0 ) precision = -precision;
   20809         c = *++fmt;
   20810       }else{
   20811         while( c>='0' && c<='9' ){
   20812           precision = precision*10 + c - '0';
   20813           c = *++fmt;
   20814         }
   20815       }
   20816     }else{
   20817       precision = -1;
   20818     }
   20819     /* Get the conversion type modifier */
   20820     if( c=='l' ){
   20821       flag_long = 1;
   20822       c = *++fmt;
   20823       if( c=='l' ){
   20824         flag_longlong = 1;
   20825         c = *++fmt;
   20826       }else{
   20827         flag_longlong = 0;
   20828       }
   20829     }else{
   20830       flag_long = flag_longlong = 0;
   20831     }
   20832     /* Fetch the info entry for the field */
   20833     infop = &fmtinfo[0];
   20834     xtype = etINVALID;
   20835     for(idx=0; idx<ArraySize(fmtinfo); idx++){
   20836       if( c==fmtinfo[idx].fmttype ){
   20837         infop = &fmtinfo[idx];
   20838         if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
   20839           xtype = infop->type;
   20840         }else{
   20841           return;
   20842         }
   20843         break;
   20844       }
   20845     }
   20846     zExtra = 0;
   20847 
   20848     /*
   20849     ** At this point, variables are initialized as follows:
   20850     **
   20851     **   flag_alternateform          TRUE if a '#' is present.
   20852     **   flag_altform2               TRUE if a '!' is present.
   20853     **   flag_plussign               TRUE if a '+' is present.
   20854     **   flag_leftjustify            TRUE if a '-' is present or if the
   20855     **                               field width was negative.
   20856     **   flag_zeropad                TRUE if the width began with 0.
   20857     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
   20858     **                               the conversion character.
   20859     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
   20860     **                               the conversion character.
   20861     **   flag_blanksign              TRUE if a ' ' is present.
   20862     **   width                       The specified field width.  This is
   20863     **                               always non-negative.  Zero is the default.
   20864     **   precision                   The specified precision.  The default
   20865     **                               is -1.
   20866     **   xtype                       The class of the conversion.
   20867     **   infop                       Pointer to the appropriate info struct.
   20868     */
   20869     switch( xtype ){
   20870       case etPOINTER:
   20871         flag_longlong = sizeof(char*)==sizeof(i64);
   20872         flag_long = sizeof(char*)==sizeof(long int);
   20873         /* Fall through into the next case */
   20874       case etORDINAL:
   20875       case etRADIX:
   20876         if( infop->flags & FLAG_SIGNED ){
   20877           i64 v;
   20878           if( bArgList ){
   20879             v = getIntArg(pArgList);
   20880           }else if( flag_longlong ){
   20881             v = va_arg(ap,i64);
   20882           }else if( flag_long ){
   20883             v = va_arg(ap,long int);
   20884           }else{
   20885             v = va_arg(ap,int);
   20886           }
   20887           if( v<0 ){
   20888             if( v==SMALLEST_INT64 ){
   20889               longvalue = ((u64)1)<<63;
   20890             }else{
   20891               longvalue = -v;
   20892             }
   20893             prefix = '-';
   20894           }else{
   20895             longvalue = v;
   20896             if( flag_plussign )        prefix = '+';
   20897             else if( flag_blanksign )  prefix = ' ';
   20898             else                       prefix = 0;
   20899           }
   20900         }else{
   20901           if( bArgList ){
   20902             longvalue = (u64)getIntArg(pArgList);
   20903           }else if( flag_longlong ){
   20904             longvalue = va_arg(ap,u64);
   20905           }else if( flag_long ){
   20906             longvalue = va_arg(ap,unsigned long int);
   20907           }else{
   20908             longvalue = va_arg(ap,unsigned int);
   20909           }
   20910           prefix = 0;
   20911         }
   20912         if( longvalue==0 ) flag_alternateform = 0;
   20913         if( flag_zeropad && precision<width-(prefix!=0) ){
   20914           precision = width-(prefix!=0);
   20915         }
   20916         if( precision<etBUFSIZE-10 ){
   20917           nOut = etBUFSIZE;
   20918           zOut = buf;
   20919         }else{
   20920           nOut = precision + 10;
   20921           zOut = zExtra = sqlite3Malloc( nOut );
   20922           if( zOut==0 ){
   20923             setStrAccumError(pAccum, STRACCUM_NOMEM);
   20924             return;
   20925           }
   20926         }
   20927         bufpt = &zOut[nOut-1];
   20928         if( xtype==etORDINAL ){
   20929           static const char zOrd[] = "thstndrd";
   20930           int x = (int)(longvalue % 10);
   20931           if( x>=4 || (longvalue/10)%10==1 ){
   20932             x = 0;
   20933           }
   20934           *(--bufpt) = zOrd[x*2+1];
   20935           *(--bufpt) = zOrd[x*2];
   20936         }
   20937         {
   20938           const char *cset = &aDigits[infop->charset];
   20939           u8 base = infop->base;
   20940           do{                                           /* Convert to ascii */
   20941             *(--bufpt) = cset[longvalue%base];
   20942             longvalue = longvalue/base;
   20943           }while( longvalue>0 );
   20944         }
   20945         length = (int)(&zOut[nOut-1]-bufpt);
   20946         for(idx=precision-length; idx>0; idx--){
   20947           *(--bufpt) = '0';                             /* Zero pad */
   20948         }
   20949         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
   20950         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
   20951           const char *pre;
   20952           char x;
   20953           pre = &aPrefix[infop->prefix];
   20954           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
   20955         }
   20956         length = (int)(&zOut[nOut-1]-bufpt);
   20957         break;
   20958       case etFLOAT:
   20959       case etEXP:
   20960       case etGENERIC:
   20961         if( bArgList ){
   20962           realvalue = getDoubleArg(pArgList);
   20963         }else{
   20964           realvalue = va_arg(ap,double);
   20965         }
   20966 #ifdef SQLITE_OMIT_FLOATING_POINT
   20967         length = 0;
   20968 #else
   20969         if( precision<0 ) precision = 6;         /* Set default precision */
   20970         if( realvalue<0.0 ){
   20971           realvalue = -realvalue;
   20972           prefix = '-';
   20973         }else{
   20974           if( flag_plussign )          prefix = '+';
   20975           else if( flag_blanksign )    prefix = ' ';
   20976           else                         prefix = 0;
   20977         }
   20978         if( xtype==etGENERIC && precision>0 ) precision--;
   20979         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
   20980         if( xtype==etFLOAT ) realvalue += rounder;
   20981         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
   20982         exp = 0;
   20983         if( sqlite3IsNaN((double)realvalue) ){
   20984           bufpt = "NaN";
   20985           length = 3;
   20986           break;
   20987         }
   20988         if( realvalue>0.0 ){
   20989           LONGDOUBLE_TYPE scale = 1.0;
   20990           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
   20991           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
   20992           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
   20993           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
   20994           realvalue /= scale;
   20995           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
   20996           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
   20997           if( exp>350 ){
   20998             if( prefix=='-' ){
   20999               bufpt = "-Inf";
   21000             }else if( prefix=='+' ){
   21001               bufpt = "+Inf";
   21002             }else{
   21003               bufpt = "Inf";
   21004             }
   21005             length = sqlite3Strlen30(bufpt);
   21006             break;
   21007           }
   21008         }
   21009         bufpt = buf;
   21010         /*
   21011         ** If the field type is etGENERIC, then convert to either etEXP
   21012         ** or etFLOAT, as appropriate.
   21013         */
   21014         if( xtype!=etFLOAT ){
   21015           realvalue += rounder;
   21016           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
   21017         }
   21018         if( xtype==etGENERIC ){
   21019           flag_rtz = !flag_alternateform;
   21020           if( exp<-4 || exp>precision ){
   21021             xtype = etEXP;
   21022           }else{
   21023             precision = precision - exp;
   21024             xtype = etFLOAT;
   21025           }
   21026         }else{
   21027           flag_rtz = flag_altform2;
   21028         }
   21029         if( xtype==etEXP ){
   21030           e2 = 0;
   21031         }else{
   21032           e2 = exp;
   21033         }
   21034         if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
   21035           bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
   21036           if( bufpt==0 ){
   21037             setStrAccumError(pAccum, STRACCUM_NOMEM);
   21038             return;
   21039           }
   21040         }
   21041         zOut = bufpt;
   21042         nsd = 16 + flag_altform2*10;
   21043         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
   21044         /* The sign in front of the number */
   21045         if( prefix ){
   21046           *(bufpt++) = prefix;
   21047         }
   21048         /* Digits prior to the decimal point */
   21049         if( e2<0 ){
   21050           *(bufpt++) = '0';
   21051         }else{
   21052           for(; e2>=0; e2--){
   21053             *(bufpt++) = et_getdigit(&realvalue,&nsd);
   21054           }
   21055         }
   21056         /* The decimal point */
   21057         if( flag_dp ){
   21058           *(bufpt++) = '.';
   21059         }
   21060         /* "0" digits after the decimal point but before the first
   21061         ** significant digit of the number */
   21062         for(e2++; e2<0; precision--, e2++){
   21063           assert( precision>0 );
   21064           *(bufpt++) = '0';
   21065         }
   21066         /* Significant digits after the decimal point */
   21067         while( (precision--)>0 ){
   21068           *(bufpt++) = et_getdigit(&realvalue,&nsd);
   21069         }
   21070         /* Remove trailing zeros and the "." if no digits follow the "." */
   21071         if( flag_rtz && flag_dp ){
   21072           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
   21073           assert( bufpt>zOut );
   21074           if( bufpt[-1]=='.' ){
   21075             if( flag_altform2 ){
   21076               *(bufpt++) = '0';
   21077             }else{
   21078               *(--bufpt) = 0;
   21079             }
   21080           }
   21081         }
   21082         /* Add the "eNNN" suffix */
   21083         if( xtype==etEXP ){
   21084           *(bufpt++) = aDigits[infop->charset];
   21085           if( exp<0 ){
   21086             *(bufpt++) = '-'; exp = -exp;
   21087           }else{
   21088             *(bufpt++) = '+';
   21089           }
   21090           if( exp>=100 ){
   21091             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
   21092             exp %= 100;
   21093           }
   21094           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
   21095           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
   21096         }
   21097         *bufpt = 0;
   21098 
   21099         /* The converted number is in buf[] and zero terminated. Output it.
   21100         ** Note that the number is in the usual order, not reversed as with
   21101         ** integer conversions. */
   21102         length = (int)(bufpt-zOut);
   21103         bufpt = zOut;
   21104 
   21105         /* Special case:  Add leading zeros if the flag_zeropad flag is
   21106         ** set and we are not left justified */
   21107         if( flag_zeropad && !flag_leftjustify && length < width){
   21108           int i;
   21109           int nPad = width - length;
   21110           for(i=width; i>=nPad; i--){
   21111             bufpt[i] = bufpt[i-nPad];
   21112           }
   21113           i = prefix!=0;
   21114           while( nPad-- ) bufpt[i++] = '0';
   21115           length = width;
   21116         }
   21117 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
   21118         break;
   21119       case etSIZE:
   21120         if( !bArgList ){
   21121           *(va_arg(ap,int*)) = pAccum->nChar;
   21122         }
   21123         length = width = 0;
   21124         break;
   21125       case etPERCENT:
   21126         buf[0] = '%';
   21127         bufpt = buf;
   21128         length = 1;
   21129         break;
   21130       case etCHARX:
   21131         if( bArgList ){
   21132           bufpt = getTextArg(pArgList);
   21133           c = bufpt ? bufpt[0] : 0;
   21134         }else{
   21135           c = va_arg(ap,int);
   21136         }
   21137         buf[0] = (char)c;
   21138         if( precision>=0 ){
   21139           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
   21140           length = precision;
   21141         }else{
   21142           length =1;
   21143         }
   21144         bufpt = buf;
   21145         break;
   21146       case etSTRING:
   21147       case etDYNSTRING:
   21148         if( bArgList ){
   21149           bufpt = getTextArg(pArgList);
   21150         }else{
   21151           bufpt = va_arg(ap,char*);
   21152         }
   21153         if( bufpt==0 ){
   21154           bufpt = "";
   21155         }else if( xtype==etDYNSTRING && !bArgList ){
   21156           zExtra = bufpt;
   21157         }
   21158         if( precision>=0 ){
   21159           for(length=0; length<precision && bufpt[length]; length++){}
   21160         }else{
   21161           length = sqlite3Strlen30(bufpt);
   21162         }
   21163         break;
   21164       case etSQLESCAPE:
   21165       case etSQLESCAPE2:
   21166       case etSQLESCAPE3: {
   21167         int i, j, k, n, isnull;
   21168         int needQuote;
   21169         char ch;
   21170         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
   21171         char *escarg;
   21172 
   21173         if( bArgList ){
   21174           escarg = getTextArg(pArgList);
   21175         }else{
   21176           escarg = va_arg(ap,char*);
   21177         }
   21178         isnull = escarg==0;
   21179         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
   21180         k = precision;
   21181         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
   21182           if( ch==q )  n++;
   21183         }
   21184         needQuote = !isnull && xtype==etSQLESCAPE2;
   21185         n += i + 1 + needQuote*2;
   21186         if( n>etBUFSIZE ){
   21187           bufpt = zExtra = sqlite3Malloc( n );
   21188           if( bufpt==0 ){
   21189             setStrAccumError(pAccum, STRACCUM_NOMEM);
   21190             return;
   21191           }
   21192         }else{
   21193           bufpt = buf;
   21194         }
   21195         j = 0;
   21196         if( needQuote ) bufpt[j++] = q;
   21197         k = i;
   21198         for(i=0; i<k; i++){
   21199           bufpt[j++] = ch = escarg[i];
   21200           if( ch==q ) bufpt[j++] = ch;
   21201         }
   21202         if( needQuote ) bufpt[j++] = q;
   21203         bufpt[j] = 0;
   21204         length = j;
   21205         /* The precision in %q and %Q means how many input characters to
   21206         ** consume, not the length of the output...
   21207         ** if( precision>=0 && precision<length ) length = precision; */
   21208         break;
   21209       }
   21210       case etTOKEN: {
   21211         Token *pToken = va_arg(ap, Token*);
   21212         assert( bArgList==0 );
   21213         if( pToken && pToken->n ){
   21214           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
   21215         }
   21216         length = width = 0;
   21217         break;
   21218       }
   21219       case etSRCLIST: {
   21220         SrcList *pSrc = va_arg(ap, SrcList*);
   21221         int k = va_arg(ap, int);
   21222         struct SrcList_item *pItem = &pSrc->a[k];
   21223         assert( bArgList==0 );
   21224         assert( k>=0 && k<pSrc->nSrc );
   21225         if( pItem->zDatabase ){
   21226           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
   21227           sqlite3StrAccumAppend(pAccum, ".", 1);
   21228         }
   21229         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
   21230         length = width = 0;
   21231         break;
   21232       }
   21233       default: {
   21234         assert( xtype==etINVALID );
   21235         return;
   21236       }
   21237     }/* End switch over the format type */
   21238     /*
   21239     ** The text of the conversion is pointed to by "bufpt" and is
   21240     ** "length" characters long.  The field width is "width".  Do
   21241     ** the output.
   21242     */
   21243     width -= length;
   21244     if( width>0 && !flag_leftjustify ) sqlite3AppendSpace(pAccum, width);
   21245     sqlite3StrAccumAppend(pAccum, bufpt, length);
   21246     if( width>0 && flag_leftjustify ) sqlite3AppendSpace(pAccum, width);
   21247 
   21248     if( zExtra ) sqlite3_free(zExtra);
   21249   }/* End for loop over the format string */
   21250 } /* End of function */
   21251 
   21252 /*
   21253 ** Enlarge the memory allocation on a StrAccum object so that it is
   21254 ** able to accept at least N more bytes of text.
   21255 **
   21256 ** Return the number of bytes of text that StrAccum is able to accept
   21257 ** after the attempted enlargement.  The value returned might be zero.
   21258 */
   21259 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
   21260   char *zNew;
   21261   assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
   21262   if( p->accError ){
   21263     testcase(p->accError==STRACCUM_TOOBIG);
   21264     testcase(p->accError==STRACCUM_NOMEM);
   21265     return 0;
   21266   }
   21267   if( !p->useMalloc ){
   21268     N = p->nAlloc - p->nChar - 1;
   21269     setStrAccumError(p, STRACCUM_TOOBIG);
   21270     return N;
   21271   }else{
   21272     char *zOld = (p->zText==p->zBase ? 0 : p->zText);
   21273     i64 szNew = p->nChar;
   21274     szNew += N + 1;
   21275     if( szNew > p->mxAlloc ){
   21276       sqlite3StrAccumReset(p);
   21277       setStrAccumError(p, STRACCUM_TOOBIG);
   21278       return 0;
   21279     }else{
   21280       p->nAlloc = (int)szNew;
   21281     }
   21282     if( p->useMalloc==1 ){
   21283       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
   21284     }else{
   21285       zNew = sqlite3_realloc(zOld, p->nAlloc);
   21286     }
   21287     if( zNew ){
   21288       assert( p->zText!=0 || p->nChar==0 );
   21289       if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
   21290       p->zText = zNew;
   21291     }else{
   21292       sqlite3StrAccumReset(p);
   21293       setStrAccumError(p, STRACCUM_NOMEM);
   21294       return 0;
   21295     }
   21296   }
   21297   return N;
   21298 }
   21299 
   21300 /*
   21301 ** Append N space characters to the given string buffer.
   21302 */
   21303 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *p, int N){
   21304   if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
   21305   while( (N--)>0 ) p->zText[p->nChar++] = ' ';
   21306 }
   21307 
   21308 /*
   21309 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
   21310 ** So enlarge if first, then do the append.
   21311 **
   21312 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
   21313 ** work (enlarging the buffer) using tail recursion, so that the
   21314 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
   21315 */
   21316 static void enlargeAndAppend(StrAccum *p, const char *z, int N){
   21317   N = sqlite3StrAccumEnlarge(p, N);
   21318   if( N>0 ){
   21319     memcpy(&p->zText[p->nChar], z, N);
   21320     p->nChar += N;
   21321   }
   21322 }
   21323 
   21324 /*
   21325 ** Append N bytes of text from z to the StrAccum object.  Increase the
   21326 ** size of the memory allocation for StrAccum if necessary.
   21327 */
   21328 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
   21329   assert( z!=0 );
   21330   assert( p->zText!=0 || p->nChar==0 || p->accError );
   21331   assert( N>=0 );
   21332   assert( p->accError==0 || p->nAlloc==0 );
   21333   if( p->nChar+N >= p->nAlloc ){
   21334     enlargeAndAppend(p,z,N);
   21335     return;
   21336   }
   21337   assert( p->zText );
   21338   memcpy(&p->zText[p->nChar], z, N);
   21339   p->nChar += N;
   21340 }
   21341 
   21342 /*
   21343 ** Append the complete text of zero-terminated string z[] to the p string.
   21344 */
   21345 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
   21346   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
   21347 }
   21348 
   21349 
   21350 /*
   21351 ** Finish off a string by making sure it is zero-terminated.
   21352 ** Return a pointer to the resulting string.  Return a NULL
   21353 ** pointer if any kind of error was encountered.
   21354 */
   21355 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
   21356   if( p->zText ){
   21357     p->zText[p->nChar] = 0;
   21358     if( p->useMalloc && p->zText==p->zBase ){
   21359       if( p->useMalloc==1 ){
   21360         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
   21361       }else{
   21362         p->zText = sqlite3_malloc(p->nChar+1);
   21363       }
   21364       if( p->zText ){
   21365         memcpy(p->zText, p->zBase, p->nChar+1);
   21366       }else{
   21367         setStrAccumError(p, STRACCUM_NOMEM);
   21368       }
   21369     }
   21370   }
   21371   return p->zText;
   21372 }
   21373 
   21374 /*
   21375 ** Reset an StrAccum string.  Reclaim all malloced memory.
   21376 */
   21377 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
   21378   if( p->zText!=p->zBase ){
   21379     if( p->useMalloc==1 ){
   21380       sqlite3DbFree(p->db, p->zText);
   21381     }else{
   21382       sqlite3_free(p->zText);
   21383     }
   21384   }
   21385   p->zText = 0;
   21386 }
   21387 
   21388 /*
   21389 ** Initialize a string accumulator
   21390 */
   21391 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
   21392   p->zText = p->zBase = zBase;
   21393   p->db = 0;
   21394   p->nChar = 0;
   21395   p->nAlloc = n;
   21396   p->mxAlloc = mx;
   21397   p->useMalloc = 1;
   21398   p->accError = 0;
   21399 }
   21400 
   21401 /*
   21402 ** Print into memory obtained from sqliteMalloc().  Use the internal
   21403 ** %-conversion extensions.
   21404 */
   21405 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
   21406   char *z;
   21407   char zBase[SQLITE_PRINT_BUF_SIZE];
   21408   StrAccum acc;
   21409   assert( db!=0 );
   21410   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
   21411                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   21412   acc.db = db;
   21413   sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
   21414   z = sqlite3StrAccumFinish(&acc);
   21415   if( acc.accError==STRACCUM_NOMEM ){
   21416     db->mallocFailed = 1;
   21417   }
   21418   return z;
   21419 }
   21420 
   21421 /*
   21422 ** Print into memory obtained from sqliteMalloc().  Use the internal
   21423 ** %-conversion extensions.
   21424 */
   21425 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
   21426   va_list ap;
   21427   char *z;
   21428   va_start(ap, zFormat);
   21429   z = sqlite3VMPrintf(db, zFormat, ap);
   21430   va_end(ap);
   21431   return z;
   21432 }
   21433 
   21434 /*
   21435 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
   21436 ** the string and before returnning.  This routine is intended to be used
   21437 ** to modify an existing string.  For example:
   21438 **
   21439 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
   21440 **
   21441 */
   21442 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
   21443   va_list ap;
   21444   char *z;
   21445   va_start(ap, zFormat);
   21446   z = sqlite3VMPrintf(db, zFormat, ap);
   21447   va_end(ap);
   21448   sqlite3DbFree(db, zStr);
   21449   return z;
   21450 }
   21451 
   21452 /*
   21453 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
   21454 ** %-conversion extensions.
   21455 */
   21456 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
   21457   char *z;
   21458   char zBase[SQLITE_PRINT_BUF_SIZE];
   21459   StrAccum acc;
   21460 #ifndef SQLITE_OMIT_AUTOINIT
   21461   if( sqlite3_initialize() ) return 0;
   21462 #endif
   21463   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
   21464   acc.useMalloc = 2;
   21465   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   21466   z = sqlite3StrAccumFinish(&acc);
   21467   return z;
   21468 }
   21469 
   21470 /*
   21471 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
   21472 ** %-conversion extensions.
   21473 */
   21474 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
   21475   va_list ap;
   21476   char *z;
   21477 #ifndef SQLITE_OMIT_AUTOINIT
   21478   if( sqlite3_initialize() ) return 0;
   21479 #endif
   21480   va_start(ap, zFormat);
   21481   z = sqlite3_vmprintf(zFormat, ap);
   21482   va_end(ap);
   21483   return z;
   21484 }
   21485 
   21486 /*
   21487 ** sqlite3_snprintf() works like snprintf() except that it ignores the
   21488 ** current locale settings.  This is important for SQLite because we
   21489 ** are not able to use a "," as the decimal point in place of "." as
   21490 ** specified by some locales.
   21491 **
   21492 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
   21493 ** from the snprintf() standard.  Unfortunately, it is too late to change
   21494 ** this without breaking compatibility, so we just have to live with the
   21495 ** mistake.
   21496 **
   21497 ** sqlite3_vsnprintf() is the varargs version.
   21498 */
   21499 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
   21500   StrAccum acc;
   21501   if( n<=0 ) return zBuf;
   21502   sqlite3StrAccumInit(&acc, zBuf, n, 0);
   21503   acc.useMalloc = 0;
   21504   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   21505   return sqlite3StrAccumFinish(&acc);
   21506 }
   21507 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
   21508   char *z;
   21509   va_list ap;
   21510   va_start(ap,zFormat);
   21511   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
   21512   va_end(ap);
   21513   return z;
   21514 }
   21515 
   21516 /*
   21517 ** This is the routine that actually formats the sqlite3_log() message.
   21518 ** We house it in a separate routine from sqlite3_log() to avoid using
   21519 ** stack space on small-stack systems when logging is disabled.
   21520 **
   21521 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
   21522 ** allocate memory because it might be called while the memory allocator
   21523 ** mutex is held.
   21524 */
   21525 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
   21526   StrAccum acc;                          /* String accumulator */
   21527   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
   21528 
   21529   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
   21530   acc.useMalloc = 0;
   21531   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   21532   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
   21533                            sqlite3StrAccumFinish(&acc));
   21534 }
   21535 
   21536 /*
   21537 ** Format and write a message to the log if logging is enabled.
   21538 */
   21539 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
   21540   va_list ap;                             /* Vararg list */
   21541   if( sqlite3GlobalConfig.xLog ){
   21542     va_start(ap, zFormat);
   21543     renderLogMsg(iErrCode, zFormat, ap);
   21544     va_end(ap);
   21545   }
   21546 }
   21547 
   21548 #if defined(SQLITE_DEBUG)
   21549 /*
   21550 ** A version of printf() that understands %lld.  Used for debugging.
   21551 ** The printf() built into some versions of windows does not understand %lld
   21552 ** and segfaults if you give it a long long int.
   21553 */
   21554 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
   21555   va_list ap;
   21556   StrAccum acc;
   21557   char zBuf[500];
   21558   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
   21559   acc.useMalloc = 0;
   21560   va_start(ap,zFormat);
   21561   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   21562   va_end(ap);
   21563   sqlite3StrAccumFinish(&acc);
   21564   fprintf(stdout,"%s", zBuf);
   21565   fflush(stdout);
   21566 }
   21567 #endif
   21568 
   21569 /*
   21570 ** variable-argument wrapper around sqlite3VXPrintf().
   21571 */
   21572 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
   21573   va_list ap;
   21574   va_start(ap,zFormat);
   21575   sqlite3VXPrintf(p, bFlags, zFormat, ap);
   21576   va_end(ap);
   21577 }
   21578 
   21579 /************** End of printf.c **********************************************/
   21580 /************** Begin file random.c ******************************************/
   21581 /*
   21582 ** 2001 September 15
   21583 **
   21584 ** The author disclaims copyright to this source code.  In place of
   21585 ** a legal notice, here is a blessing:
   21586 **
   21587 **    May you do good and not evil.
   21588 **    May you find forgiveness for yourself and forgive others.
   21589 **    May you share freely, never taking more than you give.
   21590 **
   21591 *************************************************************************
   21592 ** This file contains code to implement a pseudo-random number
   21593 ** generator (PRNG) for SQLite.
   21594 **
   21595 ** Random numbers are used by some of the database backends in order
   21596 ** to generate random integer keys for tables or random filenames.
   21597 */
   21598 
   21599 
   21600 /* All threads share a single random number generator.
   21601 ** This structure is the current state of the generator.
   21602 */
   21603 static SQLITE_WSD struct sqlite3PrngType {
   21604   unsigned char isInit;          /* True if initialized */
   21605   unsigned char i, j;            /* State variables */
   21606   unsigned char s[256];          /* State variables */
   21607 } sqlite3Prng;
   21608 
   21609 /*
   21610 ** Return N random bytes.
   21611 */
   21612 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
   21613   unsigned char t;
   21614   unsigned char *zBuf = pBuf;
   21615 
   21616   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
   21617   ** state vector.  If writable static data is unsupported on the target,
   21618   ** we have to locate the state vector at run-time.  In the more common
   21619   ** case where writable static data is supported, wsdPrng can refer directly
   21620   ** to the "sqlite3Prng" state vector declared above.
   21621   */
   21622 #ifdef SQLITE_OMIT_WSD
   21623   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
   21624 # define wsdPrng p[0]
   21625 #else
   21626 # define wsdPrng sqlite3Prng
   21627 #endif
   21628 
   21629 #if SQLITE_THREADSAFE
   21630   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
   21631   sqlite3_mutex_enter(mutex);
   21632 #endif
   21633 
   21634   if( N<=0 ){
   21635     wsdPrng.isInit = 0;
   21636     sqlite3_mutex_leave(mutex);
   21637     return;
   21638   }
   21639 
   21640   /* Initialize the state of the random number generator once,
   21641   ** the first time this routine is called.  The seed value does
   21642   ** not need to contain a lot of randomness since we are not
   21643   ** trying to do secure encryption or anything like that...
   21644   **
   21645   ** Nothing in this file or anywhere else in SQLite does any kind of
   21646   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
   21647   ** number generator) not as an encryption device.
   21648   */
   21649   if( !wsdPrng.isInit ){
   21650     int i;
   21651     char k[256];
   21652     wsdPrng.j = 0;
   21653     wsdPrng.i = 0;
   21654     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
   21655     for(i=0; i<256; i++){
   21656       wsdPrng.s[i] = (u8)i;
   21657     }
   21658     for(i=0; i<256; i++){
   21659       wsdPrng.j += wsdPrng.s[i] + k[i];
   21660       t = wsdPrng.s[wsdPrng.j];
   21661       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
   21662       wsdPrng.s[i] = t;
   21663     }
   21664     wsdPrng.isInit = 1;
   21665   }
   21666 
   21667   assert( N>0 );
   21668   do{
   21669     wsdPrng.i++;
   21670     t = wsdPrng.s[wsdPrng.i];
   21671     wsdPrng.j += t;
   21672     wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
   21673     wsdPrng.s[wsdPrng.j] = t;
   21674     t += wsdPrng.s[wsdPrng.i];
   21675     *(zBuf++) = wsdPrng.s[t];
   21676   }while( --N );
   21677   sqlite3_mutex_leave(mutex);
   21678 }
   21679 
   21680 #ifndef SQLITE_OMIT_BUILTIN_TEST
   21681 /*
   21682 ** For testing purposes, we sometimes want to preserve the state of
   21683 ** PRNG and restore the PRNG to its saved state at a later time, or
   21684 ** to reset the PRNG to its initial state.  These routines accomplish
   21685 ** those tasks.
   21686 **
   21687 ** The sqlite3_test_control() interface calls these routines to
   21688 ** control the PRNG.
   21689 */
   21690 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
   21691 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
   21692   memcpy(
   21693     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   21694     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   21695     sizeof(sqlite3Prng)
   21696   );
   21697 }
   21698 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
   21699   memcpy(
   21700     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   21701     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   21702     sizeof(sqlite3Prng)
   21703   );
   21704 }
   21705 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   21706 
   21707 /************** End of random.c **********************************************/
   21708 /************** Begin file utf.c *********************************************/
   21709 /*
   21710 ** 2004 April 13
   21711 **
   21712 ** The author disclaims copyright to this source code.  In place of
   21713 ** a legal notice, here is a blessing:
   21714 **
   21715 **    May you do good and not evil.
   21716 **    May you find forgiveness for yourself and forgive others.
   21717 **    May you share freely, never taking more than you give.
   21718 **
   21719 *************************************************************************
   21720 ** This file contains routines used to translate between UTF-8,
   21721 ** UTF-16, UTF-16BE, and UTF-16LE.
   21722 **
   21723 ** Notes on UTF-8:
   21724 **
   21725 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
   21726 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
   21727 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
   21728 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
   21729 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
   21730 **
   21731 **
   21732 ** Notes on UTF-16:  (with wwww+1==uuuuu)
   21733 **
   21734 **      Word-0               Word-1          Value
   21735 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
   21736 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
   21737 **
   21738 **
   21739 ** BOM or Byte Order Mark:
   21740 **     0xff 0xfe   little-endian utf-16 follows
   21741 **     0xfe 0xff   big-endian utf-16 follows
   21742 **
   21743 */
   21744 /* #include <assert.h> */
   21745 
   21746 #ifndef SQLITE_AMALGAMATION
   21747 /*
   21748 ** The following constant value is used by the SQLITE_BIGENDIAN and
   21749 ** SQLITE_LITTLEENDIAN macros.
   21750 */
   21751 SQLITE_PRIVATE const int sqlite3one = 1;
   21752 #endif /* SQLITE_AMALGAMATION */
   21753 
   21754 /*
   21755 ** This lookup table is used to help decode the first byte of
   21756 ** a multi-byte UTF8 character.
   21757 */
   21758 static const unsigned char sqlite3Utf8Trans1[] = {
   21759   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   21760   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   21761   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   21762   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   21763   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   21764   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   21765   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   21766   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   21767 };
   21768 
   21769 
   21770 #define WRITE_UTF8(zOut, c) {                          \
   21771   if( c<0x00080 ){                                     \
   21772     *zOut++ = (u8)(c&0xFF);                            \
   21773   }                                                    \
   21774   else if( c<0x00800 ){                                \
   21775     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
   21776     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   21777   }                                                    \
   21778   else if( c<0x10000 ){                                \
   21779     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
   21780     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   21781     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   21782   }else{                                               \
   21783     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
   21784     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
   21785     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   21786     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   21787   }                                                    \
   21788 }
   21789 
   21790 #define WRITE_UTF16LE(zOut, c) {                                    \
   21791   if( c<=0xFFFF ){                                                  \
   21792     *zOut++ = (u8)(c&0x00FF);                                       \
   21793     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   21794   }else{                                                            \
   21795     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   21796     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   21797     *zOut++ = (u8)(c&0x00FF);                                       \
   21798     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   21799   }                                                                 \
   21800 }
   21801 
   21802 #define WRITE_UTF16BE(zOut, c) {                                    \
   21803   if( c<=0xFFFF ){                                                  \
   21804     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   21805     *zOut++ = (u8)(c&0x00FF);                                       \
   21806   }else{                                                            \
   21807     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   21808     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   21809     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   21810     *zOut++ = (u8)(c&0x00FF);                                       \
   21811   }                                                                 \
   21812 }
   21813 
   21814 #define READ_UTF16LE(zIn, TERM, c){                                   \
   21815   c = (*zIn++);                                                       \
   21816   c += ((*zIn++)<<8);                                                 \
   21817   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   21818     int c2 = (*zIn++);                                                \
   21819     c2 += ((*zIn++)<<8);                                              \
   21820     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   21821   }                                                                   \
   21822 }
   21823 
   21824 #define READ_UTF16BE(zIn, TERM, c){                                   \
   21825   c = ((*zIn++)<<8);                                                  \
   21826   c += (*zIn++);                                                      \
   21827   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   21828     int c2 = ((*zIn++)<<8);                                           \
   21829     c2 += (*zIn++);                                                   \
   21830     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   21831   }                                                                   \
   21832 }
   21833 
   21834 /*
   21835 ** Translate a single UTF-8 character.  Return the unicode value.
   21836 **
   21837 ** During translation, assume that the byte that zTerm points
   21838 ** is a 0x00.
   21839 **
   21840 ** Write a pointer to the next unread byte back into *pzNext.
   21841 **
   21842 ** Notes On Invalid UTF-8:
   21843 **
   21844 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
   21845 **     be encoded as a multi-byte character.  Any multi-byte character that
   21846 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
   21847 **
   21848 **  *  This routine never allows a UTF16 surrogate value to be encoded.
   21849 **     If a multi-byte character attempts to encode a value between
   21850 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
   21851 **
   21852 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
   21853 **     byte of a character are interpreted as single-byte characters
   21854 **     and rendered as themselves even though they are technically
   21855 **     invalid characters.
   21856 **
   21857 **  *  This routine accepts over-length UTF8 encodings
   21858 **     for unicode values 0x80 and greater.  It does not change over-length
   21859 **     encodings to 0xfffd as some systems recommend.
   21860 */
   21861 #define READ_UTF8(zIn, zTerm, c)                           \
   21862   c = *(zIn++);                                            \
   21863   if( c>=0xc0 ){                                           \
   21864     c = sqlite3Utf8Trans1[c-0xc0];                         \
   21865     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   21866       c = (c<<6) + (0x3f & *(zIn++));                      \
   21867     }                                                      \
   21868     if( c<0x80                                             \
   21869         || (c&0xFFFFF800)==0xD800                          \
   21870         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   21871   }
   21872 SQLITE_PRIVATE u32 sqlite3Utf8Read(
   21873   const unsigned char **pz    /* Pointer to string from which to read char */
   21874 ){
   21875   unsigned int c;
   21876 
   21877   /* Same as READ_UTF8() above but without the zTerm parameter.
   21878   ** For this routine, we assume the UTF8 string is always zero-terminated.
   21879   */
   21880   c = *((*pz)++);
   21881   if( c>=0xc0 ){
   21882     c = sqlite3Utf8Trans1[c-0xc0];
   21883     while( (*(*pz) & 0xc0)==0x80 ){
   21884       c = (c<<6) + (0x3f & *((*pz)++));
   21885     }
   21886     if( c<0x80
   21887         || (c&0xFFFFF800)==0xD800
   21888         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
   21889   }
   21890   return c;
   21891 }
   21892 
   21893 
   21894 
   21895 
   21896 /*
   21897 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
   21898 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
   21899 */
   21900 /* #define TRANSLATE_TRACE 1 */
   21901 
   21902 #ifndef SQLITE_OMIT_UTF16
   21903 /*
   21904 ** This routine transforms the internal text encoding used by pMem to
   21905 ** desiredEnc. It is an error if the string is already of the desired
   21906 ** encoding, or if *pMem does not contain a string value.
   21907 */
   21908 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
   21909   int len;                    /* Maximum length of output string in bytes */
   21910   unsigned char *zOut;                  /* Output buffer */
   21911   unsigned char *zIn;                   /* Input iterator */
   21912   unsigned char *zTerm;                 /* End of input */
   21913   unsigned char *z;                     /* Output iterator */
   21914   unsigned int c;
   21915 
   21916   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   21917   assert( pMem->flags&MEM_Str );
   21918   assert( pMem->enc!=desiredEnc );
   21919   assert( pMem->enc!=0 );
   21920   assert( pMem->n>=0 );
   21921 
   21922 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   21923   {
   21924     char zBuf[100];
   21925     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   21926     fprintf(stderr, "INPUT:  %s\n", zBuf);
   21927   }
   21928 #endif
   21929 
   21930   /* If the translation is between UTF-16 little and big endian, then
   21931   ** all that is required is to swap the byte order. This case is handled
   21932   ** differently from the others.
   21933   */
   21934   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
   21935     u8 temp;
   21936     int rc;
   21937     rc = sqlite3VdbeMemMakeWriteable(pMem);
   21938     if( rc!=SQLITE_OK ){
   21939       assert( rc==SQLITE_NOMEM );
   21940       return SQLITE_NOMEM;
   21941     }
   21942     zIn = (u8*)pMem->z;
   21943     zTerm = &zIn[pMem->n&~1];
   21944     while( zIn<zTerm ){
   21945       temp = *zIn;
   21946       *zIn = *(zIn+1);
   21947       zIn++;
   21948       *zIn++ = temp;
   21949     }
   21950     pMem->enc = desiredEnc;
   21951     goto translate_out;
   21952   }
   21953 
   21954   /* Set len to the maximum number of bytes required in the output buffer. */
   21955   if( desiredEnc==SQLITE_UTF8 ){
   21956     /* When converting from UTF-16, the maximum growth results from
   21957     ** translating a 2-byte character to a 4-byte UTF-8 character.
   21958     ** A single byte is required for the output string
   21959     ** nul-terminator.
   21960     */
   21961     pMem->n &= ~1;
   21962     len = pMem->n * 2 + 1;
   21963   }else{
   21964     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
   21965     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
   21966     ** character. Two bytes are required in the output buffer for the
   21967     ** nul-terminator.
   21968     */
   21969     len = pMem->n * 2 + 2;
   21970   }
   21971 
   21972   /* Set zIn to point at the start of the input buffer and zTerm to point 1
   21973   ** byte past the end.
   21974   **
   21975   ** Variable zOut is set to point at the output buffer, space obtained
   21976   ** from sqlite3_malloc().
   21977   */
   21978   zIn = (u8*)pMem->z;
   21979   zTerm = &zIn[pMem->n];
   21980   zOut = sqlite3DbMallocRaw(pMem->db, len);
   21981   if( !zOut ){
   21982     return SQLITE_NOMEM;
   21983   }
   21984   z = zOut;
   21985 
   21986   if( pMem->enc==SQLITE_UTF8 ){
   21987     if( desiredEnc==SQLITE_UTF16LE ){
   21988       /* UTF-8 -> UTF-16 Little-endian */
   21989       while( zIn<zTerm ){
   21990         READ_UTF8(zIn, zTerm, c);
   21991         WRITE_UTF16LE(z, c);
   21992       }
   21993     }else{
   21994       assert( desiredEnc==SQLITE_UTF16BE );
   21995       /* UTF-8 -> UTF-16 Big-endian */
   21996       while( zIn<zTerm ){
   21997         READ_UTF8(zIn, zTerm, c);
   21998         WRITE_UTF16BE(z, c);
   21999       }
   22000     }
   22001     pMem->n = (int)(z - zOut);
   22002     *z++ = 0;
   22003   }else{
   22004     assert( desiredEnc==SQLITE_UTF8 );
   22005     if( pMem->enc==SQLITE_UTF16LE ){
   22006       /* UTF-16 Little-endian -> UTF-8 */
   22007       while( zIn<zTerm ){
   22008         READ_UTF16LE(zIn, zIn<zTerm, c);
   22009         WRITE_UTF8(z, c);
   22010       }
   22011     }else{
   22012       /* UTF-16 Big-endian -> UTF-8 */
   22013       while( zIn<zTerm ){
   22014         READ_UTF16BE(zIn, zIn<zTerm, c);
   22015         WRITE_UTF8(z, c);
   22016       }
   22017     }
   22018     pMem->n = (int)(z - zOut);
   22019   }
   22020   *z = 0;
   22021   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
   22022 
   22023   sqlite3VdbeMemRelease(pMem);
   22024   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
   22025   pMem->enc = desiredEnc;
   22026   pMem->flags |= (MEM_Term);
   22027   pMem->z = (char*)zOut;
   22028   pMem->zMalloc = pMem->z;
   22029 
   22030 translate_out:
   22031 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   22032   {
   22033     char zBuf[100];
   22034     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   22035     fprintf(stderr, "OUTPUT: %s\n", zBuf);
   22036   }
   22037 #endif
   22038   return SQLITE_OK;
   22039 }
   22040 
   22041 /*
   22042 ** This routine checks for a byte-order mark at the beginning of the
   22043 ** UTF-16 string stored in *pMem. If one is present, it is removed and
   22044 ** the encoding of the Mem adjusted. This routine does not do any
   22045 ** byte-swapping, it just sets Mem.enc appropriately.
   22046 **
   22047 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
   22048 ** changed by this function.
   22049 */
   22050 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
   22051   int rc = SQLITE_OK;
   22052   u8 bom = 0;
   22053 
   22054   assert( pMem->n>=0 );
   22055   if( pMem->n>1 ){
   22056     u8 b1 = *(u8 *)pMem->z;
   22057     u8 b2 = *(((u8 *)pMem->z) + 1);
   22058     if( b1==0xFE && b2==0xFF ){
   22059       bom = SQLITE_UTF16BE;
   22060     }
   22061     if( b1==0xFF && b2==0xFE ){
   22062       bom = SQLITE_UTF16LE;
   22063     }
   22064   }
   22065 
   22066   if( bom ){
   22067     rc = sqlite3VdbeMemMakeWriteable(pMem);
   22068     if( rc==SQLITE_OK ){
   22069       pMem->n -= 2;
   22070       memmove(pMem->z, &pMem->z[2], pMem->n);
   22071       pMem->z[pMem->n] = '\0';
   22072       pMem->z[pMem->n+1] = '\0';
   22073       pMem->flags |= MEM_Term;
   22074       pMem->enc = bom;
   22075     }
   22076   }
   22077   return rc;
   22078 }
   22079 #endif /* SQLITE_OMIT_UTF16 */
   22080 
   22081 /*
   22082 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
   22083 ** return the number of unicode characters in pZ up to (but not including)
   22084 ** the first 0x00 byte. If nByte is not less than zero, return the
   22085 ** number of unicode characters in the first nByte of pZ (or up to
   22086 ** the first 0x00, whichever comes first).
   22087 */
   22088 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
   22089   int r = 0;
   22090   const u8 *z = (const u8*)zIn;
   22091   const u8 *zTerm;
   22092   if( nByte>=0 ){
   22093     zTerm = &z[nByte];
   22094   }else{
   22095     zTerm = (const u8*)(-1);
   22096   }
   22097   assert( z<=zTerm );
   22098   while( *z!=0 && z<zTerm ){
   22099     SQLITE_SKIP_UTF8(z);
   22100     r++;
   22101   }
   22102   return r;
   22103 }
   22104 
   22105 /* This test function is not currently used by the automated test-suite.
   22106 ** Hence it is only available in debug builds.
   22107 */
   22108 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   22109 /*
   22110 ** Translate UTF-8 to UTF-8.
   22111 **
   22112 ** This has the effect of making sure that the string is well-formed
   22113 ** UTF-8.  Miscoded characters are removed.
   22114 **
   22115 ** The translation is done in-place and aborted if the output
   22116 ** overruns the input.
   22117 */
   22118 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
   22119   unsigned char *zOut = zIn;
   22120   unsigned char *zStart = zIn;
   22121   u32 c;
   22122 
   22123   while( zIn[0] && zOut<=zIn ){
   22124     c = sqlite3Utf8Read((const u8**)&zIn);
   22125     if( c!=0xfffd ){
   22126       WRITE_UTF8(zOut, c);
   22127     }
   22128   }
   22129   *zOut = 0;
   22130   return (int)(zOut - zStart);
   22131 }
   22132 #endif
   22133 
   22134 #ifndef SQLITE_OMIT_UTF16
   22135 /*
   22136 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
   22137 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
   22138 ** be freed by the calling function.
   22139 **
   22140 ** NULL is returned if there is an allocation error.
   22141 */
   22142 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
   22143   Mem m;
   22144   memset(&m, 0, sizeof(m));
   22145   m.db = db;
   22146   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
   22147   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
   22148   if( db->mallocFailed ){
   22149     sqlite3VdbeMemRelease(&m);
   22150     m.z = 0;
   22151   }
   22152   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
   22153   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
   22154   assert( m.z || db->mallocFailed );
   22155   return m.z;
   22156 }
   22157 
   22158 /*
   22159 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
   22160 ** Return the number of bytes in the first nChar unicode characters
   22161 ** in pZ.  nChar must be non-negative.
   22162 */
   22163 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
   22164   int c;
   22165   unsigned char const *z = zIn;
   22166   int n = 0;
   22167 
   22168   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
   22169     while( n<nChar ){
   22170       READ_UTF16BE(z, 1, c);
   22171       n++;
   22172     }
   22173   }else{
   22174     while( n<nChar ){
   22175       READ_UTF16LE(z, 1, c);
   22176       n++;
   22177     }
   22178   }
   22179   return (int)(z-(unsigned char const *)zIn);
   22180 }
   22181 
   22182 #if defined(SQLITE_TEST)
   22183 /*
   22184 ** This routine is called from the TCL test function "translate_selftest".
   22185 ** It checks that the primitives for serializing and deserializing
   22186 ** characters in each encoding are inverses of each other.
   22187 */
   22188 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
   22189   unsigned int i, t;
   22190   unsigned char zBuf[20];
   22191   unsigned char *z;
   22192   int n;
   22193   unsigned int c;
   22194 
   22195   for(i=0; i<0x00110000; i++){
   22196     z = zBuf;
   22197     WRITE_UTF8(z, i);
   22198     n = (int)(z-zBuf);
   22199     assert( n>0 && n<=4 );
   22200     z[0] = 0;
   22201     z = zBuf;
   22202     c = sqlite3Utf8Read((const u8**)&z);
   22203     t = i;
   22204     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
   22205     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
   22206     assert( c==t );
   22207     assert( (z-zBuf)==n );
   22208   }
   22209   for(i=0; i<0x00110000; i++){
   22210     if( i>=0xD800 && i<0xE000 ) continue;
   22211     z = zBuf;
   22212     WRITE_UTF16LE(z, i);
   22213     n = (int)(z-zBuf);
   22214     assert( n>0 && n<=4 );
   22215     z[0] = 0;
   22216     z = zBuf;
   22217     READ_UTF16LE(z, 1, c);
   22218     assert( c==i );
   22219     assert( (z-zBuf)==n );
   22220   }
   22221   for(i=0; i<0x00110000; i++){
   22222     if( i>=0xD800 && i<0xE000 ) continue;
   22223     z = zBuf;
   22224     WRITE_UTF16BE(z, i);
   22225     n = (int)(z-zBuf);
   22226     assert( n>0 && n<=4 );
   22227     z[0] = 0;
   22228     z = zBuf;
   22229     READ_UTF16BE(z, 1, c);
   22230     assert( c==i );
   22231     assert( (z-zBuf)==n );
   22232   }
   22233 }
   22234 #endif /* SQLITE_TEST */
   22235 #endif /* SQLITE_OMIT_UTF16 */
   22236 
   22237 /************** End of utf.c *************************************************/
   22238 /************** Begin file util.c ********************************************/
   22239 /*
   22240 ** 2001 September 15
   22241 **
   22242 ** The author disclaims copyright to this source code.  In place of
   22243 ** a legal notice, here is a blessing:
   22244 **
   22245 **    May you do good and not evil.
   22246 **    May you find forgiveness for yourself and forgive others.
   22247 **    May you share freely, never taking more than you give.
   22248 **
   22249 *************************************************************************
   22250 ** Utility functions used throughout sqlite.
   22251 **
   22252 ** This file contains functions for allocating memory, comparing
   22253 ** strings, and stuff like that.
   22254 **
   22255 */
   22256 /* #include <stdarg.h> */
   22257 #ifdef SQLITE_HAVE_ISNAN
   22258 # include <math.h>
   22259 #endif
   22260 
   22261 /*
   22262 ** Routine needed to support the testcase() macro.
   22263 */
   22264 #ifdef SQLITE_COVERAGE_TEST
   22265 SQLITE_PRIVATE void sqlite3Coverage(int x){
   22266   static unsigned dummy = 0;
   22267   dummy += (unsigned)x;
   22268 }
   22269 #endif
   22270 
   22271 /*
   22272 ** Give a callback to the test harness that can be used to simulate faults
   22273 ** in places where it is difficult or expensive to do so purely by means
   22274 ** of inputs.
   22275 **
   22276 ** The intent of the integer argument is to let the fault simulator know
   22277 ** which of multiple sqlite3FaultSim() calls has been hit.
   22278 **
   22279 ** Return whatever integer value the test callback returns, or return
   22280 ** SQLITE_OK if no test callback is installed.
   22281 */
   22282 #ifndef SQLITE_OMIT_BUILTIN_TEST
   22283 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
   22284   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
   22285   return xCallback ? xCallback(iTest) : SQLITE_OK;
   22286 }
   22287 #endif
   22288 
   22289 #ifndef SQLITE_OMIT_FLOATING_POINT
   22290 /*
   22291 ** Return true if the floating point value is Not a Number (NaN).
   22292 **
   22293 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
   22294 ** Otherwise, we have our own implementation that works on most systems.
   22295 */
   22296 SQLITE_PRIVATE int sqlite3IsNaN(double x){
   22297   int rc;   /* The value return */
   22298 #if !defined(SQLITE_HAVE_ISNAN)
   22299   /*
   22300   ** Systems that support the isnan() library function should probably
   22301   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
   22302   ** found that many systems do not have a working isnan() function so
   22303   ** this implementation is provided as an alternative.
   22304   **
   22305   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
   22306   ** On the other hand, the use of -ffast-math comes with the following
   22307   ** warning:
   22308   **
   22309   **      This option [-ffast-math] should never be turned on by any
   22310   **      -O option since it can result in incorrect output for programs
   22311   **      which depend on an exact implementation of IEEE or ISO
   22312   **      rules/specifications for math functions.
   22313   **
   22314   ** Under MSVC, this NaN test may fail if compiled with a floating-
   22315   ** point precision mode other than /fp:precise.  From the MSDN
   22316   ** documentation:
   22317   **
   22318   **      The compiler [with /fp:precise] will properly handle comparisons
   22319   **      involving NaN. For example, x != x evaluates to true if x is NaN
   22320   **      ...
   22321   */
   22322 #ifdef __FAST_MATH__
   22323 # error SQLite will not work correctly with the -ffast-math option of GCC.
   22324 #endif
   22325   volatile double y = x;
   22326   volatile double z = y;
   22327   rc = (y!=z);
   22328 #else  /* if defined(SQLITE_HAVE_ISNAN) */
   22329   rc = isnan(x);
   22330 #endif /* SQLITE_HAVE_ISNAN */
   22331   testcase( rc );
   22332   return rc;
   22333 }
   22334 #endif /* SQLITE_OMIT_FLOATING_POINT */
   22335 
   22336 /*
   22337 ** Compute a string length that is limited to what can be stored in
   22338 ** lower 30 bits of a 32-bit signed integer.
   22339 **
   22340 ** The value returned will never be negative.  Nor will it ever be greater
   22341 ** than the actual length of the string.  For very long strings (greater
   22342 ** than 1GiB) the value returned might be less than the true string length.
   22343 */
   22344 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
   22345   const char *z2 = z;
   22346   if( z==0 ) return 0;
   22347   while( *z2 ){ z2++; }
   22348   return 0x3fffffff & (int)(z2 - z);
   22349 }
   22350 
   22351 /*
   22352 ** Set the most recent error code and error string for the sqlite
   22353 ** handle "db". The error code is set to "err_code".
   22354 **
   22355 ** If it is not NULL, string zFormat specifies the format of the
   22356 ** error string in the style of the printf functions: The following
   22357 ** format characters are allowed:
   22358 **
   22359 **      %s      Insert a string
   22360 **      %z      A string that should be freed after use
   22361 **      %d      Insert an integer
   22362 **      %T      Insert a token
   22363 **      %S      Insert the first element of a SrcList
   22364 **
   22365 ** zFormat and any string tokens that follow it are assumed to be
   22366 ** encoded in UTF-8.
   22367 **
   22368 ** To clear the most recent error for sqlite handle "db", sqlite3Error
   22369 ** should be called with err_code set to SQLITE_OK and zFormat set
   22370 ** to NULL.
   22371 */
   22372 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
   22373   assert( db!=0 );
   22374   db->errCode = err_code;
   22375   if( zFormat && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
   22376     char *z;
   22377     va_list ap;
   22378     va_start(ap, zFormat);
   22379     z = sqlite3VMPrintf(db, zFormat, ap);
   22380     va_end(ap);
   22381     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
   22382   }else if( db->pErr ){
   22383     sqlite3ValueSetNull(db->pErr);
   22384   }
   22385 }
   22386 
   22387 /*
   22388 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
   22389 ** The following formatting characters are allowed:
   22390 **
   22391 **      %s      Insert a string
   22392 **      %z      A string that should be freed after use
   22393 **      %d      Insert an integer
   22394 **      %T      Insert a token
   22395 **      %S      Insert the first element of a SrcList
   22396 **
   22397 ** This function should be used to report any error that occurs whilst
   22398 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
   22399 ** last thing the sqlite3_prepare() function does is copy the error
   22400 ** stored by this function into the database handle using sqlite3Error().
   22401 ** Function sqlite3Error() should be used during statement execution
   22402 ** (sqlite3_step() etc.).
   22403 */
   22404 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
   22405   char *zMsg;
   22406   va_list ap;
   22407   sqlite3 *db = pParse->db;
   22408   va_start(ap, zFormat);
   22409   zMsg = sqlite3VMPrintf(db, zFormat, ap);
   22410   va_end(ap);
   22411   if( db->suppressErr ){
   22412     sqlite3DbFree(db, zMsg);
   22413   }else{
   22414     pParse->nErr++;
   22415     sqlite3DbFree(db, pParse->zErrMsg);
   22416     pParse->zErrMsg = zMsg;
   22417     pParse->rc = SQLITE_ERROR;
   22418   }
   22419 }
   22420 
   22421 /*
   22422 ** Convert an SQL-style quoted string into a normal string by removing
   22423 ** the quote characters.  The conversion is done in-place.  If the
   22424 ** input does not begin with a quote character, then this routine
   22425 ** is a no-op.
   22426 **
   22427 ** The input string must be zero-terminated.  A new zero-terminator
   22428 ** is added to the dequoted string.
   22429 **
   22430 ** The return value is -1 if no dequoting occurs or the length of the
   22431 ** dequoted string, exclusive of the zero terminator, if dequoting does
   22432 ** occur.
   22433 **
   22434 ** 2002-Feb-14: This routine is extended to remove MS-Access style
   22435 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
   22436 ** "a-b-c".
   22437 */
   22438 SQLITE_PRIVATE int sqlite3Dequote(char *z){
   22439   char quote;
   22440   int i, j;
   22441   if( z==0 ) return -1;
   22442   quote = z[0];
   22443   switch( quote ){
   22444     case '\'':  break;
   22445     case '"':   break;
   22446     case '`':   break;                /* For MySQL compatibility */
   22447     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
   22448     default:    return -1;
   22449   }
   22450   for(i=1, j=0;; i++){
   22451     assert( z[i] );
   22452     if( z[i]==quote ){
   22453       if( z[i+1]==quote ){
   22454         z[j++] = quote;
   22455         i++;
   22456       }else{
   22457         break;
   22458       }
   22459     }else{
   22460       z[j++] = z[i];
   22461     }
   22462   }
   22463   z[j] = 0;
   22464   return j;
   22465 }
   22466 
   22467 /* Convenient short-hand */
   22468 #define UpperToLower sqlite3UpperToLower
   22469 
   22470 /*
   22471 ** Some systems have stricmp().  Others have strcasecmp().  Because
   22472 ** there is no consistency, we will define our own.
   22473 **
   22474 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
   22475 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
   22476 ** the contents of two buffers containing UTF-8 strings in a
   22477 ** case-independent fashion, using the same definition of "case
   22478 ** independence" that SQLite uses internally when comparing identifiers.
   22479 */
   22480 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
   22481   register unsigned char *a, *b;
   22482   a = (unsigned char *)zLeft;
   22483   b = (unsigned char *)zRight;
   22484   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   22485   return UpperToLower[*a] - UpperToLower[*b];
   22486 }
   22487 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
   22488   register unsigned char *a, *b;
   22489   a = (unsigned char *)zLeft;
   22490   b = (unsigned char *)zRight;
   22491   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   22492   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
   22493 }
   22494 
   22495 /*
   22496 ** The string z[] is an text representation of a real number.
   22497 ** Convert this string to a double and write it into *pResult.
   22498 **
   22499 ** The string z[] is length bytes in length (bytes, not characters) and
   22500 ** uses the encoding enc.  The string is not necessarily zero-terminated.
   22501 **
   22502 ** Return TRUE if the result is a valid real number (or integer) and FALSE
   22503 ** if the string is empty or contains extraneous text.  Valid numbers
   22504 ** are in one of these formats:
   22505 **
   22506 **    [+-]digits[E[+-]digits]
   22507 **    [+-]digits.[digits][E[+-]digits]
   22508 **    [+-].digits[E[+-]digits]
   22509 **
   22510 ** Leading and trailing whitespace is ignored for the purpose of determining
   22511 ** validity.
   22512 **
   22513 ** If some prefix of the input string is a valid number, this routine
   22514 ** returns FALSE but it still converts the prefix and writes the result
   22515 ** into *pResult.
   22516 */
   22517 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
   22518 #ifndef SQLITE_OMIT_FLOATING_POINT
   22519   int incr;
   22520   const char *zEnd = z + length;
   22521   /* sign * significand * (10 ^ (esign * exponent)) */
   22522   int sign = 1;    /* sign of significand */
   22523   i64 s = 0;       /* significand */
   22524   int d = 0;       /* adjust exponent for shifting decimal point */
   22525   int esign = 1;   /* sign of exponent */
   22526   int e = 0;       /* exponent */
   22527   int eValid = 1;  /* True exponent is either not used or is well-formed */
   22528   double result;
   22529   int nDigits = 0;
   22530   int nonNum = 0;
   22531 
   22532   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   22533   *pResult = 0.0;   /* Default return value, in case of an error */
   22534 
   22535   if( enc==SQLITE_UTF8 ){
   22536     incr = 1;
   22537   }else{
   22538     int i;
   22539     incr = 2;
   22540     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   22541     for(i=3-enc; i<length && z[i]==0; i+=2){}
   22542     nonNum = i<length;
   22543     zEnd = z+i+enc-3;
   22544     z += (enc&1);
   22545   }
   22546 
   22547   /* skip leading spaces */
   22548   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
   22549   if( z>=zEnd ) return 0;
   22550 
   22551   /* get sign of significand */
   22552   if( *z=='-' ){
   22553     sign = -1;
   22554     z+=incr;
   22555   }else if( *z=='+' ){
   22556     z+=incr;
   22557   }
   22558 
   22559   /* skip leading zeroes */
   22560   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
   22561 
   22562   /* copy max significant digits to significand */
   22563   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   22564     s = s*10 + (*z - '0');
   22565     z+=incr, nDigits++;
   22566   }
   22567 
   22568   /* skip non-significant significand digits
   22569   ** (increase exponent by d to shift decimal left) */
   22570   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
   22571   if( z>=zEnd ) goto do_atof_calc;
   22572 
   22573   /* if decimal point is present */
   22574   if( *z=='.' ){
   22575     z+=incr;
   22576     /* copy digits from after decimal to significand
   22577     ** (decrease exponent by d to shift decimal right) */
   22578     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   22579       s = s*10 + (*z - '0');
   22580       z+=incr, nDigits++, d--;
   22581     }
   22582     /* skip non-significant digits */
   22583     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
   22584   }
   22585   if( z>=zEnd ) goto do_atof_calc;
   22586 
   22587   /* if exponent is present */
   22588   if( *z=='e' || *z=='E' ){
   22589     z+=incr;
   22590     eValid = 0;
   22591     if( z>=zEnd ) goto do_atof_calc;
   22592     /* get sign of exponent */
   22593     if( *z=='-' ){
   22594       esign = -1;
   22595       z+=incr;
   22596     }else if( *z=='+' ){
   22597       z+=incr;
   22598     }
   22599     /* copy digits to exponent */
   22600     while( z<zEnd && sqlite3Isdigit(*z) ){
   22601       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
   22602       z+=incr;
   22603       eValid = 1;
   22604     }
   22605   }
   22606 
   22607   /* skip trailing spaces */
   22608   if( nDigits && eValid ){
   22609     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
   22610   }
   22611 
   22612 do_atof_calc:
   22613   /* adjust exponent by d, and update sign */
   22614   e = (e*esign) + d;
   22615   if( e<0 ) {
   22616     esign = -1;
   22617     e *= -1;
   22618   } else {
   22619     esign = 1;
   22620   }
   22621 
   22622   /* if 0 significand */
   22623   if( !s ) {
   22624     /* In the IEEE 754 standard, zero is signed.
   22625     ** Add the sign if we've seen at least one digit */
   22626     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
   22627   } else {
   22628     /* attempt to reduce exponent */
   22629     if( esign>0 ){
   22630       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
   22631     }else{
   22632       while( !(s%10) && e>0 ) e--,s/=10;
   22633     }
   22634 
   22635     /* adjust the sign of significand */
   22636     s = sign<0 ? -s : s;
   22637 
   22638     /* if exponent, scale significand as appropriate
   22639     ** and store in result. */
   22640     if( e ){
   22641       LONGDOUBLE_TYPE scale = 1.0;
   22642       /* attempt to handle extremely small/large numbers better */
   22643       if( e>307 && e<342 ){
   22644         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
   22645         if( esign<0 ){
   22646           result = s / scale;
   22647           result /= 1.0e+308;
   22648         }else{
   22649           result = s * scale;
   22650           result *= 1.0e+308;
   22651         }
   22652       }else if( e>=342 ){
   22653         if( esign<0 ){
   22654           result = 0.0*s;
   22655         }else{
   22656           result = 1e308*1e308*s;  /* Infinity */
   22657         }
   22658       }else{
   22659         /* 1.0e+22 is the largest power of 10 than can be
   22660         ** represented exactly. */
   22661         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
   22662         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
   22663         if( esign<0 ){
   22664           result = s / scale;
   22665         }else{
   22666           result = s * scale;
   22667         }
   22668       }
   22669     } else {
   22670       result = (double)s;
   22671     }
   22672   }
   22673 
   22674   /* store the result */
   22675   *pResult = result;
   22676 
   22677   /* return true if number and no extra non-whitespace chracters after */
   22678   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
   22679 #else
   22680   return !sqlite3Atoi64(z, pResult, length, enc);
   22681 #endif /* SQLITE_OMIT_FLOATING_POINT */
   22682 }
   22683 
   22684 /*
   22685 ** Compare the 19-character string zNum against the text representation
   22686 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
   22687 ** if zNum is less than, equal to, or greater than the string.
   22688 ** Note that zNum must contain exactly 19 characters.
   22689 **
   22690 ** Unlike memcmp() this routine is guaranteed to return the difference
   22691 ** in the values of the last digit if the only difference is in the
   22692 ** last digit.  So, for example,
   22693 **
   22694 **      compare2pow63("9223372036854775800", 1)
   22695 **
   22696 ** will return -8.
   22697 */
   22698 static int compare2pow63(const char *zNum, int incr){
   22699   int c = 0;
   22700   int i;
   22701                     /* 012345678901234567 */
   22702   const char *pow63 = "922337203685477580";
   22703   for(i=0; c==0 && i<18; i++){
   22704     c = (zNum[i*incr]-pow63[i])*10;
   22705   }
   22706   if( c==0 ){
   22707     c = zNum[18*incr] - '8';
   22708     testcase( c==(-1) );
   22709     testcase( c==0 );
   22710     testcase( c==(+1) );
   22711   }
   22712   return c;
   22713 }
   22714 
   22715 /*
   22716 ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
   22717 ** routine does *not* accept hexadecimal notation.
   22718 **
   22719 ** If the zNum value is representable as a 64-bit twos-complement
   22720 ** integer, then write that value into *pNum and return 0.
   22721 **
   22722 ** If zNum is exactly 9223372036854775808, return 2.  This special
   22723 ** case is broken out because while 9223372036854775808 cannot be a
   22724 ** signed 64-bit integer, its negative -9223372036854775808 can be.
   22725 **
   22726 ** If zNum is too big for a 64-bit integer and is not
   22727 ** 9223372036854775808  or if zNum contains any non-numeric text,
   22728 ** then return 1.
   22729 **
   22730 ** length is the number of bytes in the string (bytes, not characters).
   22731 ** The string is not necessarily zero-terminated.  The encoding is
   22732 ** given by enc.
   22733 */
   22734 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
   22735   int incr;
   22736   u64 u = 0;
   22737   int neg = 0; /* assume positive */
   22738   int i;
   22739   int c = 0;
   22740   int nonNum = 0;
   22741   const char *zStart;
   22742   const char *zEnd = zNum + length;
   22743   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   22744   if( enc==SQLITE_UTF8 ){
   22745     incr = 1;
   22746   }else{
   22747     incr = 2;
   22748     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   22749     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
   22750     nonNum = i<length;
   22751     zEnd = zNum+i+enc-3;
   22752     zNum += (enc&1);
   22753   }
   22754   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
   22755   if( zNum<zEnd ){
   22756     if( *zNum=='-' ){
   22757       neg = 1;
   22758       zNum+=incr;
   22759     }else if( *zNum=='+' ){
   22760       zNum+=incr;
   22761     }
   22762   }
   22763   zStart = zNum;
   22764   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
   22765   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
   22766     u = u*10 + c - '0';
   22767   }
   22768   if( u>LARGEST_INT64 ){
   22769     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
   22770   }else if( neg ){
   22771     *pNum = -(i64)u;
   22772   }else{
   22773     *pNum = (i64)u;
   22774   }
   22775   testcase( i==18 );
   22776   testcase( i==19 );
   22777   testcase( i==20 );
   22778   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
   22779     /* zNum is empty or contains non-numeric text or is longer
   22780     ** than 19 digits (thus guaranteeing that it is too large) */
   22781     return 1;
   22782   }else if( i<19*incr ){
   22783     /* Less than 19 digits, so we know that it fits in 64 bits */
   22784     assert( u<=LARGEST_INT64 );
   22785     return 0;
   22786   }else{
   22787     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
   22788     c = compare2pow63(zNum, incr);
   22789     if( c<0 ){
   22790       /* zNum is less than 9223372036854775808 so it fits */
   22791       assert( u<=LARGEST_INT64 );
   22792       return 0;
   22793     }else if( c>0 ){
   22794       /* zNum is greater than 9223372036854775808 so it overflows */
   22795       return 1;
   22796     }else{
   22797       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
   22798       ** special case 2 overflow if positive */
   22799       assert( u-1==LARGEST_INT64 );
   22800       return neg ? 0 : 2;
   22801     }
   22802   }
   22803 }
   22804 
   22805 /*
   22806 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
   22807 ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
   22808 ** whereas sqlite3Atoi64() does not.
   22809 **
   22810 ** Returns:
   22811 **
   22812 **     0    Successful transformation.  Fits in a 64-bit signed integer.
   22813 **     1    Integer too large for a 64-bit signed integer or is malformed
   22814 **     2    Special case of 9223372036854775808
   22815 */
   22816 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
   22817 #ifndef SQLITE_OMIT_HEX_INTEGER
   22818   if( z[0]=='0'
   22819    && (z[1]=='x' || z[1]=='X')
   22820    && sqlite3Isxdigit(z[2])
   22821   ){
   22822     u64 u = 0;
   22823     int i, k;
   22824     for(i=2; z[i]=='0'; i++){}
   22825     for(k=i; sqlite3Isxdigit(z[k]); k++){
   22826       u = u*16 + sqlite3HexToInt(z[k]);
   22827     }
   22828     memcpy(pOut, &u, 8);
   22829     return (z[k]==0 && k-i<=16) ? 0 : 1;
   22830   }else
   22831 #endif /* SQLITE_OMIT_HEX_INTEGER */
   22832   {
   22833     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
   22834   }
   22835 }
   22836 
   22837 /*
   22838 ** If zNum represents an integer that will fit in 32-bits, then set
   22839 ** *pValue to that integer and return true.  Otherwise return false.
   22840 **
   22841 ** This routine accepts both decimal and hexadecimal notation for integers.
   22842 **
   22843 ** Any non-numeric characters that following zNum are ignored.
   22844 ** This is different from sqlite3Atoi64() which requires the
   22845 ** input number to be zero-terminated.
   22846 */
   22847 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
   22848   sqlite_int64 v = 0;
   22849   int i, c;
   22850   int neg = 0;
   22851   if( zNum[0]=='-' ){
   22852     neg = 1;
   22853     zNum++;
   22854   }else if( zNum[0]=='+' ){
   22855     zNum++;
   22856   }
   22857 #ifndef SQLITE_OMIT_HEX_INTEGER
   22858   else if( zNum[0]=='0'
   22859         && (zNum[1]=='x' || zNum[1]=='X')
   22860         && sqlite3Isxdigit(zNum[2])
   22861   ){
   22862     u32 u = 0;
   22863     zNum += 2;
   22864     while( zNum[0]=='0' ) zNum++;
   22865     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
   22866       u = u*16 + sqlite3HexToInt(zNum[i]);
   22867     }
   22868     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
   22869       memcpy(pValue, &u, 4);
   22870       return 1;
   22871     }else{
   22872       return 0;
   22873     }
   22874   }
   22875 #endif
   22876   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
   22877     v = v*10 + c;
   22878   }
   22879 
   22880   /* The longest decimal representation of a 32 bit integer is 10 digits:
   22881   **
   22882   **             1234567890
   22883   **     2^31 -> 2147483648
   22884   */
   22885   testcase( i==10 );
   22886   if( i>10 ){
   22887     return 0;
   22888   }
   22889   testcase( v-neg==2147483647 );
   22890   if( v-neg>2147483647 ){
   22891     return 0;
   22892   }
   22893   if( neg ){
   22894     v = -v;
   22895   }
   22896   *pValue = (int)v;
   22897   return 1;
   22898 }
   22899 
   22900 /*
   22901 ** Return a 32-bit integer value extracted from a string.  If the
   22902 ** string is not an integer, just return 0.
   22903 */
   22904 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
   22905   int x = 0;
   22906   if( z ) sqlite3GetInt32(z, &x);
   22907   return x;
   22908 }
   22909 
   22910 /*
   22911 ** The variable-length integer encoding is as follows:
   22912 **
   22913 ** KEY:
   22914 **         A = 0xxxxxxx    7 bits of data and one flag bit
   22915 **         B = 1xxxxxxx    7 bits of data and one flag bit
   22916 **         C = xxxxxxxx    8 bits of data
   22917 **
   22918 **  7 bits - A
   22919 ** 14 bits - BA
   22920 ** 21 bits - BBA
   22921 ** 28 bits - BBBA
   22922 ** 35 bits - BBBBA
   22923 ** 42 bits - BBBBBA
   22924 ** 49 bits - BBBBBBA
   22925 ** 56 bits - BBBBBBBA
   22926 ** 64 bits - BBBBBBBBC
   22927 */
   22928 
   22929 /*
   22930 ** Write a 64-bit variable-length integer to memory starting at p[0].
   22931 ** The length of data write will be between 1 and 9 bytes.  The number
   22932 ** of bytes written is returned.
   22933 **
   22934 ** A variable-length integer consists of the lower 7 bits of each byte
   22935 ** for all bytes that have the 8th bit set and one byte with the 8th
   22936 ** bit clear.  Except, if we get to the 9th byte, it stores the full
   22937 ** 8 bits and is the last byte.
   22938 */
   22939 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
   22940   int i, j, n;
   22941   u8 buf[10];
   22942   if( v & (((u64)0xff000000)<<32) ){
   22943     p[8] = (u8)v;
   22944     v >>= 8;
   22945     for(i=7; i>=0; i--){
   22946       p[i] = (u8)((v & 0x7f) | 0x80);
   22947       v >>= 7;
   22948     }
   22949     return 9;
   22950   }
   22951   n = 0;
   22952   do{
   22953     buf[n++] = (u8)((v & 0x7f) | 0x80);
   22954     v >>= 7;
   22955   }while( v!=0 );
   22956   buf[0] &= 0x7f;
   22957   assert( n<=9 );
   22958   for(i=0, j=n-1; j>=0; j--, i++){
   22959     p[i] = buf[j];
   22960   }
   22961   return n;
   22962 }
   22963 
   22964 /*
   22965 ** This routine is a faster version of sqlite3PutVarint() that only
   22966 ** works for 32-bit positive integers and which is optimized for
   22967 ** the common case of small integers.  A MACRO version, putVarint32,
   22968 ** is provided which inlines the single-byte case.  All code should use
   22969 ** the MACRO version as this function assumes the single-byte case has
   22970 ** already been handled.
   22971 */
   22972 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
   22973 #ifndef putVarint32
   22974   if( (v & ~0x7f)==0 ){
   22975     p[0] = v;
   22976     return 1;
   22977   }
   22978 #endif
   22979   if( (v & ~0x3fff)==0 ){
   22980     p[0] = (u8)((v>>7) | 0x80);
   22981     p[1] = (u8)(v & 0x7f);
   22982     return 2;
   22983   }
   22984   return sqlite3PutVarint(p, v);
   22985 }
   22986 
   22987 /*
   22988 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
   22989 ** are defined here rather than simply putting the constant expressions
   22990 ** inline in order to work around bugs in the RVT compiler.
   22991 **
   22992 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
   22993 **
   22994 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
   22995 */
   22996 #define SLOT_2_0     0x001fc07f
   22997 #define SLOT_4_2_0   0xf01fc07f
   22998 
   22999 
   23000 /*
   23001 ** Read a 64-bit variable-length integer from memory starting at p[0].
   23002 ** Return the number of bytes read.  The value is stored in *v.
   23003 */
   23004 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
   23005   u32 a,b,s;
   23006 
   23007   a = *p;
   23008   /* a: p0 (unmasked) */
   23009   if (!(a&0x80))
   23010   {
   23011     *v = a;
   23012     return 1;
   23013   }
   23014 
   23015   p++;
   23016   b = *p;
   23017   /* b: p1 (unmasked) */
   23018   if (!(b&0x80))
   23019   {
   23020     a &= 0x7f;
   23021     a = a<<7;
   23022     a |= b;
   23023     *v = a;
   23024     return 2;
   23025   }
   23026 
   23027   /* Verify that constants are precomputed correctly */
   23028   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
   23029   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
   23030 
   23031   p++;
   23032   a = a<<14;
   23033   a |= *p;
   23034   /* a: p0<<14 | p2 (unmasked) */
   23035   if (!(a&0x80))
   23036   {
   23037     a &= SLOT_2_0;
   23038     b &= 0x7f;
   23039     b = b<<7;
   23040     a |= b;
   23041     *v = a;
   23042     return 3;
   23043   }
   23044 
   23045   /* CSE1 from below */
   23046   a &= SLOT_2_0;
   23047   p++;
   23048   b = b<<14;
   23049   b |= *p;
   23050   /* b: p1<<14 | p3 (unmasked) */
   23051   if (!(b&0x80))
   23052   {
   23053     b &= SLOT_2_0;
   23054     /* moved CSE1 up */
   23055     /* a &= (0x7f<<14)|(0x7f); */
   23056     a = a<<7;
   23057     a |= b;
   23058     *v = a;
   23059     return 4;
   23060   }
   23061 
   23062   /* a: p0<<14 | p2 (masked) */
   23063   /* b: p1<<14 | p3 (unmasked) */
   23064   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   23065   /* moved CSE1 up */
   23066   /* a &= (0x7f<<14)|(0x7f); */
   23067   b &= SLOT_2_0;
   23068   s = a;
   23069   /* s: p0<<14 | p2 (masked) */
   23070 
   23071   p++;
   23072   a = a<<14;
   23073   a |= *p;
   23074   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   23075   if (!(a&0x80))
   23076   {
   23077     /* we can skip these cause they were (effectively) done above in calc'ing s */
   23078     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   23079     /* b &= (0x7f<<14)|(0x7f); */
   23080     b = b<<7;
   23081     a |= b;
   23082     s = s>>18;
   23083     *v = ((u64)s)<<32 | a;
   23084     return 5;
   23085   }
   23086 
   23087   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   23088   s = s<<7;
   23089   s |= b;
   23090   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   23091 
   23092   p++;
   23093   b = b<<14;
   23094   b |= *p;
   23095   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
   23096   if (!(b&0x80))
   23097   {
   23098     /* we can skip this cause it was (effectively) done above in calc'ing s */
   23099     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   23100     a &= SLOT_2_0;
   23101     a = a<<7;
   23102     a |= b;
   23103     s = s>>18;
   23104     *v = ((u64)s)<<32 | a;
   23105     return 6;
   23106   }
   23107 
   23108   p++;
   23109   a = a<<14;
   23110   a |= *p;
   23111   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
   23112   if (!(a&0x80))
   23113   {
   23114     a &= SLOT_4_2_0;
   23115     b &= SLOT_2_0;
   23116     b = b<<7;
   23117     a |= b;
   23118     s = s>>11;
   23119     *v = ((u64)s)<<32 | a;
   23120     return 7;
   23121   }
   23122 
   23123   /* CSE2 from below */
   23124   a &= SLOT_2_0;
   23125   p++;
   23126   b = b<<14;
   23127   b |= *p;
   23128   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
   23129   if (!(b&0x80))
   23130   {
   23131     b &= SLOT_4_2_0;
   23132     /* moved CSE2 up */
   23133     /* a &= (0x7f<<14)|(0x7f); */
   23134     a = a<<7;
   23135     a |= b;
   23136     s = s>>4;
   23137     *v = ((u64)s)<<32 | a;
   23138     return 8;
   23139   }
   23140 
   23141   p++;
   23142   a = a<<15;
   23143   a |= *p;
   23144   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
   23145 
   23146   /* moved CSE2 up */
   23147   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
   23148   b &= SLOT_2_0;
   23149   b = b<<8;
   23150   a |= b;
   23151 
   23152   s = s<<4;
   23153   b = p[-4];
   23154   b &= 0x7f;
   23155   b = b>>3;
   23156   s |= b;
   23157 
   23158   *v = ((u64)s)<<32 | a;
   23159 
   23160   return 9;
   23161 }
   23162 
   23163 /*
   23164 ** Read a 32-bit variable-length integer from memory starting at p[0].
   23165 ** Return the number of bytes read.  The value is stored in *v.
   23166 **
   23167 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
   23168 ** integer, then set *v to 0xffffffff.
   23169 **
   23170 ** A MACRO version, getVarint32, is provided which inlines the
   23171 ** single-byte case.  All code should use the MACRO version as
   23172 ** this function assumes the single-byte case has already been handled.
   23173 */
   23174 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
   23175   u32 a,b;
   23176 
   23177   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
   23178   ** by the getVarin32() macro */
   23179   a = *p;
   23180   /* a: p0 (unmasked) */
   23181 #ifndef getVarint32
   23182   if (!(a&0x80))
   23183   {
   23184     /* Values between 0 and 127 */
   23185     *v = a;
   23186     return 1;
   23187   }
   23188 #endif
   23189 
   23190   /* The 2-byte case */
   23191   p++;
   23192   b = *p;
   23193   /* b: p1 (unmasked) */
   23194   if (!(b&0x80))
   23195   {
   23196     /* Values between 128 and 16383 */
   23197     a &= 0x7f;
   23198     a = a<<7;
   23199     *v = a | b;
   23200     return 2;
   23201   }
   23202 
   23203   /* The 3-byte case */
   23204   p++;
   23205   a = a<<14;
   23206   a |= *p;
   23207   /* a: p0<<14 | p2 (unmasked) */
   23208   if (!(a&0x80))
   23209   {
   23210     /* Values between 16384 and 2097151 */
   23211     a &= (0x7f<<14)|(0x7f);
   23212     b &= 0x7f;
   23213     b = b<<7;
   23214     *v = a | b;
   23215     return 3;
   23216   }
   23217 
   23218   /* A 32-bit varint is used to store size information in btrees.
   23219   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
   23220   ** A 3-byte varint is sufficient, for example, to record the size
   23221   ** of a 1048569-byte BLOB or string.
   23222   **
   23223   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
   23224   ** rare larger cases can be handled by the slower 64-bit varint
   23225   ** routine.
   23226   */
   23227 #if 1
   23228   {
   23229     u64 v64;
   23230     u8 n;
   23231 
   23232     p -= 2;
   23233     n = sqlite3GetVarint(p, &v64);
   23234     assert( n>3 && n<=9 );
   23235     if( (v64 & SQLITE_MAX_U32)!=v64 ){
   23236       *v = 0xffffffff;
   23237     }else{
   23238       *v = (u32)v64;
   23239     }
   23240     return n;
   23241   }
   23242 
   23243 #else
   23244   /* For following code (kept for historical record only) shows an
   23245   ** unrolling for the 3- and 4-byte varint cases.  This code is
   23246   ** slightly faster, but it is also larger and much harder to test.
   23247   */
   23248   p++;
   23249   b = b<<14;
   23250   b |= *p;
   23251   /* b: p1<<14 | p3 (unmasked) */
   23252   if (!(b&0x80))
   23253   {
   23254     /* Values between 2097152 and 268435455 */
   23255     b &= (0x7f<<14)|(0x7f);
   23256     a &= (0x7f<<14)|(0x7f);
   23257     a = a<<7;
   23258     *v = a | b;
   23259     return 4;
   23260   }
   23261 
   23262   p++;
   23263   a = a<<14;
   23264   a |= *p;
   23265   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   23266   if (!(a&0x80))
   23267   {
   23268     /* Values  between 268435456 and 34359738367 */
   23269     a &= SLOT_4_2_0;
   23270     b &= SLOT_4_2_0;
   23271     b = b<<7;
   23272     *v = a | b;
   23273     return 5;
   23274   }
   23275 
   23276   /* We can only reach this point when reading a corrupt database
   23277   ** file.  In that case we are not in any hurry.  Use the (relatively
   23278   ** slow) general-purpose sqlite3GetVarint() routine to extract the
   23279   ** value. */
   23280   {
   23281     u64 v64;
   23282     u8 n;
   23283 
   23284     p -= 4;
   23285     n = sqlite3GetVarint(p, &v64);
   23286     assert( n>5 && n<=9 );
   23287     *v = (u32)v64;
   23288     return n;
   23289   }
   23290 #endif
   23291 }
   23292 
   23293 /*
   23294 ** Return the number of bytes that will be needed to store the given
   23295 ** 64-bit integer.
   23296 */
   23297 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
   23298   int i = 0;
   23299   do{
   23300     i++;
   23301     v >>= 7;
   23302   }while( v!=0 && ALWAYS(i<9) );
   23303   return i;
   23304 }
   23305 
   23306 
   23307 /*
   23308 ** Read or write a four-byte big-endian integer value.
   23309 */
   23310 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
   23311   testcase( p[0]&0x80 );
   23312   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
   23313 }
   23314 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
   23315   p[0] = (u8)(v>>24);
   23316   p[1] = (u8)(v>>16);
   23317   p[2] = (u8)(v>>8);
   23318   p[3] = (u8)v;
   23319 }
   23320 
   23321 
   23322 
   23323 /*
   23324 ** Translate a single byte of Hex into an integer.
   23325 ** This routine only works if h really is a valid hexadecimal
   23326 ** character:  0..9a..fA..F
   23327 */
   23328 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
   23329   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
   23330 #ifdef SQLITE_ASCII
   23331   h += 9*(1&(h>>6));
   23332 #endif
   23333 #ifdef SQLITE_EBCDIC
   23334   h += 9*(1&~(h>>4));
   23335 #endif
   23336   return (u8)(h & 0xf);
   23337 }
   23338 
   23339 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
   23340 /*
   23341 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
   23342 ** value.  Return a pointer to its binary value.  Space to hold the
   23343 ** binary value has been obtained from malloc and must be freed by
   23344 ** the calling routine.
   23345 */
   23346 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
   23347   char *zBlob;
   23348   int i;
   23349 
   23350   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
   23351   n--;
   23352   if( zBlob ){
   23353     for(i=0; i<n; i+=2){
   23354       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
   23355     }
   23356     zBlob[i/2] = 0;
   23357   }
   23358   return zBlob;
   23359 }
   23360 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
   23361 
   23362 /*
   23363 ** Log an error that is an API call on a connection pointer that should
   23364 ** not have been used.  The "type" of connection pointer is given as the
   23365 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
   23366 */
   23367 static void logBadConnection(const char *zType){
   23368   sqlite3_log(SQLITE_MISUSE,
   23369      "API call with %s database connection pointer",
   23370      zType
   23371   );
   23372 }
   23373 
   23374 /*
   23375 ** Check to make sure we have a valid db pointer.  This test is not
   23376 ** foolproof but it does provide some measure of protection against
   23377 ** misuse of the interface such as passing in db pointers that are
   23378 ** NULL or which have been previously closed.  If this routine returns
   23379 ** 1 it means that the db pointer is valid and 0 if it should not be
   23380 ** dereferenced for any reason.  The calling function should invoke
   23381 ** SQLITE_MISUSE immediately.
   23382 **
   23383 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
   23384 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
   23385 ** open properly and is not fit for general use but which can be
   23386 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
   23387 */
   23388 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
   23389   u32 magic;
   23390   if( db==0 ){
   23391     logBadConnection("NULL");
   23392     return 0;
   23393   }
   23394   magic = db->magic;
   23395   if( magic!=SQLITE_MAGIC_OPEN ){
   23396     if( sqlite3SafetyCheckSickOrOk(db) ){
   23397       testcase( sqlite3GlobalConfig.xLog!=0 );
   23398       logBadConnection("unopened");
   23399     }
   23400     return 0;
   23401   }else{
   23402     return 1;
   23403   }
   23404 }
   23405 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
   23406   u32 magic;
   23407   magic = db->magic;
   23408   if( magic!=SQLITE_MAGIC_SICK &&
   23409       magic!=SQLITE_MAGIC_OPEN &&
   23410       magic!=SQLITE_MAGIC_BUSY ){
   23411     testcase( sqlite3GlobalConfig.xLog!=0 );
   23412     logBadConnection("invalid");
   23413     return 0;
   23414   }else{
   23415     return 1;
   23416   }
   23417 }
   23418 
   23419 /*
   23420 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
   23421 ** the other 64-bit signed integer at *pA and store the result in *pA.
   23422 ** Return 0 on success.  Or if the operation would have resulted in an
   23423 ** overflow, leave *pA unchanged and return 1.
   23424 */
   23425 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
   23426   i64 iA = *pA;
   23427   testcase( iA==0 ); testcase( iA==1 );
   23428   testcase( iB==-1 ); testcase( iB==0 );
   23429   if( iB>=0 ){
   23430     testcase( iA>0 && LARGEST_INT64 - iA == iB );
   23431     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
   23432     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
   23433   }else{
   23434     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
   23435     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
   23436     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
   23437   }
   23438   *pA += iB;
   23439   return 0;
   23440 }
   23441 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
   23442   testcase( iB==SMALLEST_INT64+1 );
   23443   if( iB==SMALLEST_INT64 ){
   23444     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
   23445     if( (*pA)>=0 ) return 1;
   23446     *pA -= iB;
   23447     return 0;
   23448   }else{
   23449     return sqlite3AddInt64(pA, -iB);
   23450   }
   23451 }
   23452 #define TWOPOWER32 (((i64)1)<<32)
   23453 #define TWOPOWER31 (((i64)1)<<31)
   23454 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
   23455   i64 iA = *pA;
   23456   i64 iA1, iA0, iB1, iB0, r;
   23457 
   23458   iA1 = iA/TWOPOWER32;
   23459   iA0 = iA % TWOPOWER32;
   23460   iB1 = iB/TWOPOWER32;
   23461   iB0 = iB % TWOPOWER32;
   23462   if( iA1==0 ){
   23463     if( iB1==0 ){
   23464       *pA *= iB;
   23465       return 0;
   23466     }
   23467     r = iA0*iB1;
   23468   }else if( iB1==0 ){
   23469     r = iA1*iB0;
   23470   }else{
   23471     /* If both iA1 and iB1 are non-zero, overflow will result */
   23472     return 1;
   23473   }
   23474   testcase( r==(-TWOPOWER31)-1 );
   23475   testcase( r==(-TWOPOWER31) );
   23476   testcase( r==TWOPOWER31 );
   23477   testcase( r==TWOPOWER31-1 );
   23478   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
   23479   r *= TWOPOWER32;
   23480   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
   23481   *pA = r;
   23482   return 0;
   23483 }
   23484 
   23485 /*
   23486 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
   23487 ** if the integer has a value of -2147483648, return +2147483647
   23488 */
   23489 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
   23490   if( x>=0 ) return x;
   23491   if( x==(int)0x80000000 ) return 0x7fffffff;
   23492   return -x;
   23493 }
   23494 
   23495 #ifdef SQLITE_ENABLE_8_3_NAMES
   23496 /*
   23497 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
   23498 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
   23499 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
   23500 ** three characters, then shorten the suffix on z[] to be the last three
   23501 ** characters of the original suffix.
   23502 **
   23503 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
   23504 ** do the suffix shortening regardless of URI parameter.
   23505 **
   23506 ** Examples:
   23507 **
   23508 **     test.db-journal    =>   test.nal
   23509 **     test.db-wal        =>   test.wal
   23510 **     test.db-shm        =>   test.shm
   23511 **     test.db-mj7f3319fa =>   test.9fa
   23512 */
   23513 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
   23514 #if SQLITE_ENABLE_8_3_NAMES<2
   23515   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
   23516 #endif
   23517   {
   23518     int i, sz;
   23519     sz = sqlite3Strlen30(z);
   23520     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
   23521     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
   23522   }
   23523 }
   23524 #endif
   23525 
   23526 /*
   23527 ** Find (an approximate) sum of two LogEst values.  This computation is
   23528 ** not a simple "+" operator because LogEst is stored as a logarithmic
   23529 ** value.
   23530 **
   23531 */
   23532 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
   23533   static const unsigned char x[] = {
   23534      10, 10,                         /* 0,1 */
   23535       9, 9,                          /* 2,3 */
   23536       8, 8,                          /* 4,5 */
   23537       7, 7, 7,                       /* 6,7,8 */
   23538       6, 6, 6,                       /* 9,10,11 */
   23539       5, 5, 5,                       /* 12-14 */
   23540       4, 4, 4, 4,                    /* 15-18 */
   23541       3, 3, 3, 3, 3, 3,              /* 19-24 */
   23542       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
   23543   };
   23544   if( a>=b ){
   23545     if( a>b+49 ) return a;
   23546     if( a>b+31 ) return a+1;
   23547     return a+x[a-b];
   23548   }else{
   23549     if( b>a+49 ) return b;
   23550     if( b>a+31 ) return b+1;
   23551     return b+x[b-a];
   23552   }
   23553 }
   23554 
   23555 /*
   23556 ** Convert an integer into a LogEst.  In other words, compute an
   23557 ** approximation for 10*log2(x).
   23558 */
   23559 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
   23560   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
   23561   LogEst y = 40;
   23562   if( x<8 ){
   23563     if( x<2 ) return 0;
   23564     while( x<8 ){  y -= 10; x <<= 1; }
   23565   }else{
   23566     while( x>255 ){ y += 40; x >>= 4; }
   23567     while( x>15 ){  y += 10; x >>= 1; }
   23568   }
   23569   return a[x&7] + y - 10;
   23570 }
   23571 
   23572 #ifndef SQLITE_OMIT_VIRTUALTABLE
   23573 /*
   23574 ** Convert a double into a LogEst
   23575 ** In other words, compute an approximation for 10*log2(x).
   23576 */
   23577 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
   23578   u64 a;
   23579   LogEst e;
   23580   assert( sizeof(x)==8 && sizeof(a)==8 );
   23581   if( x<=1 ) return 0;
   23582   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
   23583   memcpy(&a, &x, 8);
   23584   e = (a>>52) - 1022;
   23585   return e*10;
   23586 }
   23587 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   23588 
   23589 /*
   23590 ** Convert a LogEst into an integer.
   23591 */
   23592 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
   23593   u64 n;
   23594   if( x<10 ) return 1;
   23595   n = x%10;
   23596   x /= 10;
   23597   if( n>=5 ) n -= 2;
   23598   else if( n>=1 ) n -= 1;
   23599   if( x>=3 ){
   23600     return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
   23601   }
   23602   return (n+8)>>(3-x);
   23603 }
   23604 
   23605 /************** End of util.c ************************************************/
   23606 /************** Begin file hash.c ********************************************/
   23607 /*
   23608 ** 2001 September 22
   23609 **
   23610 ** The author disclaims copyright to this source code.  In place of
   23611 ** a legal notice, here is a blessing:
   23612 **
   23613 **    May you do good and not evil.
   23614 **    May you find forgiveness for yourself and forgive others.
   23615 **    May you share freely, never taking more than you give.
   23616 **
   23617 *************************************************************************
   23618 ** This is the implementation of generic hash-tables
   23619 ** used in SQLite.
   23620 */
   23621 /* #include <assert.h> */
   23622 
   23623 /* Turn bulk memory into a hash table object by initializing the
   23624 ** fields of the Hash structure.
   23625 **
   23626 ** "pNew" is a pointer to the hash table that is to be initialized.
   23627 */
   23628 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
   23629   assert( pNew!=0 );
   23630   pNew->first = 0;
   23631   pNew->count = 0;
   23632   pNew->htsize = 0;
   23633   pNew->ht = 0;
   23634 }
   23635 
   23636 /* Remove all entries from a hash table.  Reclaim all memory.
   23637 ** Call this routine to delete a hash table or to reset a hash table
   23638 ** to the empty state.
   23639 */
   23640 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
   23641   HashElem *elem;         /* For looping over all elements of the table */
   23642 
   23643   assert( pH!=0 );
   23644   elem = pH->first;
   23645   pH->first = 0;
   23646   sqlite3_free(pH->ht);
   23647   pH->ht = 0;
   23648   pH->htsize = 0;
   23649   while( elem ){
   23650     HashElem *next_elem = elem->next;
   23651     sqlite3_free(elem);
   23652     elem = next_elem;
   23653   }
   23654   pH->count = 0;
   23655 }
   23656 
   23657 /*
   23658 ** The hashing function.
   23659 */
   23660 static unsigned int strHash(const char *z, int nKey){
   23661   unsigned int h = 0;
   23662   assert( nKey>=0 );
   23663   while( nKey > 0  ){
   23664     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
   23665     nKey--;
   23666   }
   23667   return h;
   23668 }
   23669 
   23670 
   23671 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
   23672 ** insert pNew into the pEntry hash bucket.
   23673 */
   23674 static void insertElement(
   23675   Hash *pH,              /* The complete hash table */
   23676   struct _ht *pEntry,    /* The entry into which pNew is inserted */
   23677   HashElem *pNew         /* The element to be inserted */
   23678 ){
   23679   HashElem *pHead;       /* First element already in pEntry */
   23680   if( pEntry ){
   23681     pHead = pEntry->count ? pEntry->chain : 0;
   23682     pEntry->count++;
   23683     pEntry->chain = pNew;
   23684   }else{
   23685     pHead = 0;
   23686   }
   23687   if( pHead ){
   23688     pNew->next = pHead;
   23689     pNew->prev = pHead->prev;
   23690     if( pHead->prev ){ pHead->prev->next = pNew; }
   23691     else             { pH->first = pNew; }
   23692     pHead->prev = pNew;
   23693   }else{
   23694     pNew->next = pH->first;
   23695     if( pH->first ){ pH->first->prev = pNew; }
   23696     pNew->prev = 0;
   23697     pH->first = pNew;
   23698   }
   23699 }
   23700 
   23701 
   23702 /* Resize the hash table so that it cantains "new_size" buckets.
   23703 **
   23704 ** The hash table might fail to resize if sqlite3_malloc() fails or
   23705 ** if the new size is the same as the prior size.
   23706 ** Return TRUE if the resize occurs and false if not.
   23707 */
   23708 static int rehash(Hash *pH, unsigned int new_size){
   23709   struct _ht *new_ht;            /* The new hash table */
   23710   HashElem *elem, *next_elem;    /* For looping over existing elements */
   23711 
   23712 #if SQLITE_MALLOC_SOFT_LIMIT>0
   23713   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
   23714     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
   23715   }
   23716   if( new_size==pH->htsize ) return 0;
   23717 #endif
   23718 
   23719   /* The inability to allocates space for a larger hash table is
   23720   ** a performance hit but it is not a fatal error.  So mark the
   23721   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
   23722   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
   23723   ** only zeroes the requested number of bytes whereas this module will
   23724   ** use the actual amount of space allocated for the hash table (which
   23725   ** may be larger than the requested amount).
   23726   */
   23727   sqlite3BeginBenignMalloc();
   23728   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
   23729   sqlite3EndBenignMalloc();
   23730 
   23731   if( new_ht==0 ) return 0;
   23732   sqlite3_free(pH->ht);
   23733   pH->ht = new_ht;
   23734   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
   23735   memset(new_ht, 0, new_size*sizeof(struct _ht));
   23736   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   23737     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
   23738     next_elem = elem->next;
   23739     insertElement(pH, &new_ht[h], elem);
   23740   }
   23741   return 1;
   23742 }
   23743 
   23744 /* This function (for internal use only) locates an element in an
   23745 ** hash table that matches the given key.  The hash for this key has
   23746 ** already been computed and is passed as the 4th parameter.
   23747 */
   23748 static HashElem *findElementGivenHash(
   23749   const Hash *pH,     /* The pH to be searched */
   23750   const char *pKey,   /* The key we are searching for */
   23751   int nKey,           /* Bytes in key (not counting zero terminator) */
   23752   unsigned int h      /* The hash for this key. */
   23753 ){
   23754   HashElem *elem;                /* Used to loop thru the element list */
   23755   int count;                     /* Number of elements left to test */
   23756 
   23757   if( pH->ht ){
   23758     struct _ht *pEntry = &pH->ht[h];
   23759     elem = pEntry->chain;
   23760     count = pEntry->count;
   23761   }else{
   23762     elem = pH->first;
   23763     count = pH->count;
   23764   }
   23765   while( count-- && ALWAYS(elem) ){
   23766     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
   23767       return elem;
   23768     }
   23769     elem = elem->next;
   23770   }
   23771   return 0;
   23772 }
   23773 
   23774 /* Remove a single entry from the hash table given a pointer to that
   23775 ** element and a hash on the element's key.
   23776 */
   23777 static void removeElementGivenHash(
   23778   Hash *pH,         /* The pH containing "elem" */
   23779   HashElem* elem,   /* The element to be removed from the pH */
   23780   unsigned int h    /* Hash value for the element */
   23781 ){
   23782   struct _ht *pEntry;
   23783   if( elem->prev ){
   23784     elem->prev->next = elem->next;
   23785   }else{
   23786     pH->first = elem->next;
   23787   }
   23788   if( elem->next ){
   23789     elem->next->prev = elem->prev;
   23790   }
   23791   if( pH->ht ){
   23792     pEntry = &pH->ht[h];
   23793     if( pEntry->chain==elem ){
   23794       pEntry->chain = elem->next;
   23795     }
   23796     pEntry->count--;
   23797     assert( pEntry->count>=0 );
   23798   }
   23799   sqlite3_free( elem );
   23800   pH->count--;
   23801   if( pH->count==0 ){
   23802     assert( pH->first==0 );
   23803     assert( pH->count==0 );
   23804     sqlite3HashClear(pH);
   23805   }
   23806 }
   23807 
   23808 /* Attempt to locate an element of the hash table pH with a key
   23809 ** that matches pKey,nKey.  Return the data for this element if it is
   23810 ** found, or NULL if there is no match.
   23811 */
   23812 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
   23813   HashElem *elem;    /* The element that matches key */
   23814   unsigned int h;    /* A hash on key */
   23815 
   23816   assert( pH!=0 );
   23817   assert( pKey!=0 );
   23818   assert( nKey>=0 );
   23819   if( pH->ht ){
   23820     h = strHash(pKey, nKey) % pH->htsize;
   23821   }else{
   23822     h = 0;
   23823   }
   23824   elem = findElementGivenHash(pH, pKey, nKey, h);
   23825   return elem ? elem->data : 0;
   23826 }
   23827 
   23828 /* Insert an element into the hash table pH.  The key is pKey,nKey
   23829 ** and the data is "data".
   23830 **
   23831 ** If no element exists with a matching key, then a new
   23832 ** element is created and NULL is returned.
   23833 **
   23834 ** If another element already exists with the same key, then the
   23835 ** new data replaces the old data and the old data is returned.
   23836 ** The key is not copied in this instance.  If a malloc fails, then
   23837 ** the new data is returned and the hash table is unchanged.
   23838 **
   23839 ** If the "data" parameter to this function is NULL, then the
   23840 ** element corresponding to "key" is removed from the hash table.
   23841 */
   23842 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
   23843   unsigned int h;       /* the hash of the key modulo hash table size */
   23844   HashElem *elem;       /* Used to loop thru the element list */
   23845   HashElem *new_elem;   /* New element added to the pH */
   23846 
   23847   assert( pH!=0 );
   23848   assert( pKey!=0 );
   23849   assert( nKey>=0 );
   23850   if( pH->htsize ){
   23851     h = strHash(pKey, nKey) % pH->htsize;
   23852   }else{
   23853     h = 0;
   23854   }
   23855   elem = findElementGivenHash(pH,pKey,nKey,h);
   23856   if( elem ){
   23857     void *old_data = elem->data;
   23858     if( data==0 ){
   23859       removeElementGivenHash(pH,elem,h);
   23860     }else{
   23861       elem->data = data;
   23862       elem->pKey = pKey;
   23863       assert(nKey==elem->nKey);
   23864     }
   23865     return old_data;
   23866   }
   23867   if( data==0 ) return 0;
   23868   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
   23869   if( new_elem==0 ) return data;
   23870   new_elem->pKey = pKey;
   23871   new_elem->nKey = nKey;
   23872   new_elem->data = data;
   23873   pH->count++;
   23874   if( pH->count>=10 && pH->count > 2*pH->htsize ){
   23875     if( rehash(pH, pH->count*2) ){
   23876       assert( pH->htsize>0 );
   23877       h = strHash(pKey, nKey) % pH->htsize;
   23878     }
   23879   }
   23880   if( pH->ht ){
   23881     insertElement(pH, &pH->ht[h], new_elem);
   23882   }else{
   23883     insertElement(pH, 0, new_elem);
   23884   }
   23885   return 0;
   23886 }
   23887 
   23888 /************** End of hash.c ************************************************/
   23889 /************** Begin file opcodes.c *****************************************/
   23890 /* Automatically generated.  Do not edit */
   23891 /* See the mkopcodec.awk script for details. */
   23892 #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   23893 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
   23894 # define OpHelp(X) "\0" X
   23895 #else
   23896 # define OpHelp(X)
   23897 #endif
   23898 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
   23899  static const char *const azName[] = { "?",
   23900      /*   1 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
   23901      /*   2 */ "Savepoint"        OpHelp(""),
   23902      /*   3 */ "AutoCommit"       OpHelp(""),
   23903      /*   4 */ "Transaction"      OpHelp(""),
   23904      /*   5 */ "SorterNext"       OpHelp(""),
   23905      /*   6 */ "PrevIfOpen"       OpHelp(""),
   23906      /*   7 */ "NextIfOpen"       OpHelp(""),
   23907      /*   8 */ "Prev"             OpHelp(""),
   23908      /*   9 */ "Next"             OpHelp(""),
   23909      /*  10 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
   23910      /*  11 */ "Checkpoint"       OpHelp(""),
   23911      /*  12 */ "JournalMode"      OpHelp(""),
   23912      /*  13 */ "Vacuum"           OpHelp(""),
   23913      /*  14 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
   23914      /*  15 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
   23915      /*  16 */ "Goto"             OpHelp(""),
   23916      /*  17 */ "Gosub"            OpHelp(""),
   23917      /*  18 */ "Return"           OpHelp(""),
   23918      /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
   23919      /*  20 */ "InitCoroutine"    OpHelp(""),
   23920      /*  21 */ "EndCoroutine"     OpHelp(""),
   23921      /*  22 */ "Yield"            OpHelp(""),
   23922      /*  23 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
   23923      /*  24 */ "Halt"             OpHelp(""),
   23924      /*  25 */ "Integer"          OpHelp("r[P2]=P1"),
   23925      /*  26 */ "Int64"            OpHelp("r[P2]=P4"),
   23926      /*  27 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
   23927      /*  28 */ "Null"             OpHelp("r[P2..P3]=NULL"),
   23928      /*  29 */ "SoftNull"         OpHelp("r[P1]=NULL"),
   23929      /*  30 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
   23930      /*  31 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
   23931      /*  32 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
   23932      /*  33 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
   23933      /*  34 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
   23934      /*  35 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
   23935      /*  36 */ "CollSeq"          OpHelp(""),
   23936      /*  37 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
   23937      /*  38 */ "MustBeInt"        OpHelp(""),
   23938      /*  39 */ "RealAffinity"     OpHelp(""),
   23939      /*  40 */ "Permutation"      OpHelp(""),
   23940      /*  41 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
   23941      /*  42 */ "Jump"             OpHelp(""),
   23942      /*  43 */ "Once"             OpHelp(""),
   23943      /*  44 */ "If"               OpHelp(""),
   23944      /*  45 */ "IfNot"            OpHelp(""),
   23945      /*  46 */ "Column"           OpHelp("r[P3]=PX"),
   23946      /*  47 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
   23947      /*  48 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
   23948      /*  49 */ "Count"            OpHelp("r[P2]=count()"),
   23949      /*  50 */ "ReadCookie"       OpHelp(""),
   23950      /*  51 */ "SetCookie"        OpHelp(""),
   23951      /*  52 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
   23952      /*  53 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
   23953      /*  54 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
   23954      /*  55 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
   23955      /*  56 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
   23956      /*  57 */ "SorterOpen"       OpHelp(""),
   23957      /*  58 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
   23958      /*  59 */ "Close"            OpHelp(""),
   23959      /*  60 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
   23960      /*  61 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
   23961      /*  62 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
   23962      /*  63 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
   23963      /*  64 */ "Seek"             OpHelp("intkey=r[P2]"),
   23964      /*  65 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
   23965      /*  66 */ "NotFound"         OpHelp("key=r[P3@P4]"),
   23966      /*  67 */ "Found"            OpHelp("key=r[P3@P4]"),
   23967      /*  68 */ "NotExists"        OpHelp("intkey=r[P3]"),
   23968      /*  69 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
   23969      /*  70 */ "NewRowid"         OpHelp("r[P2]=rowid"),
   23970      /*  71 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
   23971      /*  72 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
   23972      /*  73 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
   23973      /*  74 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
   23974      /*  75 */ "Delete"           OpHelp(""),
   23975      /*  76 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
   23976      /*  77 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
   23977      /*  78 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
   23978      /*  79 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
   23979      /*  80 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
   23980      /*  81 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
   23981      /*  82 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
   23982      /*  83 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
   23983      /*  84 */ "ResetCount"       OpHelp(""),
   23984      /*  85 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
   23985      /*  86 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
   23986      /*  87 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
   23987      /*  88 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
   23988      /*  89 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
   23989      /*  90 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
   23990      /*  91 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
   23991      /*  92 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
   23992      /*  93 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
   23993      /*  94 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
   23994      /*  95 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
   23995      /*  96 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
   23996      /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
   23997      /*  98 */ "SorterData"       OpHelp("r[P2]=data"),
   23998      /*  99 */ "RowKey"           OpHelp("r[P2]=key"),
   23999      /* 100 */ "RowData"          OpHelp("r[P2]=data"),
   24000      /* 101 */ "Rowid"            OpHelp("r[P2]=rowid"),
   24001      /* 102 */ "NullRow"          OpHelp(""),
   24002      /* 103 */ "Last"             OpHelp(""),
   24003      /* 104 */ "SorterSort"       OpHelp(""),
   24004      /* 105 */ "Sort"             OpHelp(""),
   24005      /* 106 */ "Rewind"           OpHelp(""),
   24006      /* 107 */ "SorterInsert"     OpHelp(""),
   24007      /* 108 */ "IdxInsert"        OpHelp("key=r[P2]"),
   24008      /* 109 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
   24009      /* 110 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
   24010      /* 111 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
   24011      /* 112 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
   24012      /* 113 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
   24013      /* 114 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
   24014      /* 115 */ "Destroy"          OpHelp(""),
   24015      /* 116 */ "Clear"            OpHelp(""),
   24016      /* 117 */ "ResetSorter"      OpHelp(""),
   24017      /* 118 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
   24018      /* 119 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
   24019      /* 120 */ "ParseSchema"      OpHelp(""),
   24020      /* 121 */ "LoadAnalysis"     OpHelp(""),
   24021      /* 122 */ "DropTable"        OpHelp(""),
   24022      /* 123 */ "DropIndex"        OpHelp(""),
   24023      /* 124 */ "DropTrigger"      OpHelp(""),
   24024      /* 125 */ "IntegrityCk"      OpHelp(""),
   24025      /* 126 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
   24026      /* 127 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
   24027      /* 128 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
   24028      /* 129 */ "Program"          OpHelp(""),
   24029      /* 130 */ "Param"            OpHelp(""),
   24030      /* 131 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
   24031      /* 132 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
   24032      /* 133 */ "Real"             OpHelp("r[P2]=P4"),
   24033      /* 134 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
   24034      /* 135 */ "IfPos"            OpHelp("if r[P1]>0 goto P2"),
   24035      /* 136 */ "IfNeg"            OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
   24036      /* 137 */ "IfZero"           OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
   24037      /* 138 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
   24038      /* 139 */ "IncrVacuum"       OpHelp(""),
   24039      /* 140 */ "Expire"           OpHelp(""),
   24040      /* 141 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
   24041      /* 142 */ "VBegin"           OpHelp(""),
   24042      /* 143 */ "ToText"           OpHelp(""),
   24043      /* 144 */ "ToBlob"           OpHelp(""),
   24044      /* 145 */ "ToNumeric"        OpHelp(""),
   24045      /* 146 */ "ToInt"            OpHelp(""),
   24046      /* 147 */ "ToReal"           OpHelp(""),
   24047      /* 148 */ "VCreate"          OpHelp(""),
   24048      /* 149 */ "VDestroy"         OpHelp(""),
   24049      /* 150 */ "VOpen"            OpHelp(""),
   24050      /* 151 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
   24051      /* 152 */ "VNext"            OpHelp(""),
   24052      /* 153 */ "VRename"          OpHelp(""),
   24053      /* 154 */ "Pagecount"        OpHelp(""),
   24054      /* 155 */ "MaxPgcnt"         OpHelp(""),
   24055      /* 156 */ "Init"             OpHelp("Start at P2"),
   24056      /* 157 */ "Noop"             OpHelp(""),
   24057      /* 158 */ "Explain"          OpHelp(""),
   24058   };
   24059   return azName[i];
   24060 }
   24061 #endif
   24062 
   24063 /************** End of opcodes.c *********************************************/
   24064 /************** Begin file os_unix.c *****************************************/
   24065 /*
   24066 ** 2004 May 22
   24067 **
   24068 ** The author disclaims copyright to this source code.  In place of
   24069 ** a legal notice, here is a blessing:
   24070 **
   24071 **    May you do good and not evil.
   24072 **    May you find forgiveness for yourself and forgive others.
   24073 **    May you share freely, never taking more than you give.
   24074 **
   24075 ******************************************************************************
   24076 **
   24077 ** This file contains the VFS implementation for unix-like operating systems
   24078 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
   24079 **
   24080 ** There are actually several different VFS implementations in this file.
   24081 ** The differences are in the way that file locking is done.  The default
   24082 ** implementation uses Posix Advisory Locks.  Alternative implementations
   24083 ** use flock(), dot-files, various proprietary locking schemas, or simply
   24084 ** skip locking all together.
   24085 **
   24086 ** This source file is organized into divisions where the logic for various
   24087 ** subfunctions is contained within the appropriate division.  PLEASE
   24088 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
   24089 ** in the correct division and should be clearly labeled.
   24090 **
   24091 ** The layout of divisions is as follows:
   24092 **
   24093 **   *  General-purpose declarations and utility functions.
   24094 **   *  Unique file ID logic used by VxWorks.
   24095 **   *  Various locking primitive implementations (all except proxy locking):
   24096 **      + for Posix Advisory Locks
   24097 **      + for no-op locks
   24098 **      + for dot-file locks
   24099 **      + for flock() locking
   24100 **      + for named semaphore locks (VxWorks only)
   24101 **      + for AFP filesystem locks (MacOSX only)
   24102 **   *  sqlite3_file methods not associated with locking.
   24103 **   *  Definitions of sqlite3_io_methods objects for all locking
   24104 **      methods plus "finder" functions for each locking method.
   24105 **   *  sqlite3_vfs method implementations.
   24106 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
   24107 **   *  Definitions of sqlite3_vfs objects for all locking methods
   24108 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
   24109 */
   24110 #if SQLITE_OS_UNIX              /* This file is used on unix only */
   24111 
   24112 /*
   24113 ** There are various methods for file locking used for concurrency
   24114 ** control:
   24115 **
   24116 **   1. POSIX locking (the default),
   24117 **   2. No locking,
   24118 **   3. Dot-file locking,
   24119 **   4. flock() locking,
   24120 **   5. AFP locking (OSX only),
   24121 **   6. Named POSIX semaphores (VXWorks only),
   24122 **   7. proxy locking. (OSX only)
   24123 **
   24124 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
   24125 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
   24126 ** selection of the appropriate locking style based on the filesystem
   24127 ** where the database is located.
   24128 */
   24129 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   24130 #  if defined(__APPLE__)
   24131 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   24132 #  else
   24133 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   24134 #  endif
   24135 #endif
   24136 
   24137 /*
   24138 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
   24139 ** vxworks, or 0 otherwise.
   24140 */
   24141 #ifndef OS_VXWORKS
   24142 #  if defined(__RTP__) || defined(_WRS_KERNEL)
   24143 #    define OS_VXWORKS 1
   24144 #  else
   24145 #    define OS_VXWORKS 0
   24146 #  endif
   24147 #endif
   24148 
   24149 /*
   24150 ** standard include files.
   24151 */
   24152 #include <sys/types.h>
   24153 #include <sys/stat.h>
   24154 #include <fcntl.h>
   24155 #include <unistd.h>
   24156 /* #include <time.h> */
   24157 #include <sys/time.h>
   24158 #include <errno.h>
   24159 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   24160 # include <sys/mman.h>
   24161 #endif
   24162 
   24163 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
   24164 # include <sys/ioctl.h>
   24165 # if OS_VXWORKS
   24166 #  include <semaphore.h>
   24167 #  include <limits.h>
   24168 # else
   24169 #  include <sys/file.h>
   24170 #  include <sys/param.h>
   24171 # endif
   24172 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   24173 
   24174 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   24175 # include <sys/mount.h>
   24176 #endif
   24177 
   24178 #ifdef HAVE_UTIME
   24179 # include <utime.h>
   24180 #endif
   24181 
   24182 /*
   24183 ** Allowed values of unixFile.fsFlags
   24184 */
   24185 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
   24186 
   24187 /*
   24188 ** If we are to be thread-safe, include the pthreads header and define
   24189 ** the SQLITE_UNIX_THREADS macro.
   24190 */
   24191 #if SQLITE_THREADSAFE
   24192 /* # include <pthread.h> */
   24193 # define SQLITE_UNIX_THREADS 1
   24194 #endif
   24195 
   24196 /*
   24197 ** Default permissions when creating a new file
   24198 */
   24199 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
   24200 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
   24201 #endif
   24202 
   24203 /*
   24204 ** Default permissions when creating auto proxy dir
   24205 */
   24206 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   24207 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
   24208 #endif
   24209 
   24210 /*
   24211 ** Maximum supported path-length.
   24212 */
   24213 #define MAX_PATHNAME 512
   24214 
   24215 /*
   24216 ** Only set the lastErrno if the error code is a real error and not
   24217 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
   24218 */
   24219 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
   24220 
   24221 /* Forward references */
   24222 typedef struct unixShm unixShm;               /* Connection shared memory */
   24223 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
   24224 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
   24225 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
   24226 
   24227 /*
   24228 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
   24229 ** cannot be closed immediately. In these cases, instances of the following
   24230 ** structure are used to store the file descriptor while waiting for an
   24231 ** opportunity to either close or reuse it.
   24232 */
   24233 struct UnixUnusedFd {
   24234   int fd;                   /* File descriptor to close */
   24235   int flags;                /* Flags this file descriptor was opened with */
   24236   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
   24237 };
   24238 
   24239 /*
   24240 ** The unixFile structure is subclass of sqlite3_file specific to the unix
   24241 ** VFS implementations.
   24242 */
   24243 typedef struct unixFile unixFile;
   24244 struct unixFile {
   24245   sqlite3_io_methods const *pMethod;  /* Always the first entry */
   24246   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
   24247   unixInodeInfo *pInode;              /* Info about locks on this inode */
   24248   int h;                              /* The file descriptor */
   24249   unsigned char eFileLock;            /* The type of lock held on this fd */
   24250   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
   24251   int lastErrno;                      /* The unix errno from last I/O error */
   24252   void *lockingContext;               /* Locking style specific state */
   24253   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
   24254   const char *zPath;                  /* Name of the file */
   24255   unixShm *pShm;                      /* Shared memory segment information */
   24256   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
   24257 #if SQLITE_MAX_MMAP_SIZE>0
   24258   int nFetchOut;                      /* Number of outstanding xFetch refs */
   24259   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
   24260   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
   24261   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
   24262   void *pMapRegion;                   /* Memory mapped region */
   24263 #endif
   24264 #ifdef __QNXNTO__
   24265   int sectorSize;                     /* Device sector size */
   24266   int deviceCharacteristics;          /* Precomputed device characteristics */
   24267 #endif
   24268 #if SQLITE_ENABLE_LOCKING_STYLE
   24269   int openFlags;                      /* The flags specified at open() */
   24270 #endif
   24271 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
   24272   unsigned fsFlags;                   /* cached details from statfs() */
   24273 #endif
   24274 #if OS_VXWORKS
   24275   struct vxworksFileId *pId;          /* Unique file ID */
   24276 #endif
   24277 #ifdef SQLITE_DEBUG
   24278   /* The next group of variables are used to track whether or not the
   24279   ** transaction counter in bytes 24-27 of database files are updated
   24280   ** whenever any part of the database changes.  An assertion fault will
   24281   ** occur if a file is updated without also updating the transaction
   24282   ** counter.  This test is made to avoid new problems similar to the
   24283   ** one described by ticket #3584.
   24284   */
   24285   unsigned char transCntrChng;   /* True if the transaction counter changed */
   24286   unsigned char dbUpdate;        /* True if any part of database file changed */
   24287   unsigned char inNormalWrite;   /* True if in a normal write operation */
   24288 
   24289 #endif
   24290 
   24291 #ifdef SQLITE_TEST
   24292   /* In test mode, increase the size of this structure a bit so that
   24293   ** it is larger than the struct CrashFile defined in test6.c.
   24294   */
   24295   char aPadding[32];
   24296 #endif
   24297 };
   24298 
   24299 /* This variable holds the process id (pid) from when the xRandomness()
   24300 ** method was called.  If xOpen() is called from a different process id,
   24301 ** indicating that a fork() has occurred, the PRNG will be reset.
   24302 */
   24303 static int randomnessPid = 0;
   24304 
   24305 /*
   24306 ** Allowed values for the unixFile.ctrlFlags bitmask:
   24307 */
   24308 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
   24309 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
   24310 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
   24311 #ifndef SQLITE_DISABLE_DIRSYNC
   24312 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
   24313 #else
   24314 # define UNIXFILE_DIRSYNC    0x00
   24315 #endif
   24316 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   24317 #define UNIXFILE_DELETE      0x20     /* Delete on close */
   24318 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
   24319 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
   24320 #define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings have been issued */
   24321 
   24322 /*
   24323 ** Include code that is common to all os_*.c files
   24324 */
   24325 /************** Include os_common.h in the middle of os_unix.c ***************/
   24326 /************** Begin file os_common.h ***************************************/
   24327 /*
   24328 ** 2004 May 22
   24329 **
   24330 ** The author disclaims copyright to this source code.  In place of
   24331 ** a legal notice, here is a blessing:
   24332 **
   24333 **    May you do good and not evil.
   24334 **    May you find forgiveness for yourself and forgive others.
   24335 **    May you share freely, never taking more than you give.
   24336 **
   24337 ******************************************************************************
   24338 **
   24339 ** This file contains macros and a little bit of code that is common to
   24340 ** all of the platform-specific files (os_*.c) and is #included into those
   24341 ** files.
   24342 **
   24343 ** This file should be #included by the os_*.c files only.  It is not a
   24344 ** general purpose header file.
   24345 */
   24346 #ifndef _OS_COMMON_H_
   24347 #define _OS_COMMON_H_
   24348 
   24349 /*
   24350 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   24351 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   24352 ** switch.  The following code should catch this problem at compile-time.
   24353 */
   24354 #ifdef MEMORY_DEBUG
   24355 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   24356 #endif
   24357 
   24358 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   24359 # ifndef SQLITE_DEBUG_OS_TRACE
   24360 #   define SQLITE_DEBUG_OS_TRACE 0
   24361 # endif
   24362   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   24363 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   24364 #else
   24365 # define OSTRACE(X)
   24366 #endif
   24367 
   24368 /*
   24369 ** Macros for performance tracing.  Normally turned off.  Only works
   24370 ** on i486 hardware.
   24371 */
   24372 #ifdef SQLITE_PERFORMANCE_TRACE
   24373 
   24374 /*
   24375 ** hwtime.h contains inline assembler code for implementing
   24376 ** high-performance timing routines.
   24377 */
   24378 /************** Include hwtime.h in the middle of os_common.h ****************/
   24379 /************** Begin file hwtime.h ******************************************/
   24380 /*
   24381 ** 2008 May 27
   24382 **
   24383 ** The author disclaims copyright to this source code.  In place of
   24384 ** a legal notice, here is a blessing:
   24385 **
   24386 **    May you do good and not evil.
   24387 **    May you find forgiveness for yourself and forgive others.
   24388 **    May you share freely, never taking more than you give.
   24389 **
   24390 ******************************************************************************
   24391 **
   24392 ** This file contains inline asm code for retrieving "high-performance"
   24393 ** counters for x86 class CPUs.
   24394 */
   24395 #ifndef _HWTIME_H_
   24396 #define _HWTIME_H_
   24397 
   24398 /*
   24399 ** The following routine only works on pentium-class (or newer) processors.
   24400 ** It uses the RDTSC opcode to read the cycle count value out of the
   24401 ** processor and returns that value.  This can be used for high-res
   24402 ** profiling.
   24403 */
   24404 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   24405       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   24406 
   24407   #if defined(__GNUC__)
   24408 
   24409   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24410      unsigned int lo, hi;
   24411      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   24412      return (sqlite_uint64)hi << 32 | lo;
   24413   }
   24414 
   24415   #elif defined(_MSC_VER)
   24416 
   24417   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   24418      __asm {
   24419         rdtsc
   24420         ret       ; return value at EDX:EAX
   24421      }
   24422   }
   24423 
   24424   #endif
   24425 
   24426 #elif (defined(__GNUC__) && defined(__x86_64__))
   24427 
   24428   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24429       unsigned long val;
   24430       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   24431       return val;
   24432   }
   24433 
   24434 #elif (defined(__GNUC__) && defined(__ppc__))
   24435 
   24436   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24437       unsigned long long retval;
   24438       unsigned long junk;
   24439       __asm__ __volatile__ ("\n\
   24440           1:      mftbu   %1\n\
   24441                   mftb    %L0\n\
   24442                   mftbu   %0\n\
   24443                   cmpw    %0,%1\n\
   24444                   bne     1b"
   24445                   : "=r" (retval), "=r" (junk));
   24446       return retval;
   24447   }
   24448 
   24449 #else
   24450 
   24451   #error Need implementation of sqlite3Hwtime() for your platform.
   24452 
   24453   /*
   24454   ** To compile without implementing sqlite3Hwtime() for your platform,
   24455   ** you can remove the above #error and use the following
   24456   ** stub function.  You will lose timing support for many
   24457   ** of the debugging and testing utilities, but it should at
   24458   ** least compile and run.
   24459   */
   24460 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   24461 
   24462 #endif
   24463 
   24464 #endif /* !defined(_HWTIME_H_) */
   24465 
   24466 /************** End of hwtime.h **********************************************/
   24467 /************** Continuing where we left off in os_common.h ******************/
   24468 
   24469 static sqlite_uint64 g_start;
   24470 static sqlite_uint64 g_elapsed;
   24471 #define TIMER_START       g_start=sqlite3Hwtime()
   24472 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   24473 #define TIMER_ELAPSED     g_elapsed
   24474 #else
   24475 #define TIMER_START
   24476 #define TIMER_END
   24477 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   24478 #endif
   24479 
   24480 /*
   24481 ** If we compile with the SQLITE_TEST macro set, then the following block
   24482 ** of code will give us the ability to simulate a disk I/O error.  This
   24483 ** is used for testing the I/O recovery logic.
   24484 */
   24485 #ifdef SQLITE_TEST
   24486 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   24487 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   24488 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   24489 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   24490 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   24491 SQLITE_API int sqlite3_diskfull_pending = 0;
   24492 SQLITE_API int sqlite3_diskfull = 0;
   24493 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   24494 #define SimulateIOError(CODE)  \
   24495   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   24496        || sqlite3_io_error_pending-- == 1 )  \
   24497               { local_ioerr(); CODE; }
   24498 static void local_ioerr(){
   24499   IOTRACE(("IOERR\n"));
   24500   sqlite3_io_error_hit++;
   24501   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   24502 }
   24503 #define SimulateDiskfullError(CODE) \
   24504    if( sqlite3_diskfull_pending ){ \
   24505      if( sqlite3_diskfull_pending == 1 ){ \
   24506        local_ioerr(); \
   24507        sqlite3_diskfull = 1; \
   24508        sqlite3_io_error_hit = 1; \
   24509        CODE; \
   24510      }else{ \
   24511        sqlite3_diskfull_pending--; \
   24512      } \
   24513    }
   24514 #else
   24515 #define SimulateIOErrorBenign(X)
   24516 #define SimulateIOError(A)
   24517 #define SimulateDiskfullError(A)
   24518 #endif
   24519 
   24520 /*
   24521 ** When testing, keep a count of the number of open files.
   24522 */
   24523 #ifdef SQLITE_TEST
   24524 SQLITE_API int sqlite3_open_file_count = 0;
   24525 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   24526 #else
   24527 #define OpenCounter(X)
   24528 #endif
   24529 
   24530 #endif /* !defined(_OS_COMMON_H_) */
   24531 
   24532 /************** End of os_common.h *******************************************/
   24533 /************** Continuing where we left off in os_unix.c ********************/
   24534 
   24535 /*
   24536 ** Define various macros that are missing from some systems.
   24537 */
   24538 #ifndef O_LARGEFILE
   24539 # define O_LARGEFILE 0
   24540 #endif
   24541 #ifdef SQLITE_DISABLE_LFS
   24542 # undef O_LARGEFILE
   24543 # define O_LARGEFILE 0
   24544 #endif
   24545 #ifndef O_NOFOLLOW
   24546 # define O_NOFOLLOW 0
   24547 #endif
   24548 #ifndef O_BINARY
   24549 # define O_BINARY 0
   24550 #endif
   24551 
   24552 /*
   24553 ** The threadid macro resolves to the thread-id or to 0.  Used for
   24554 ** testing and debugging only.
   24555 */
   24556 #if SQLITE_THREADSAFE
   24557 #define threadid pthread_self()
   24558 #else
   24559 #define threadid 0
   24560 #endif
   24561 
   24562 /*
   24563 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
   24564 */
   24565 #if !defined(HAVE_MREMAP)
   24566 # if defined(__linux__) && defined(_GNU_SOURCE)
   24567 #  define HAVE_MREMAP 1
   24568 # else
   24569 #  define HAVE_MREMAP 0
   24570 # endif
   24571 #endif
   24572 
   24573 /*
   24574 ** Different Unix systems declare open() in different ways.  Same use
   24575 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
   24576 ** The difference is important when using a pointer to the function.
   24577 **
   24578 ** The safest way to deal with the problem is to always use this wrapper
   24579 ** which always has the same well-defined interface.
   24580 */
   24581 static int posixOpen(const char *zFile, int flags, int mode){
   24582   return open(zFile, flags, mode);
   24583 }
   24584 
   24585 /*
   24586 ** On some systems, calls to fchown() will trigger a message in a security
   24587 ** log if they come from non-root processes.  So avoid calling fchown() if
   24588 ** we are not running as root.
   24589 */
   24590 static int posixFchown(int fd, uid_t uid, gid_t gid){
   24591 #if OS_VXWORKS
   24592   return 0;
   24593 #else
   24594   return geteuid() ? 0 : fchown(fd,uid,gid);
   24595 #endif
   24596 }
   24597 
   24598 /* Forward reference */
   24599 static int openDirectory(const char*, int*);
   24600 static int unixGetpagesize(void);
   24601 
   24602 /*
   24603 ** Many system calls are accessed through pointer-to-functions so that
   24604 ** they may be overridden at runtime to facilitate fault injection during
   24605 ** testing and sandboxing.  The following array holds the names and pointers
   24606 ** to all overrideable system calls.
   24607 */
   24608 static struct unix_syscall {
   24609   const char *zName;            /* Name of the system call */
   24610   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   24611   sqlite3_syscall_ptr pDefault; /* Default value */
   24612 } aSyscall[] = {
   24613   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
   24614 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
   24615 
   24616   { "close",        (sqlite3_syscall_ptr)close,      0  },
   24617 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
   24618 
   24619   { "access",       (sqlite3_syscall_ptr)access,     0  },
   24620 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
   24621 
   24622   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
   24623 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
   24624 
   24625   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
   24626 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
   24627 
   24628 /*
   24629 ** The DJGPP compiler environment looks mostly like Unix, but it
   24630 ** lacks the fcntl() system call.  So redefine fcntl() to be something
   24631 ** that always succeeds.  This means that locking does not occur under
   24632 ** DJGPP.  But it is DOS - what did you expect?
   24633 */
   24634 #ifdef __DJGPP__
   24635   { "fstat",        0,                 0  },
   24636 #define osFstat(a,b,c)    0
   24637 #else
   24638   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
   24639 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
   24640 #endif
   24641 
   24642   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
   24643 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
   24644 
   24645   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
   24646 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
   24647 
   24648   { "read",         (sqlite3_syscall_ptr)read,       0  },
   24649 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
   24650 
   24651 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   24652   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
   24653 #else
   24654   { "pread",        (sqlite3_syscall_ptr)0,          0  },
   24655 #endif
   24656 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
   24657 
   24658 #if defined(USE_PREAD64)
   24659   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
   24660 #else
   24661   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
   24662 #endif
   24663 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
   24664 
   24665   { "write",        (sqlite3_syscall_ptr)write,      0  },
   24666 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
   24667 
   24668 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   24669   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
   24670 #else
   24671   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
   24672 #endif
   24673 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
   24674                     aSyscall[12].pCurrent)
   24675 
   24676 #if defined(USE_PREAD64)
   24677   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
   24678 #else
   24679   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
   24680 #endif
   24681 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
   24682                     aSyscall[13].pCurrent)
   24683 
   24684   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
   24685 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
   24686 
   24687 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   24688   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
   24689 #else
   24690   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
   24691 #endif
   24692 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
   24693 
   24694   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
   24695 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
   24696 
   24697   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
   24698 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
   24699 
   24700   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
   24701 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
   24702 
   24703   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
   24704 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
   24705 
   24706   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
   24707 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
   24708 
   24709 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   24710   { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
   24711 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
   24712 
   24713   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
   24714 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
   24715 
   24716 #if HAVE_MREMAP
   24717   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
   24718 #else
   24719   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
   24720 #endif
   24721 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
   24722   { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
   24723 #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
   24724 
   24725 #endif
   24726 
   24727 }; /* End of the overrideable system calls */
   24728 
   24729 /*
   24730 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   24731 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
   24732 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   24733 ** system call named zName.
   24734 */
   24735 static int unixSetSystemCall(
   24736   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   24737   const char *zName,            /* Name of system call to override */
   24738   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   24739 ){
   24740   unsigned int i;
   24741   int rc = SQLITE_NOTFOUND;
   24742 
   24743   UNUSED_PARAMETER(pNotUsed);
   24744   if( zName==0 ){
   24745     /* If no zName is given, restore all system calls to their default
   24746     ** settings and return NULL
   24747     */
   24748     rc = SQLITE_OK;
   24749     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   24750       if( aSyscall[i].pDefault ){
   24751         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   24752       }
   24753     }
   24754   }else{
   24755     /* If zName is specified, operate on only the one system call
   24756     ** specified.
   24757     */
   24758     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   24759       if( strcmp(zName, aSyscall[i].zName)==0 ){
   24760         if( aSyscall[i].pDefault==0 ){
   24761           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   24762         }
   24763         rc = SQLITE_OK;
   24764         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   24765         aSyscall[i].pCurrent = pNewFunc;
   24766         break;
   24767       }
   24768     }
   24769   }
   24770   return rc;
   24771 }
   24772 
   24773 /*
   24774 ** Return the value of a system call.  Return NULL if zName is not a
   24775 ** recognized system call name.  NULL is also returned if the system call
   24776 ** is currently undefined.
   24777 */
   24778 static sqlite3_syscall_ptr unixGetSystemCall(
   24779   sqlite3_vfs *pNotUsed,
   24780   const char *zName
   24781 ){
   24782   unsigned int i;
   24783 
   24784   UNUSED_PARAMETER(pNotUsed);
   24785   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   24786     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   24787   }
   24788   return 0;
   24789 }
   24790 
   24791 /*
   24792 ** Return the name of the first system call after zName.  If zName==NULL
   24793 ** then return the name of the first system call.  Return NULL if zName
   24794 ** is the last system call or if zName is not the name of a valid
   24795 ** system call.
   24796 */
   24797 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
   24798   int i = -1;
   24799 
   24800   UNUSED_PARAMETER(p);
   24801   if( zName ){
   24802     for(i=0; i<ArraySize(aSyscall)-1; i++){
   24803       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   24804     }
   24805   }
   24806   for(i++; i<ArraySize(aSyscall); i++){
   24807     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   24808   }
   24809   return 0;
   24810 }
   24811 
   24812 /*
   24813 ** Do not accept any file descriptor less than this value, in order to avoid
   24814 ** opening database file using file descriptors that are commonly used for
   24815 ** standard input, output, and error.
   24816 */
   24817 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
   24818 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
   24819 #endif
   24820 
   24821 /*
   24822 ** Invoke open().  Do so multiple times, until it either succeeds or
   24823 ** fails for some reason other than EINTR.
   24824 **
   24825 ** If the file creation mode "m" is 0 then set it to the default for
   24826 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
   24827 ** 0644) as modified by the system umask.  If m is not 0, then
   24828 ** make the file creation mode be exactly m ignoring the umask.
   24829 **
   24830 ** The m parameter will be non-zero only when creating -wal, -journal,
   24831 ** and -shm files.  We want those files to have *exactly* the same
   24832 ** permissions as their original database, unadulterated by the umask.
   24833 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
   24834 ** transaction crashes and leaves behind hot journals, then any
   24835 ** process that is able to write to the database will also be able to
   24836 ** recover the hot journals.
   24837 */
   24838 static int robust_open(const char *z, int f, mode_t m){
   24839   int fd;
   24840   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
   24841   while(1){
   24842 #if defined(O_CLOEXEC)
   24843     fd = osOpen(z,f|O_CLOEXEC,m2);
   24844 #else
   24845     fd = osOpen(z,f,m2);
   24846 #endif
   24847     if( fd<0 ){
   24848       if( errno==EINTR ) continue;
   24849       break;
   24850     }
   24851     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
   24852     osClose(fd);
   24853     sqlite3_log(SQLITE_WARNING,
   24854                 "attempt to open \"%s\" as file descriptor %d", z, fd);
   24855     fd = -1;
   24856     if( osOpen("/dev/null", f, m)<0 ) break;
   24857   }
   24858   if( fd>=0 ){
   24859     if( m!=0 ){
   24860       struct stat statbuf;
   24861       if( osFstat(fd, &statbuf)==0
   24862        && statbuf.st_size==0
   24863        && (statbuf.st_mode&0777)!=m
   24864       ){
   24865         osFchmod(fd, m);
   24866       }
   24867     }
   24868 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
   24869     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   24870 #endif
   24871   }
   24872   return fd;
   24873 }
   24874 
   24875 /*
   24876 ** Helper functions to obtain and relinquish the global mutex. The
   24877 ** global mutex is used to protect the unixInodeInfo and
   24878 ** vxworksFileId objects used by this file, all of which may be
   24879 ** shared by multiple threads.
   24880 **
   24881 ** Function unixMutexHeld() is used to assert() that the global mutex
   24882 ** is held when required. This function is only used as part of assert()
   24883 ** statements. e.g.
   24884 **
   24885 **   unixEnterMutex()
   24886 **     assert( unixMutexHeld() );
   24887 **   unixEnterLeave()
   24888 */
   24889 static void unixEnterMutex(void){
   24890   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   24891 }
   24892 static void unixLeaveMutex(void){
   24893   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   24894 }
   24895 #ifdef SQLITE_DEBUG
   24896 static int unixMutexHeld(void) {
   24897   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   24898 }
   24899 #endif
   24900 
   24901 
   24902 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   24903 /*
   24904 ** Helper function for printing out trace information from debugging
   24905 ** binaries. This returns the string represetation of the supplied
   24906 ** integer lock-type.
   24907 */
   24908 static const char *azFileLock(int eFileLock){
   24909   switch( eFileLock ){
   24910     case NO_LOCK: return "NONE";
   24911     case SHARED_LOCK: return "SHARED";
   24912     case RESERVED_LOCK: return "RESERVED";
   24913     case PENDING_LOCK: return "PENDING";
   24914     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   24915   }
   24916   return "ERROR";
   24917 }
   24918 #endif
   24919 
   24920 #ifdef SQLITE_LOCK_TRACE
   24921 /*
   24922 ** Print out information about all locking operations.
   24923 **
   24924 ** This routine is used for troubleshooting locks on multithreaded
   24925 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   24926 ** command-line option on the compiler.  This code is normally
   24927 ** turned off.
   24928 */
   24929 static int lockTrace(int fd, int op, struct flock *p){
   24930   char *zOpName, *zType;
   24931   int s;
   24932   int savedErrno;
   24933   if( op==F_GETLK ){
   24934     zOpName = "GETLK";
   24935   }else if( op==F_SETLK ){
   24936     zOpName = "SETLK";
   24937   }else{
   24938     s = osFcntl(fd, op, p);
   24939     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   24940     return s;
   24941   }
   24942   if( p->l_type==F_RDLCK ){
   24943     zType = "RDLCK";
   24944   }else if( p->l_type==F_WRLCK ){
   24945     zType = "WRLCK";
   24946   }else if( p->l_type==F_UNLCK ){
   24947     zType = "UNLCK";
   24948   }else{
   24949     assert( 0 );
   24950   }
   24951   assert( p->l_whence==SEEK_SET );
   24952   s = osFcntl(fd, op, p);
   24953   savedErrno = errno;
   24954   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   24955      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   24956      (int)p->l_pid, s);
   24957   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   24958     struct flock l2;
   24959     l2 = *p;
   24960     osFcntl(fd, F_GETLK, &l2);
   24961     if( l2.l_type==F_RDLCK ){
   24962       zType = "RDLCK";
   24963     }else if( l2.l_type==F_WRLCK ){
   24964       zType = "WRLCK";
   24965     }else if( l2.l_type==F_UNLCK ){
   24966       zType = "UNLCK";
   24967     }else{
   24968       assert( 0 );
   24969     }
   24970     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   24971        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   24972   }
   24973   errno = savedErrno;
   24974   return s;
   24975 }
   24976 #undef osFcntl
   24977 #define osFcntl lockTrace
   24978 #endif /* SQLITE_LOCK_TRACE */
   24979 
   24980 /*
   24981 ** Retry ftruncate() calls that fail due to EINTR
   24982 */
   24983 static int robust_ftruncate(int h, sqlite3_int64 sz){
   24984   int rc;
   24985   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
   24986   return rc;
   24987 }
   24988 
   24989 /*
   24990 ** This routine translates a standard POSIX errno code into something
   24991 ** useful to the clients of the sqlite3 functions.  Specifically, it is
   24992 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
   24993 ** and a variety of "please close the file descriptor NOW" errors into
   24994 ** SQLITE_IOERR
   24995 **
   24996 ** Errors during initialization of locks, or file system support for locks,
   24997 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
   24998 */
   24999 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
   25000   switch (posixError) {
   25001 #if 0
   25002   /* At one point this code was not commented out. In theory, this branch
   25003   ** should never be hit, as this function should only be called after
   25004   ** a locking-related function (i.e. fcntl()) has returned non-zero with
   25005   ** the value of errno as the first argument. Since a system call has failed,
   25006   ** errno should be non-zero.
   25007   **
   25008   ** Despite this, if errno really is zero, we still don't want to return
   25009   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
   25010   ** propagated back to the caller. Commenting this branch out means errno==0
   25011   ** will be handled by the "default:" case below.
   25012   */
   25013   case 0:
   25014     return SQLITE_OK;
   25015 #endif
   25016 
   25017   case EAGAIN:
   25018   case ETIMEDOUT:
   25019   case EBUSY:
   25020   case EINTR:
   25021   case ENOLCK:
   25022     /* random NFS retry error, unless during file system support
   25023      * introspection, in which it actually means what it says */
   25024     return SQLITE_BUSY;
   25025 
   25026   case EACCES:
   25027     /* EACCES is like EAGAIN during locking operations, but not any other time*/
   25028     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
   25029         (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
   25030         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
   25031         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
   25032       return SQLITE_BUSY;
   25033     }
   25034     /* else fall through */
   25035   case EPERM:
   25036     return SQLITE_PERM;
   25037 
   25038 #if EOPNOTSUPP!=ENOTSUP
   25039   case EOPNOTSUPP:
   25040     /* something went terribly awry, unless during file system support
   25041      * introspection, in which it actually means what it says */
   25042 #endif
   25043 #ifdef ENOTSUP
   25044   case ENOTSUP:
   25045     /* invalid fd, unless during file system support introspection, in which
   25046      * it actually means what it says */
   25047 #endif
   25048   case EIO:
   25049   case EBADF:
   25050   case EINVAL:
   25051   case ENOTCONN:
   25052   case ENODEV:
   25053   case ENXIO:
   25054   case ENOENT:
   25055 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
   25056   case ESTALE:
   25057 #endif
   25058   case ENOSYS:
   25059     /* these should force the client to close the file and reconnect */
   25060 
   25061   default:
   25062     return sqliteIOErr;
   25063   }
   25064 }
   25065 
   25066 
   25067 /******************************************************************************
   25068 ****************** Begin Unique File ID Utility Used By VxWorks ***************
   25069 **
   25070 ** On most versions of unix, we can get a unique ID for a file by concatenating
   25071 ** the device number and the inode number.  But this does not work on VxWorks.
   25072 ** On VxWorks, a unique file id must be based on the canonical filename.
   25073 **
   25074 ** A pointer to an instance of the following structure can be used as a
   25075 ** unique file ID in VxWorks.  Each instance of this structure contains
   25076 ** a copy of the canonical filename.  There is also a reference count.
   25077 ** The structure is reclaimed when the number of pointers to it drops to
   25078 ** zero.
   25079 **
   25080 ** There are never very many files open at one time and lookups are not
   25081 ** a performance-critical path, so it is sufficient to put these
   25082 ** structures on a linked list.
   25083 */
   25084 struct vxworksFileId {
   25085   struct vxworksFileId *pNext;  /* Next in a list of them all */
   25086   int nRef;                     /* Number of references to this one */
   25087   int nName;                    /* Length of the zCanonicalName[] string */
   25088   char *zCanonicalName;         /* Canonical filename */
   25089 };
   25090 
   25091 #if OS_VXWORKS
   25092 /*
   25093 ** All unique filenames are held on a linked list headed by this
   25094 ** variable:
   25095 */
   25096 static struct vxworksFileId *vxworksFileList = 0;
   25097 
   25098 /*
   25099 ** Simplify a filename into its canonical form
   25100 ** by making the following changes:
   25101 **
   25102 **  * removing any trailing and duplicate /
   25103 **  * convert /./ into just /
   25104 **  * convert /A/../ where A is any simple name into just /
   25105 **
   25106 ** Changes are made in-place.  Return the new name length.
   25107 **
   25108 ** The original filename is in z[0..n-1].  Return the number of
   25109 ** characters in the simplified name.
   25110 */
   25111 static int vxworksSimplifyName(char *z, int n){
   25112   int i, j;
   25113   while( n>1 && z[n-1]=='/' ){ n--; }
   25114   for(i=j=0; i<n; i++){
   25115     if( z[i]=='/' ){
   25116       if( z[i+1]=='/' ) continue;
   25117       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
   25118         i += 1;
   25119         continue;
   25120       }
   25121       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
   25122         while( j>0 && z[j-1]!='/' ){ j--; }
   25123         if( j>0 ){ j--; }
   25124         i += 2;
   25125         continue;
   25126       }
   25127     }
   25128     z[j++] = z[i];
   25129   }
   25130   z[j] = 0;
   25131   return j;
   25132 }
   25133 
   25134 /*
   25135 ** Find a unique file ID for the given absolute pathname.  Return
   25136 ** a pointer to the vxworksFileId object.  This pointer is the unique
   25137 ** file ID.
   25138 **
   25139 ** The nRef field of the vxworksFileId object is incremented before
   25140 ** the object is returned.  A new vxworksFileId object is created
   25141 ** and added to the global list if necessary.
   25142 **
   25143 ** If a memory allocation error occurs, return NULL.
   25144 */
   25145 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
   25146   struct vxworksFileId *pNew;         /* search key and new file ID */
   25147   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
   25148   int n;                              /* Length of zAbsoluteName string */
   25149 
   25150   assert( zAbsoluteName[0]=='/' );
   25151   n = (int)strlen(zAbsoluteName);
   25152   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
   25153   if( pNew==0 ) return 0;
   25154   pNew->zCanonicalName = (char*)&pNew[1];
   25155   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
   25156   n = vxworksSimplifyName(pNew->zCanonicalName, n);
   25157 
   25158   /* Search for an existing entry that matching the canonical name.
   25159   ** If found, increment the reference count and return a pointer to
   25160   ** the existing file ID.
   25161   */
   25162   unixEnterMutex();
   25163   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
   25164     if( pCandidate->nName==n
   25165      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
   25166     ){
   25167        sqlite3_free(pNew);
   25168        pCandidate->nRef++;
   25169        unixLeaveMutex();
   25170        return pCandidate;
   25171     }
   25172   }
   25173 
   25174   /* No match was found.  We will make a new file ID */
   25175   pNew->nRef = 1;
   25176   pNew->nName = n;
   25177   pNew->pNext = vxworksFileList;
   25178   vxworksFileList = pNew;
   25179   unixLeaveMutex();
   25180   return pNew;
   25181 }
   25182 
   25183 /*
   25184 ** Decrement the reference count on a vxworksFileId object.  Free
   25185 ** the object when the reference count reaches zero.
   25186 */
   25187 static void vxworksReleaseFileId(struct vxworksFileId *pId){
   25188   unixEnterMutex();
   25189   assert( pId->nRef>0 );
   25190   pId->nRef--;
   25191   if( pId->nRef==0 ){
   25192     struct vxworksFileId **pp;
   25193     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
   25194     assert( *pp==pId );
   25195     *pp = pId->pNext;
   25196     sqlite3_free(pId);
   25197   }
   25198   unixLeaveMutex();
   25199 }
   25200 #endif /* OS_VXWORKS */
   25201 /*************** End of Unique File ID Utility Used By VxWorks ****************
   25202 ******************************************************************************/
   25203 
   25204 
   25205 /******************************************************************************
   25206 *************************** Posix Advisory Locking ****************************
   25207 **
   25208 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
   25209 ** section 6.5.2.2 lines 483 through 490 specify that when a process
   25210 ** sets or clears a lock, that operation overrides any prior locks set
   25211 ** by the same process.  It does not explicitly say so, but this implies
   25212 ** that it overrides locks set by the same process using a different
   25213 ** file descriptor.  Consider this test case:
   25214 **
   25215 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   25216 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   25217 **
   25218 ** Suppose ./file1 and ./file2 are really the same file (because
   25219 ** one is a hard or symbolic link to the other) then if you set
   25220 ** an exclusive lock on fd1, then try to get an exclusive lock
   25221 ** on fd2, it works.  I would have expected the second lock to
   25222 ** fail since there was already a lock on the file due to fd1.
   25223 ** But not so.  Since both locks came from the same process, the
   25224 ** second overrides the first, even though they were on different
   25225 ** file descriptors opened on different file names.
   25226 **
   25227 ** This means that we cannot use POSIX locks to synchronize file access
   25228 ** among competing threads of the same process.  POSIX locks will work fine
   25229 ** to synchronize access for threads in separate processes, but not
   25230 ** threads within the same process.
   25231 **
   25232 ** To work around the problem, SQLite has to manage file locks internally
   25233 ** on its own.  Whenever a new database is opened, we have to find the
   25234 ** specific inode of the database file (the inode is determined by the
   25235 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
   25236 ** and check for locks already existing on that inode.  When locks are
   25237 ** created or removed, we have to look at our own internal record of the
   25238 ** locks to see if another thread has previously set a lock on that same
   25239 ** inode.
   25240 **
   25241 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
   25242 ** For VxWorks, we have to use the alternative unique ID system based on
   25243 ** canonical filename and implemented in the previous division.)
   25244 **
   25245 ** The sqlite3_file structure for POSIX is no longer just an integer file
   25246 ** descriptor.  It is now a structure that holds the integer file
   25247 ** descriptor and a pointer to a structure that describes the internal
   25248 ** locks on the corresponding inode.  There is one locking structure
   25249 ** per inode, so if the same inode is opened twice, both unixFile structures
   25250 ** point to the same locking structure.  The locking structure keeps
   25251 ** a reference count (so we will know when to delete it) and a "cnt"
   25252 ** field that tells us its internal lock status.  cnt==0 means the
   25253 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   25254 ** cnt>0 means there are cnt shared locks on the file.
   25255 **
   25256 ** Any attempt to lock or unlock a file first checks the locking
   25257 ** structure.  The fcntl() system call is only invoked to set a
   25258 ** POSIX lock if the internal lock structure transitions between
   25259 ** a locked and an unlocked state.
   25260 **
   25261 ** But wait:  there are yet more problems with POSIX advisory locks.
   25262 **
   25263 ** If you close a file descriptor that points to a file that has locks,
   25264 ** all locks on that file that are owned by the current process are
   25265 ** released.  To work around this problem, each unixInodeInfo object
   25266 ** maintains a count of the number of pending locks on tha inode.
   25267 ** When an attempt is made to close an unixFile, if there are
   25268 ** other unixFile open on the same inode that are holding locks, the call
   25269 ** to close() the file descriptor is deferred until all of the locks clear.
   25270 ** The unixInodeInfo structure keeps a list of file descriptors that need to
   25271 ** be closed and that list is walked (and cleared) when the last lock
   25272 ** clears.
   25273 **
   25274 ** Yet another problem:  LinuxThreads do not play well with posix locks.
   25275 **
   25276 ** Many older versions of linux use the LinuxThreads library which is
   25277 ** not posix compliant.  Under LinuxThreads, a lock created by thread
   25278 ** A cannot be modified or overridden by a different thread B.
   25279 ** Only thread A can modify the lock.  Locking behavior is correct
   25280 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
   25281 ** on linux - with NPTL a lock created by thread A can override locks
   25282 ** in thread B.  But there is no way to know at compile-time which
   25283 ** threading library is being used.  So there is no way to know at
   25284 ** compile-time whether or not thread A can override locks on thread B.
   25285 ** One has to do a run-time check to discover the behavior of the
   25286 ** current process.
   25287 **
   25288 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
   25289 ** was dropped beginning with version 3.7.0.  SQLite will still work with
   25290 ** LinuxThreads provided that (1) there is no more than one connection
   25291 ** per database file in the same process and (2) database connections
   25292 ** do not move across threads.
   25293 */
   25294 
   25295 /*
   25296 ** An instance of the following structure serves as the key used
   25297 ** to locate a particular unixInodeInfo object.
   25298 */
   25299 struct unixFileId {
   25300   dev_t dev;                  /* Device number */
   25301 #if OS_VXWORKS
   25302   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
   25303 #else
   25304   ino_t ino;                  /* Inode number */
   25305 #endif
   25306 };
   25307 
   25308 /*
   25309 ** An instance of the following structure is allocated for each open
   25310 ** inode.  Or, on LinuxThreads, there is one of these structures for
   25311 ** each inode opened by each thread.
   25312 **
   25313 ** A single inode can have multiple file descriptors, so each unixFile
   25314 ** structure contains a pointer to an instance of this object and this
   25315 ** object keeps a count of the number of unixFile pointing to it.
   25316 */
   25317 struct unixInodeInfo {
   25318   struct unixFileId fileId;       /* The lookup key */
   25319   int nShared;                    /* Number of SHARED locks held */
   25320   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   25321   unsigned char bProcessLock;     /* An exclusive process lock is held */
   25322   int nRef;                       /* Number of pointers to this structure */
   25323   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
   25324   int nLock;                      /* Number of outstanding file locks */
   25325   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
   25326   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
   25327   unixInodeInfo *pPrev;           /*    .... doubly linked */
   25328 #if SQLITE_ENABLE_LOCKING_STYLE
   25329   unsigned long long sharedByte;  /* for AFP simulated shared lock */
   25330 #endif
   25331 #if OS_VXWORKS
   25332   sem_t *pSem;                    /* Named POSIX semaphore */
   25333   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
   25334 #endif
   25335 };
   25336 
   25337 /*
   25338 ** A lists of all unixInodeInfo objects.
   25339 */
   25340 static unixInodeInfo *inodeList = 0;
   25341 
   25342 /*
   25343 **
   25344 ** This function - unixLogError_x(), is only ever called via the macro
   25345 ** unixLogError().
   25346 **
   25347 ** It is invoked after an error occurs in an OS function and errno has been
   25348 ** set. It logs a message using sqlite3_log() containing the current value of
   25349 ** errno and, if possible, the human-readable equivalent from strerror() or
   25350 ** strerror_r().
   25351 **
   25352 ** The first argument passed to the macro should be the error code that
   25353 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   25354 ** The two subsequent arguments should be the name of the OS function that
   25355 ** failed (e.g. "unlink", "open") and the associated file-system path,
   25356 ** if any.
   25357 */
   25358 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
   25359 static int unixLogErrorAtLine(
   25360   int errcode,                    /* SQLite error code */
   25361   const char *zFunc,              /* Name of OS function that failed */
   25362   const char *zPath,              /* File path associated with error */
   25363   int iLine                       /* Source line number where error occurred */
   25364 ){
   25365   char *zErr;                     /* Message from strerror() or equivalent */
   25366   int iErrno = errno;             /* Saved syscall error number */
   25367 
   25368   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
   25369   ** the strerror() function to obtain the human-readable error message
   25370   ** equivalent to errno. Otherwise, use strerror_r().
   25371   */
   25372 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
   25373   char aErr[80];
   25374   memset(aErr, 0, sizeof(aErr));
   25375   zErr = aErr;
   25376 
   25377   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
   25378   ** assume that the system provides the GNU version of strerror_r() that
   25379   ** returns a pointer to a buffer containing the error message. That pointer
   25380   ** may point to aErr[], or it may point to some static storage somewhere.
   25381   ** Otherwise, assume that the system provides the POSIX version of
   25382   ** strerror_r(), which always writes an error message into aErr[].
   25383   **
   25384   ** If the code incorrectly assumes that it is the POSIX version that is
   25385   ** available, the error message will often be an empty string. Not a
   25386   ** huge problem. Incorrectly concluding that the GNU version is available
   25387   ** could lead to a segfault though.
   25388   */
   25389 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
   25390   zErr =
   25391 # endif
   25392   strerror_r(iErrno, aErr, sizeof(aErr)-1);
   25393 
   25394 #elif SQLITE_THREADSAFE
   25395   /* This is a threadsafe build, but strerror_r() is not available. */
   25396   zErr = "";
   25397 #else
   25398   /* Non-threadsafe build, use strerror(). */
   25399   zErr = strerror(iErrno);
   25400 #endif
   25401 
   25402   if( zPath==0 ) zPath = "";
   25403   sqlite3_log(errcode,
   25404       "os_unix.c:%d: (%d) %s(%s) - %s",
   25405       iLine, iErrno, zFunc, zPath, zErr
   25406   );
   25407 
   25408   return errcode;
   25409 }
   25410 
   25411 /*
   25412 ** Close a file descriptor.
   25413 **
   25414 ** We assume that close() almost always works, since it is only in a
   25415 ** very sick application or on a very sick platform that it might fail.
   25416 ** If it does fail, simply leak the file descriptor, but do log the
   25417 ** error.
   25418 **
   25419 ** Note that it is not safe to retry close() after EINTR since the
   25420 ** file descriptor might have already been reused by another thread.
   25421 ** So we don't even try to recover from an EINTR.  Just log the error
   25422 ** and move on.
   25423 */
   25424 static void robust_close(unixFile *pFile, int h, int lineno){
   25425   if( osClose(h) ){
   25426     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
   25427                        pFile ? pFile->zPath : 0, lineno);
   25428   }
   25429 }
   25430 
   25431 /*
   25432 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
   25433 */
   25434 static void closePendingFds(unixFile *pFile){
   25435   unixInodeInfo *pInode = pFile->pInode;
   25436   UnixUnusedFd *p;
   25437   UnixUnusedFd *pNext;
   25438   for(p=pInode->pUnused; p; p=pNext){
   25439     pNext = p->pNext;
   25440     robust_close(pFile, p->fd, __LINE__);
   25441     sqlite3_free(p);
   25442   }
   25443   pInode->pUnused = 0;
   25444 }
   25445 
   25446 /*
   25447 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
   25448 **
   25449 ** The mutex entered using the unixEnterMutex() function must be held
   25450 ** when this function is called.
   25451 */
   25452 static void releaseInodeInfo(unixFile *pFile){
   25453   unixInodeInfo *pInode = pFile->pInode;
   25454   assert( unixMutexHeld() );
   25455   if( ALWAYS(pInode) ){
   25456     pInode->nRef--;
   25457     if( pInode->nRef==0 ){
   25458       assert( pInode->pShmNode==0 );
   25459       closePendingFds(pFile);
   25460       if( pInode->pPrev ){
   25461         assert( pInode->pPrev->pNext==pInode );
   25462         pInode->pPrev->pNext = pInode->pNext;
   25463       }else{
   25464         assert( inodeList==pInode );
   25465         inodeList = pInode->pNext;
   25466       }
   25467       if( pInode->pNext ){
   25468         assert( pInode->pNext->pPrev==pInode );
   25469         pInode->pNext->pPrev = pInode->pPrev;
   25470       }
   25471       sqlite3_free(pInode);
   25472     }
   25473   }
   25474 }
   25475 
   25476 /*
   25477 ** Given a file descriptor, locate the unixInodeInfo object that
   25478 ** describes that file descriptor.  Create a new one if necessary.  The
   25479 ** return value might be uninitialized if an error occurs.
   25480 **
   25481 ** The mutex entered using the unixEnterMutex() function must be held
   25482 ** when this function is called.
   25483 **
   25484 ** Return an appropriate error code.
   25485 */
   25486 static int findInodeInfo(
   25487   unixFile *pFile,               /* Unix file with file desc used in the key */
   25488   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
   25489 ){
   25490   int rc;                        /* System call return code */
   25491   int fd;                        /* The file descriptor for pFile */
   25492   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
   25493   struct stat statbuf;           /* Low-level file information */
   25494   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
   25495 
   25496   assert( unixMutexHeld() );
   25497 
   25498   /* Get low-level information about the file that we can used to
   25499   ** create a unique name for the file.
   25500   */
   25501   fd = pFile->h;
   25502   rc = osFstat(fd, &statbuf);
   25503   if( rc!=0 ){
   25504     pFile->lastErrno = errno;
   25505 #ifdef EOVERFLOW
   25506     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
   25507 #endif
   25508     return SQLITE_IOERR;
   25509   }
   25510 
   25511 #ifdef __APPLE__
   25512   /* On OS X on an msdos filesystem, the inode number is reported
   25513   ** incorrectly for zero-size files.  See ticket #3260.  To work
   25514   ** around this problem (we consider it a bug in OS X, not SQLite)
   25515   ** we always increase the file size to 1 by writing a single byte
   25516   ** prior to accessing the inode number.  The one byte written is
   25517   ** an ASCII 'S' character which also happens to be the first byte
   25518   ** in the header of every SQLite database.  In this way, if there
   25519   ** is a race condition such that another thread has already populated
   25520   ** the first page of the database, no damage is done.
   25521   */
   25522   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
   25523     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
   25524     if( rc!=1 ){
   25525       pFile->lastErrno = errno;
   25526       return SQLITE_IOERR;
   25527     }
   25528     rc = osFstat(fd, &statbuf);
   25529     if( rc!=0 ){
   25530       pFile->lastErrno = errno;
   25531       return SQLITE_IOERR;
   25532     }
   25533   }
   25534 #endif
   25535 
   25536   memset(&fileId, 0, sizeof(fileId));
   25537   fileId.dev = statbuf.st_dev;
   25538 #if OS_VXWORKS
   25539   fileId.pId = pFile->pId;
   25540 #else
   25541   fileId.ino = statbuf.st_ino;
   25542 #endif
   25543   pInode = inodeList;
   25544   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
   25545     pInode = pInode->pNext;
   25546   }
   25547   if( pInode==0 ){
   25548     pInode = sqlite3_malloc( sizeof(*pInode) );
   25549     if( pInode==0 ){
   25550       return SQLITE_NOMEM;
   25551     }
   25552     memset(pInode, 0, sizeof(*pInode));
   25553     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
   25554     pInode->nRef = 1;
   25555     pInode->pNext = inodeList;
   25556     pInode->pPrev = 0;
   25557     if( inodeList ) inodeList->pPrev = pInode;
   25558     inodeList = pInode;
   25559   }else{
   25560     pInode->nRef++;
   25561   }
   25562   *ppInode = pInode;
   25563   return SQLITE_OK;
   25564 }
   25565 
   25566 /*
   25567 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
   25568 */
   25569 static int fileHasMoved(unixFile *pFile){
   25570 #if OS_VXWORKS
   25571   return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
   25572 #else
   25573   struct stat buf;
   25574   return pFile->pInode!=0 &&
   25575       (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
   25576 #endif
   25577 }
   25578 
   25579 
   25580 /*
   25581 ** Check a unixFile that is a database.  Verify the following:
   25582 **
   25583 ** (1) There is exactly one hard link on the file
   25584 ** (2) The file is not a symbolic link
   25585 ** (3) The file has not been renamed or unlinked
   25586 **
   25587 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
   25588 */
   25589 static void verifyDbFile(unixFile *pFile){
   25590   struct stat buf;
   25591   int rc;
   25592   if( pFile->ctrlFlags & UNIXFILE_WARNED ){
   25593     /* One or more of the following warnings have already been issued.  Do not
   25594     ** repeat them so as not to clutter the error log */
   25595     return;
   25596   }
   25597   rc = osFstat(pFile->h, &buf);
   25598   if( rc!=0 ){
   25599     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
   25600     pFile->ctrlFlags |= UNIXFILE_WARNED;
   25601     return;
   25602   }
   25603   if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
   25604     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
   25605     pFile->ctrlFlags |= UNIXFILE_WARNED;
   25606     return;
   25607   }
   25608   if( buf.st_nlink>1 ){
   25609     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
   25610     pFile->ctrlFlags |= UNIXFILE_WARNED;
   25611     return;
   25612   }
   25613   if( fileHasMoved(pFile) ){
   25614     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
   25615     pFile->ctrlFlags |= UNIXFILE_WARNED;
   25616     return;
   25617   }
   25618 }
   25619 
   25620 
   25621 /*
   25622 ** This routine checks if there is a RESERVED lock held on the specified
   25623 ** file by this or any other process. If such a lock is held, set *pResOut
   25624 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   25625 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   25626 */
   25627 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   25628   int rc = SQLITE_OK;
   25629   int reserved = 0;
   25630   unixFile *pFile = (unixFile*)id;
   25631 
   25632   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   25633 
   25634   assert( pFile );
   25635   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   25636 
   25637   /* Check if a thread in this process holds such a lock */
   25638   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   25639     reserved = 1;
   25640   }
   25641 
   25642   /* Otherwise see if some other process holds it.
   25643   */
   25644 #ifndef __DJGPP__
   25645   if( !reserved && !pFile->pInode->bProcessLock ){
   25646     struct flock lock;
   25647     lock.l_whence = SEEK_SET;
   25648     lock.l_start = RESERVED_BYTE;
   25649     lock.l_len = 1;
   25650     lock.l_type = F_WRLCK;
   25651     if( osFcntl(pFile->h, F_GETLK, &lock) ){
   25652       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
   25653       pFile->lastErrno = errno;
   25654     } else if( lock.l_type!=F_UNLCK ){
   25655       reserved = 1;
   25656     }
   25657   }
   25658 #endif
   25659 
   25660   unixLeaveMutex();
   25661   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
   25662 
   25663   *pResOut = reserved;
   25664   return rc;
   25665 }
   25666 
   25667 /*
   25668 ** Attempt to set a system-lock on the file pFile.  The lock is
   25669 ** described by pLock.
   25670 **
   25671 ** If the pFile was opened read/write from unix-excl, then the only lock
   25672 ** ever obtained is an exclusive lock, and it is obtained exactly once
   25673 ** the first time any lock is attempted.  All subsequent system locking
   25674 ** operations become no-ops.  Locking operations still happen internally,
   25675 ** in order to coordinate access between separate database connections
   25676 ** within this process, but all of that is handled in memory and the
   25677 ** operating system does not participate.
   25678 **
   25679 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
   25680 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
   25681 ** and is read-only.
   25682 **
   25683 ** Zero is returned if the call completes successfully, or -1 if a call
   25684 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
   25685 */
   25686 static int unixFileLock(unixFile *pFile, struct flock *pLock){
   25687   int rc;
   25688   unixInodeInfo *pInode = pFile->pInode;
   25689   assert( unixMutexHeld() );
   25690   assert( pInode!=0 );
   25691   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
   25692    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
   25693   ){
   25694     if( pInode->bProcessLock==0 ){
   25695       struct flock lock;
   25696       assert( pInode->nLock==0 );
   25697       lock.l_whence = SEEK_SET;
   25698       lock.l_start = SHARED_FIRST;
   25699       lock.l_len = SHARED_SIZE;
   25700       lock.l_type = F_WRLCK;
   25701       rc = osFcntl(pFile->h, F_SETLK, &lock);
   25702       if( rc<0 ) return rc;
   25703       pInode->bProcessLock = 1;
   25704       pInode->nLock++;
   25705     }else{
   25706       rc = 0;
   25707     }
   25708   }else{
   25709     rc = osFcntl(pFile->h, F_SETLK, pLock);
   25710   }
   25711   return rc;
   25712 }
   25713 
   25714 /*
   25715 ** Lock the file with the lock specified by parameter eFileLock - one
   25716 ** of the following:
   25717 **
   25718 **     (1) SHARED_LOCK
   25719 **     (2) RESERVED_LOCK
   25720 **     (3) PENDING_LOCK
   25721 **     (4) EXCLUSIVE_LOCK
   25722 **
   25723 ** Sometimes when requesting one lock state, additional lock states
   25724 ** are inserted in between.  The locking might fail on one of the later
   25725 ** transitions leaving the lock state different from what it started but
   25726 ** still short of its goal.  The following chart shows the allowed
   25727 ** transitions and the inserted intermediate states:
   25728 **
   25729 **    UNLOCKED -> SHARED
   25730 **    SHARED -> RESERVED
   25731 **    SHARED -> (PENDING) -> EXCLUSIVE
   25732 **    RESERVED -> (PENDING) -> EXCLUSIVE
   25733 **    PENDING -> EXCLUSIVE
   25734 **
   25735 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   25736 ** routine to lower a locking level.
   25737 */
   25738 static int unixLock(sqlite3_file *id, int eFileLock){
   25739   /* The following describes the implementation of the various locks and
   25740   ** lock transitions in terms of the POSIX advisory shared and exclusive
   25741   ** lock primitives (called read-locks and write-locks below, to avoid
   25742   ** confusion with SQLite lock names). The algorithms are complicated
   25743   ** slightly in order to be compatible with windows systems simultaneously
   25744   ** accessing the same database file, in case that is ever required.
   25745   **
   25746   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
   25747   ** byte', each single bytes at well known offsets, and the 'shared byte
   25748   ** range', a range of 510 bytes at a well known offset.
   25749   **
   25750   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
   25751   ** byte'.  If this is successful, a random byte from the 'shared byte
   25752   ** range' is read-locked and the lock on the 'pending byte' released.
   25753   **
   25754   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   25755   ** A RESERVED lock is implemented by grabbing a write-lock on the
   25756   ** 'reserved byte'.
   25757   **
   25758   ** A process may only obtain a PENDING lock after it has obtained a
   25759   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
   25760   ** on the 'pending byte'. This ensures that no new SHARED locks can be
   25761   ** obtained, but existing SHARED locks are allowed to persist. A process
   25762   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
   25763   ** This property is used by the algorithm for rolling back a journal file
   25764   ** after a crash.
   25765   **
   25766   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
   25767   ** implemented by obtaining a write-lock on the entire 'shared byte
   25768   ** range'. Since all other locks require a read-lock on one of the bytes
   25769   ** within this range, this ensures that no other locks are held on the
   25770   ** database.
   25771   **
   25772   ** The reason a single byte cannot be used instead of the 'shared byte
   25773   ** range' is that some versions of windows do not support read-locks. By
   25774   ** locking a random byte from a range, concurrent SHARED locks may exist
   25775   ** even if the locking primitive used is always a write-lock.
   25776   */
   25777   int rc = SQLITE_OK;
   25778   unixFile *pFile = (unixFile*)id;
   25779   unixInodeInfo *pInode;
   25780   struct flock lock;
   25781   int tErrno = 0;
   25782 
   25783   assert( pFile );
   25784   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
   25785       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   25786       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
   25787 
   25788   /* If there is already a lock of this type or more restrictive on the
   25789   ** unixFile, do nothing. Don't use the end_lock: exit path, as
   25790   ** unixEnterMutex() hasn't been called yet.
   25791   */
   25792   if( pFile->eFileLock>=eFileLock ){
   25793     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
   25794             azFileLock(eFileLock)));
   25795     return SQLITE_OK;
   25796   }
   25797 
   25798   /* Make sure the locking sequence is correct.
   25799   **  (1) We never move from unlocked to anything higher than shared lock.
   25800   **  (2) SQLite never explicitly requests a pendig lock.
   25801   **  (3) A shared lock is always held when a reserve lock is requested.
   25802   */
   25803   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   25804   assert( eFileLock!=PENDING_LOCK );
   25805   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   25806 
   25807   /* This mutex is needed because pFile->pInode is shared across threads
   25808   */
   25809   unixEnterMutex();
   25810   pInode = pFile->pInode;
   25811 
   25812   /* If some thread using this PID has a lock via a different unixFile*
   25813   ** handle that precludes the requested lock, return BUSY.
   25814   */
   25815   if( (pFile->eFileLock!=pInode->eFileLock &&
   25816           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   25817   ){
   25818     rc = SQLITE_BUSY;
   25819     goto end_lock;
   25820   }
   25821 
   25822   /* If a SHARED lock is requested, and some thread using this PID already
   25823   ** has a SHARED or RESERVED lock, then increment reference counts and
   25824   ** return SQLITE_OK.
   25825   */
   25826   if( eFileLock==SHARED_LOCK &&
   25827       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   25828     assert( eFileLock==SHARED_LOCK );
   25829     assert( pFile->eFileLock==0 );
   25830     assert( pInode->nShared>0 );
   25831     pFile->eFileLock = SHARED_LOCK;
   25832     pInode->nShared++;
   25833     pInode->nLock++;
   25834     goto end_lock;
   25835   }
   25836 
   25837 
   25838   /* A PENDING lock is needed before acquiring a SHARED lock and before
   25839   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   25840   ** be released.
   25841   */
   25842   lock.l_len = 1L;
   25843   lock.l_whence = SEEK_SET;
   25844   if( eFileLock==SHARED_LOCK
   25845       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   25846   ){
   25847     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
   25848     lock.l_start = PENDING_BYTE;
   25849     if( unixFileLock(pFile, &lock) ){
   25850       tErrno = errno;
   25851       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   25852       if( rc!=SQLITE_BUSY ){
   25853         pFile->lastErrno = tErrno;
   25854       }
   25855       goto end_lock;
   25856     }
   25857   }
   25858 
   25859 
   25860   /* If control gets to this point, then actually go ahead and make
   25861   ** operating system calls for the specified lock.
   25862   */
   25863   if( eFileLock==SHARED_LOCK ){
   25864     assert( pInode->nShared==0 );
   25865     assert( pInode->eFileLock==0 );
   25866     assert( rc==SQLITE_OK );
   25867 
   25868     /* Now get the read-lock */
   25869     lock.l_start = SHARED_FIRST;
   25870     lock.l_len = SHARED_SIZE;
   25871     if( unixFileLock(pFile, &lock) ){
   25872       tErrno = errno;
   25873       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   25874     }
   25875 
   25876     /* Drop the temporary PENDING lock */
   25877     lock.l_start = PENDING_BYTE;
   25878     lock.l_len = 1L;
   25879     lock.l_type = F_UNLCK;
   25880     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
   25881       /* This could happen with a network mount */
   25882       tErrno = errno;
   25883       rc = SQLITE_IOERR_UNLOCK;
   25884     }
   25885 
   25886     if( rc ){
   25887       if( rc!=SQLITE_BUSY ){
   25888         pFile->lastErrno = tErrno;
   25889       }
   25890       goto end_lock;
   25891     }else{
   25892       pFile->eFileLock = SHARED_LOCK;
   25893       pInode->nLock++;
   25894       pInode->nShared = 1;
   25895     }
   25896   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   25897     /* We are trying for an exclusive lock but another thread in this
   25898     ** same process is still holding a shared lock. */
   25899     rc = SQLITE_BUSY;
   25900   }else{
   25901     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   25902     ** assumed that there is a SHARED or greater lock on the file
   25903     ** already.
   25904     */
   25905     assert( 0!=pFile->eFileLock );
   25906     lock.l_type = F_WRLCK;
   25907 
   25908     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
   25909     if( eFileLock==RESERVED_LOCK ){
   25910       lock.l_start = RESERVED_BYTE;
   25911       lock.l_len = 1L;
   25912     }else{
   25913       lock.l_start = SHARED_FIRST;
   25914       lock.l_len = SHARED_SIZE;
   25915     }
   25916 
   25917     if( unixFileLock(pFile, &lock) ){
   25918       tErrno = errno;
   25919       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   25920       if( rc!=SQLITE_BUSY ){
   25921         pFile->lastErrno = tErrno;
   25922       }
   25923     }
   25924   }
   25925 
   25926 
   25927 #ifdef SQLITE_DEBUG
   25928   /* Set up the transaction-counter change checking flags when
   25929   ** transitioning from a SHARED to a RESERVED lock.  The change
   25930   ** from SHARED to RESERVED marks the beginning of a normal
   25931   ** write operation (not a hot journal rollback).
   25932   */
   25933   if( rc==SQLITE_OK
   25934    && pFile->eFileLock<=SHARED_LOCK
   25935    && eFileLock==RESERVED_LOCK
   25936   ){
   25937     pFile->transCntrChng = 0;
   25938     pFile->dbUpdate = 0;
   25939     pFile->inNormalWrite = 1;
   25940   }
   25941 #endif
   25942 
   25943 
   25944   if( rc==SQLITE_OK ){
   25945     pFile->eFileLock = eFileLock;
   25946     pInode->eFileLock = eFileLock;
   25947   }else if( eFileLock==EXCLUSIVE_LOCK ){
   25948     pFile->eFileLock = PENDING_LOCK;
   25949     pInode->eFileLock = PENDING_LOCK;
   25950   }
   25951 
   25952 end_lock:
   25953   unixLeaveMutex();
   25954   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
   25955       rc==SQLITE_OK ? "ok" : "failed"));
   25956   return rc;
   25957 }
   25958 
   25959 /*
   25960 ** Add the file descriptor used by file handle pFile to the corresponding
   25961 ** pUnused list.
   25962 */
   25963 static void setPendingFd(unixFile *pFile){
   25964   unixInodeInfo *pInode = pFile->pInode;
   25965   UnixUnusedFd *p = pFile->pUnused;
   25966   p->pNext = pInode->pUnused;
   25967   pInode->pUnused = p;
   25968   pFile->h = -1;
   25969   pFile->pUnused = 0;
   25970 }
   25971 
   25972 /*
   25973 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   25974 ** must be either NO_LOCK or SHARED_LOCK.
   25975 **
   25976 ** If the locking level of the file descriptor is already at or below
   25977 ** the requested locking level, this routine is a no-op.
   25978 **
   25979 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
   25980 ** the byte range is divided into 2 parts and the first part is unlocked then
   25981 ** set to a read lock, then the other part is simply unlocked.  This works
   25982 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
   25983 ** remove the write lock on a region when a read lock is set.
   25984 */
   25985 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
   25986   unixFile *pFile = (unixFile*)id;
   25987   unixInodeInfo *pInode;
   25988   struct flock lock;
   25989   int rc = SQLITE_OK;
   25990 
   25991   assert( pFile );
   25992   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
   25993       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   25994       getpid()));
   25995 
   25996   assert( eFileLock<=SHARED_LOCK );
   25997   if( pFile->eFileLock<=eFileLock ){
   25998     return SQLITE_OK;
   25999   }
   26000   unixEnterMutex();
   26001   pInode = pFile->pInode;
   26002   assert( pInode->nShared!=0 );
   26003   if( pFile->eFileLock>SHARED_LOCK ){
   26004     assert( pInode->eFileLock==pFile->eFileLock );
   26005 
   26006 #ifdef SQLITE_DEBUG
   26007     /* When reducing a lock such that other processes can start
   26008     ** reading the database file again, make sure that the
   26009     ** transaction counter was updated if any part of the database
   26010     ** file changed.  If the transaction counter is not updated,
   26011     ** other connections to the same file might not realize that
   26012     ** the file has changed and hence might not know to flush their
   26013     ** cache.  The use of a stale cache can lead to database corruption.
   26014     */
   26015     pFile->inNormalWrite = 0;
   26016 #endif
   26017 
   26018     /* downgrading to a shared lock on NFS involves clearing the write lock
   26019     ** before establishing the readlock - to avoid a race condition we downgrade
   26020     ** the lock in 2 blocks, so that part of the range will be covered by a
   26021     ** write lock until the rest is covered by a read lock:
   26022     **  1:   [WWWWW]
   26023     **  2:   [....W]
   26024     **  3:   [RRRRW]
   26025     **  4:   [RRRR.]
   26026     */
   26027     if( eFileLock==SHARED_LOCK ){
   26028 
   26029 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
   26030       (void)handleNFSUnlock;
   26031       assert( handleNFSUnlock==0 );
   26032 #endif
   26033 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   26034       if( handleNFSUnlock ){
   26035         int tErrno;               /* Error code from system call errors */
   26036         off_t divSize = SHARED_SIZE - 1;
   26037 
   26038         lock.l_type = F_UNLCK;
   26039         lock.l_whence = SEEK_SET;
   26040         lock.l_start = SHARED_FIRST;
   26041         lock.l_len = divSize;
   26042         if( unixFileLock(pFile, &lock)==(-1) ){
   26043           tErrno = errno;
   26044           rc = SQLITE_IOERR_UNLOCK;
   26045           if( IS_LOCK_ERROR(rc) ){
   26046             pFile->lastErrno = tErrno;
   26047           }
   26048           goto end_unlock;
   26049         }
   26050         lock.l_type = F_RDLCK;
   26051         lock.l_whence = SEEK_SET;
   26052         lock.l_start = SHARED_FIRST;
   26053         lock.l_len = divSize;
   26054         if( unixFileLock(pFile, &lock)==(-1) ){
   26055           tErrno = errno;
   26056           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   26057           if( IS_LOCK_ERROR(rc) ){
   26058             pFile->lastErrno = tErrno;
   26059           }
   26060           goto end_unlock;
   26061         }
   26062         lock.l_type = F_UNLCK;
   26063         lock.l_whence = SEEK_SET;
   26064         lock.l_start = SHARED_FIRST+divSize;
   26065         lock.l_len = SHARED_SIZE-divSize;
   26066         if( unixFileLock(pFile, &lock)==(-1) ){
   26067           tErrno = errno;
   26068           rc = SQLITE_IOERR_UNLOCK;
   26069           if( IS_LOCK_ERROR(rc) ){
   26070             pFile->lastErrno = tErrno;
   26071           }
   26072           goto end_unlock;
   26073         }
   26074       }else
   26075 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   26076       {
   26077         lock.l_type = F_RDLCK;
   26078         lock.l_whence = SEEK_SET;
   26079         lock.l_start = SHARED_FIRST;
   26080         lock.l_len = SHARED_SIZE;
   26081         if( unixFileLock(pFile, &lock) ){
   26082           /* In theory, the call to unixFileLock() cannot fail because another
   26083           ** process is holding an incompatible lock. If it does, this
   26084           ** indicates that the other process is not following the locking
   26085           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
   26086           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
   26087           ** an assert to fail). */
   26088           rc = SQLITE_IOERR_RDLOCK;
   26089           pFile->lastErrno = errno;
   26090           goto end_unlock;
   26091         }
   26092       }
   26093     }
   26094     lock.l_type = F_UNLCK;
   26095     lock.l_whence = SEEK_SET;
   26096     lock.l_start = PENDING_BYTE;
   26097     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
   26098     if( unixFileLock(pFile, &lock)==0 ){
   26099       pInode->eFileLock = SHARED_LOCK;
   26100     }else{
   26101       rc = SQLITE_IOERR_UNLOCK;
   26102       pFile->lastErrno = errno;
   26103       goto end_unlock;
   26104     }
   26105   }
   26106   if( eFileLock==NO_LOCK ){
   26107     /* Decrement the shared lock counter.  Release the lock using an
   26108     ** OS call only when all threads in this same process have released
   26109     ** the lock.
   26110     */
   26111     pInode->nShared--;
   26112     if( pInode->nShared==0 ){
   26113       lock.l_type = F_UNLCK;
   26114       lock.l_whence = SEEK_SET;
   26115       lock.l_start = lock.l_len = 0L;
   26116       if( unixFileLock(pFile, &lock)==0 ){
   26117         pInode->eFileLock = NO_LOCK;
   26118       }else{
   26119         rc = SQLITE_IOERR_UNLOCK;
   26120         pFile->lastErrno = errno;
   26121         pInode->eFileLock = NO_LOCK;
   26122         pFile->eFileLock = NO_LOCK;
   26123       }
   26124     }
   26125 
   26126     /* Decrement the count of locks against this same file.  When the
   26127     ** count reaches zero, close any other file descriptors whose close
   26128     ** was deferred because of outstanding locks.
   26129     */
   26130     pInode->nLock--;
   26131     assert( pInode->nLock>=0 );
   26132     if( pInode->nLock==0 ){
   26133       closePendingFds(pFile);
   26134     }
   26135   }
   26136 
   26137 end_unlock:
   26138   unixLeaveMutex();
   26139   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   26140   return rc;
   26141 }
   26142 
   26143 /*
   26144 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26145 ** must be either NO_LOCK or SHARED_LOCK.
   26146 **
   26147 ** If the locking level of the file descriptor is already at or below
   26148 ** the requested locking level, this routine is a no-op.
   26149 */
   26150 static int unixUnlock(sqlite3_file *id, int eFileLock){
   26151 #if SQLITE_MAX_MMAP_SIZE>0
   26152   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
   26153 #endif
   26154   return posixUnlock(id, eFileLock, 0);
   26155 }
   26156 
   26157 #if SQLITE_MAX_MMAP_SIZE>0
   26158 static int unixMapfile(unixFile *pFd, i64 nByte);
   26159 static void unixUnmapfile(unixFile *pFd);
   26160 #endif
   26161 
   26162 /*
   26163 ** This function performs the parts of the "close file" operation
   26164 ** common to all locking schemes. It closes the directory and file
   26165 ** handles, if they are valid, and sets all fields of the unixFile
   26166 ** structure to 0.
   26167 **
   26168 ** It is *not* necessary to hold the mutex when this routine is called,
   26169 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
   26170 ** vxworksReleaseFileId() routine.
   26171 */
   26172 static int closeUnixFile(sqlite3_file *id){
   26173   unixFile *pFile = (unixFile*)id;
   26174 #if SQLITE_MAX_MMAP_SIZE>0
   26175   unixUnmapfile(pFile);
   26176 #endif
   26177   if( pFile->h>=0 ){
   26178     robust_close(pFile, pFile->h, __LINE__);
   26179     pFile->h = -1;
   26180   }
   26181 #if OS_VXWORKS
   26182   if( pFile->pId ){
   26183     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
   26184       osUnlink(pFile->pId->zCanonicalName);
   26185     }
   26186     vxworksReleaseFileId(pFile->pId);
   26187     pFile->pId = 0;
   26188   }
   26189 #endif
   26190 #ifdef SQLITE_UNLINK_AFTER_CLOSE
   26191   if( pFile->ctrlFlags & UNIXFILE_DELETE ){
   26192     osUnlink(pFile->zPath);
   26193     sqlite3_free(*(char**)&pFile->zPath);
   26194     pFile->zPath = 0;
   26195   }
   26196 #endif
   26197   OSTRACE(("CLOSE   %-3d\n", pFile->h));
   26198   OpenCounter(-1);
   26199   sqlite3_free(pFile->pUnused);
   26200   memset(pFile, 0, sizeof(unixFile));
   26201   return SQLITE_OK;
   26202 }
   26203 
   26204 /*
   26205 ** Close a file.
   26206 */
   26207 static int unixClose(sqlite3_file *id){
   26208   int rc = SQLITE_OK;
   26209   unixFile *pFile = (unixFile *)id;
   26210   verifyDbFile(pFile);
   26211   unixUnlock(id, NO_LOCK);
   26212   unixEnterMutex();
   26213 
   26214   /* unixFile.pInode is always valid here. Otherwise, a different close
   26215   ** routine (e.g. nolockClose()) would be called instead.
   26216   */
   26217   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
   26218   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
   26219     /* If there are outstanding locks, do not actually close the file just
   26220     ** yet because that would clear those locks.  Instead, add the file
   26221     ** descriptor to pInode->pUnused list.  It will be automatically closed
   26222     ** when the last lock is cleared.
   26223     */
   26224     setPendingFd(pFile);
   26225   }
   26226   releaseInodeInfo(pFile);
   26227   rc = closeUnixFile(id);
   26228   unixLeaveMutex();
   26229   return rc;
   26230 }
   26231 
   26232 /************** End of the posix advisory lock implementation *****************
   26233 ******************************************************************************/
   26234 
   26235 /******************************************************************************
   26236 ****************************** No-op Locking **********************************
   26237 **
   26238 ** Of the various locking implementations available, this is by far the
   26239 ** simplest:  locking is ignored.  No attempt is made to lock the database
   26240 ** file for reading or writing.
   26241 **
   26242 ** This locking mode is appropriate for use on read-only databases
   26243 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   26244 ** also be used if the application employs some external mechanism to
   26245 ** prevent simultaneous access of the same database by two or more
   26246 ** database connections.  But there is a serious risk of database
   26247 ** corruption if this locking mode is used in situations where multiple
   26248 ** database connections are accessing the same database file at the same
   26249 ** time and one or more of those connections are writing.
   26250 */
   26251 
   26252 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
   26253   UNUSED_PARAMETER(NotUsed);
   26254   *pResOut = 0;
   26255   return SQLITE_OK;
   26256 }
   26257 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
   26258   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   26259   return SQLITE_OK;
   26260 }
   26261 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
   26262   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   26263   return SQLITE_OK;
   26264 }
   26265 
   26266 /*
   26267 ** Close the file.
   26268 */
   26269 static int nolockClose(sqlite3_file *id) {
   26270   return closeUnixFile(id);
   26271 }
   26272 
   26273 /******************* End of the no-op lock implementation *********************
   26274 ******************************************************************************/
   26275 
   26276 /******************************************************************************
   26277 ************************* Begin dot-file Locking ******************************
   26278 **
   26279 ** The dotfile locking implementation uses the existence of separate lock
   26280 ** files (really a directory) to control access to the database.  This works
   26281 ** on just about every filesystem imaginable.  But there are serious downsides:
   26282 **
   26283 **    (1)  There is zero concurrency.  A single reader blocks all other
   26284 **         connections from reading or writing the database.
   26285 **
   26286 **    (2)  An application crash or power loss can leave stale lock files
   26287 **         sitting around that need to be cleared manually.
   26288 **
   26289 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
   26290 ** other locking strategy is available.
   26291 **
   26292 ** Dotfile locking works by creating a subdirectory in the same directory as
   26293 ** the database and with the same name but with a ".lock" extension added.
   26294 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
   26295 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
   26296 */
   26297 
   26298 /*
   26299 ** The file suffix added to the data base filename in order to create the
   26300 ** lock directory.
   26301 */
   26302 #define DOTLOCK_SUFFIX ".lock"
   26303 
   26304 /*
   26305 ** This routine checks if there is a RESERVED lock held on the specified
   26306 ** file by this or any other process. If such a lock is held, set *pResOut
   26307 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26308 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26309 **
   26310 ** In dotfile locking, either a lock exists or it does not.  So in this
   26311 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
   26312 ** is held on the file and false if the file is unlocked.
   26313 */
   26314 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   26315   int rc = SQLITE_OK;
   26316   int reserved = 0;
   26317   unixFile *pFile = (unixFile*)id;
   26318 
   26319   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26320 
   26321   assert( pFile );
   26322 
   26323   /* Check if a thread in this process holds such a lock */
   26324   if( pFile->eFileLock>SHARED_LOCK ){
   26325     /* Either this connection or some other connection in the same process
   26326     ** holds a lock on the file.  No need to check further. */
   26327     reserved = 1;
   26328   }else{
   26329     /* The lock is held if and only if the lockfile exists */
   26330     const char *zLockFile = (const char*)pFile->lockingContext;
   26331     reserved = osAccess(zLockFile, 0)==0;
   26332   }
   26333   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
   26334   *pResOut = reserved;
   26335   return rc;
   26336 }
   26337 
   26338 /*
   26339 ** Lock the file with the lock specified by parameter eFileLock - one
   26340 ** of the following:
   26341 **
   26342 **     (1) SHARED_LOCK
   26343 **     (2) RESERVED_LOCK
   26344 **     (3) PENDING_LOCK
   26345 **     (4) EXCLUSIVE_LOCK
   26346 **
   26347 ** Sometimes when requesting one lock state, additional lock states
   26348 ** are inserted in between.  The locking might fail on one of the later
   26349 ** transitions leaving the lock state different from what it started but
   26350 ** still short of its goal.  The following chart shows the allowed
   26351 ** transitions and the inserted intermediate states:
   26352 **
   26353 **    UNLOCKED -> SHARED
   26354 **    SHARED -> RESERVED
   26355 **    SHARED -> (PENDING) -> EXCLUSIVE
   26356 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26357 **    PENDING -> EXCLUSIVE
   26358 **
   26359 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26360 ** routine to lower a locking level.
   26361 **
   26362 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
   26363 ** But we track the other locking levels internally.
   26364 */
   26365 static int dotlockLock(sqlite3_file *id, int eFileLock) {
   26366   unixFile *pFile = (unixFile*)id;
   26367   char *zLockFile = (char *)pFile->lockingContext;
   26368   int rc = SQLITE_OK;
   26369 
   26370 
   26371   /* If we have any lock, then the lock file already exists.  All we have
   26372   ** to do is adjust our internal record of the lock level.
   26373   */
   26374   if( pFile->eFileLock > NO_LOCK ){
   26375     pFile->eFileLock = eFileLock;
   26376     /* Always update the timestamp on the old file */
   26377 #ifdef HAVE_UTIME
   26378     utime(zLockFile, NULL);
   26379 #else
   26380     utimes(zLockFile, NULL);
   26381 #endif
   26382     return SQLITE_OK;
   26383   }
   26384 
   26385   /* grab an exclusive lock */
   26386   rc = osMkdir(zLockFile, 0777);
   26387   if( rc<0 ){
   26388     /* failed to open/create the lock directory */
   26389     int tErrno = errno;
   26390     if( EEXIST == tErrno ){
   26391       rc = SQLITE_BUSY;
   26392     } else {
   26393       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26394       if( IS_LOCK_ERROR(rc) ){
   26395         pFile->lastErrno = tErrno;
   26396       }
   26397     }
   26398     return rc;
   26399   }
   26400 
   26401   /* got it, set the type and return ok */
   26402   pFile->eFileLock = eFileLock;
   26403   return rc;
   26404 }
   26405 
   26406 /*
   26407 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26408 ** must be either NO_LOCK or SHARED_LOCK.
   26409 **
   26410 ** If the locking level of the file descriptor is already at or below
   26411 ** the requested locking level, this routine is a no-op.
   26412 **
   26413 ** When the locking level reaches NO_LOCK, delete the lock file.
   26414 */
   26415 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
   26416   unixFile *pFile = (unixFile*)id;
   26417   char *zLockFile = (char *)pFile->lockingContext;
   26418   int rc;
   26419 
   26420   assert( pFile );
   26421   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
   26422            pFile->eFileLock, getpid()));
   26423   assert( eFileLock<=SHARED_LOCK );
   26424 
   26425   /* no-op if possible */
   26426   if( pFile->eFileLock==eFileLock ){
   26427     return SQLITE_OK;
   26428   }
   26429 
   26430   /* To downgrade to shared, simply update our internal notion of the
   26431   ** lock state.  No need to mess with the file on disk.
   26432   */
   26433   if( eFileLock==SHARED_LOCK ){
   26434     pFile->eFileLock = SHARED_LOCK;
   26435     return SQLITE_OK;
   26436   }
   26437 
   26438   /* To fully unlock the database, delete the lock file */
   26439   assert( eFileLock==NO_LOCK );
   26440   rc = osRmdir(zLockFile);
   26441   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
   26442   if( rc<0 ){
   26443     int tErrno = errno;
   26444     rc = 0;
   26445     if( ENOENT != tErrno ){
   26446       rc = SQLITE_IOERR_UNLOCK;
   26447     }
   26448     if( IS_LOCK_ERROR(rc) ){
   26449       pFile->lastErrno = tErrno;
   26450     }
   26451     return rc;
   26452   }
   26453   pFile->eFileLock = NO_LOCK;
   26454   return SQLITE_OK;
   26455 }
   26456 
   26457 /*
   26458 ** Close a file.  Make sure the lock has been released before closing.
   26459 */
   26460 static int dotlockClose(sqlite3_file *id) {
   26461   int rc = SQLITE_OK;
   26462   if( id ){
   26463     unixFile *pFile = (unixFile*)id;
   26464     dotlockUnlock(id, NO_LOCK);
   26465     sqlite3_free(pFile->lockingContext);
   26466     rc = closeUnixFile(id);
   26467   }
   26468   return rc;
   26469 }
   26470 /****************** End of the dot-file lock implementation *******************
   26471 ******************************************************************************/
   26472 
   26473 /******************************************************************************
   26474 ************************** Begin flock Locking ********************************
   26475 **
   26476 ** Use the flock() system call to do file locking.
   26477 **
   26478 ** flock() locking is like dot-file locking in that the various
   26479 ** fine-grain locking levels supported by SQLite are collapsed into
   26480 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
   26481 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
   26482 ** still works when you do this, but concurrency is reduced since
   26483 ** only a single process can be reading the database at a time.
   26484 **
   26485 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
   26486 ** compiling for VXWORKS.
   26487 */
   26488 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   26489 
   26490 /*
   26491 ** Retry flock() calls that fail with EINTR
   26492 */
   26493 #ifdef EINTR
   26494 static int robust_flock(int fd, int op){
   26495   int rc;
   26496   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
   26497   return rc;
   26498 }
   26499 #else
   26500 # define robust_flock(a,b) flock(a,b)
   26501 #endif
   26502 
   26503 
   26504 /*
   26505 ** This routine checks if there is a RESERVED lock held on the specified
   26506 ** file by this or any other process. If such a lock is held, set *pResOut
   26507 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26508 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26509 */
   26510 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   26511   int rc = SQLITE_OK;
   26512   int reserved = 0;
   26513   unixFile *pFile = (unixFile*)id;
   26514 
   26515   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26516 
   26517   assert( pFile );
   26518 
   26519   /* Check if a thread in this process holds such a lock */
   26520   if( pFile->eFileLock>SHARED_LOCK ){
   26521     reserved = 1;
   26522   }
   26523 
   26524   /* Otherwise see if some other process holds it. */
   26525   if( !reserved ){
   26526     /* attempt to get the lock */
   26527     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
   26528     if( !lrc ){
   26529       /* got the lock, unlock it */
   26530       lrc = robust_flock(pFile->h, LOCK_UN);
   26531       if ( lrc ) {
   26532         int tErrno = errno;
   26533         /* unlock failed with an error */
   26534         lrc = SQLITE_IOERR_UNLOCK;
   26535         if( IS_LOCK_ERROR(lrc) ){
   26536           pFile->lastErrno = tErrno;
   26537           rc = lrc;
   26538         }
   26539       }
   26540     } else {
   26541       int tErrno = errno;
   26542       reserved = 1;
   26543       /* someone else might have it reserved */
   26544       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26545       if( IS_LOCK_ERROR(lrc) ){
   26546         pFile->lastErrno = tErrno;
   26547         rc = lrc;
   26548       }
   26549     }
   26550   }
   26551   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
   26552 
   26553 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   26554   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   26555     rc = SQLITE_OK;
   26556     reserved=1;
   26557   }
   26558 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   26559   *pResOut = reserved;
   26560   return rc;
   26561 }
   26562 
   26563 /*
   26564 ** Lock the file with the lock specified by parameter eFileLock - one
   26565 ** of the following:
   26566 **
   26567 **     (1) SHARED_LOCK
   26568 **     (2) RESERVED_LOCK
   26569 **     (3) PENDING_LOCK
   26570 **     (4) EXCLUSIVE_LOCK
   26571 **
   26572 ** Sometimes when requesting one lock state, additional lock states
   26573 ** are inserted in between.  The locking might fail on one of the later
   26574 ** transitions leaving the lock state different from what it started but
   26575 ** still short of its goal.  The following chart shows the allowed
   26576 ** transitions and the inserted intermediate states:
   26577 **
   26578 **    UNLOCKED -> SHARED
   26579 **    SHARED -> RESERVED
   26580 **    SHARED -> (PENDING) -> EXCLUSIVE
   26581 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26582 **    PENDING -> EXCLUSIVE
   26583 **
   26584 ** flock() only really support EXCLUSIVE locks.  We track intermediate
   26585 ** lock states in the sqlite3_file structure, but all locks SHARED or
   26586 ** above are really EXCLUSIVE locks and exclude all other processes from
   26587 ** access the file.
   26588 **
   26589 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26590 ** routine to lower a locking level.
   26591 */
   26592 static int flockLock(sqlite3_file *id, int eFileLock) {
   26593   int rc = SQLITE_OK;
   26594   unixFile *pFile = (unixFile*)id;
   26595 
   26596   assert( pFile );
   26597 
   26598   /* if we already have a lock, it is exclusive.
   26599   ** Just adjust level and punt on outta here. */
   26600   if (pFile->eFileLock > NO_LOCK) {
   26601     pFile->eFileLock = eFileLock;
   26602     return SQLITE_OK;
   26603   }
   26604 
   26605   /* grab an exclusive lock */
   26606 
   26607   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
   26608     int tErrno = errno;
   26609     /* didn't get, must be busy */
   26610     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26611     if( IS_LOCK_ERROR(rc) ){
   26612       pFile->lastErrno = tErrno;
   26613     }
   26614   } else {
   26615     /* got it, set the type and return ok */
   26616     pFile->eFileLock = eFileLock;
   26617   }
   26618   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
   26619            rc==SQLITE_OK ? "ok" : "failed"));
   26620 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   26621   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   26622     rc = SQLITE_BUSY;
   26623   }
   26624 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   26625   return rc;
   26626 }
   26627 
   26628 
   26629 /*
   26630 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26631 ** must be either NO_LOCK or SHARED_LOCK.
   26632 **
   26633 ** If the locking level of the file descriptor is already at or below
   26634 ** the requested locking level, this routine is a no-op.
   26635 */
   26636 static int flockUnlock(sqlite3_file *id, int eFileLock) {
   26637   unixFile *pFile = (unixFile*)id;
   26638 
   26639   assert( pFile );
   26640   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
   26641            pFile->eFileLock, getpid()));
   26642   assert( eFileLock<=SHARED_LOCK );
   26643 
   26644   /* no-op if possible */
   26645   if( pFile->eFileLock==eFileLock ){
   26646     return SQLITE_OK;
   26647   }
   26648 
   26649   /* shared can just be set because we always have an exclusive */
   26650   if (eFileLock==SHARED_LOCK) {
   26651     pFile->eFileLock = eFileLock;
   26652     return SQLITE_OK;
   26653   }
   26654 
   26655   /* no, really, unlock. */
   26656   if( robust_flock(pFile->h, LOCK_UN) ){
   26657 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   26658     return SQLITE_OK;
   26659 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   26660     return SQLITE_IOERR_UNLOCK;
   26661   }else{
   26662     pFile->eFileLock = NO_LOCK;
   26663     return SQLITE_OK;
   26664   }
   26665 }
   26666 
   26667 /*
   26668 ** Close a file.
   26669 */
   26670 static int flockClose(sqlite3_file *id) {
   26671   int rc = SQLITE_OK;
   26672   if( id ){
   26673     flockUnlock(id, NO_LOCK);
   26674     rc = closeUnixFile(id);
   26675   }
   26676   return rc;
   26677 }
   26678 
   26679 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
   26680 
   26681 /******************* End of the flock lock implementation *********************
   26682 ******************************************************************************/
   26683 
   26684 /******************************************************************************
   26685 ************************ Begin Named Semaphore Locking ************************
   26686 **
   26687 ** Named semaphore locking is only supported on VxWorks.
   26688 **
   26689 ** Semaphore locking is like dot-lock and flock in that it really only
   26690 ** supports EXCLUSIVE locking.  Only a single process can read or write
   26691 ** the database file at a time.  This reduces potential concurrency, but
   26692 ** makes the lock implementation much easier.
   26693 */
   26694 #if OS_VXWORKS
   26695 
   26696 /*
   26697 ** This routine checks if there is a RESERVED lock held on the specified
   26698 ** file by this or any other process. If such a lock is held, set *pResOut
   26699 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26700 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26701 */
   26702 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
   26703   int rc = SQLITE_OK;
   26704   int reserved = 0;
   26705   unixFile *pFile = (unixFile*)id;
   26706 
   26707   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26708 
   26709   assert( pFile );
   26710 
   26711   /* Check if a thread in this process holds such a lock */
   26712   if( pFile->eFileLock>SHARED_LOCK ){
   26713     reserved = 1;
   26714   }
   26715 
   26716   /* Otherwise see if some other process holds it. */
   26717   if( !reserved ){
   26718     sem_t *pSem = pFile->pInode->pSem;
   26719 
   26720     if( sem_trywait(pSem)==-1 ){
   26721       int tErrno = errno;
   26722       if( EAGAIN != tErrno ){
   26723         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   26724         pFile->lastErrno = tErrno;
   26725       } else {
   26726         /* someone else has the lock when we are in NO_LOCK */
   26727         reserved = (pFile->eFileLock < SHARED_LOCK);
   26728       }
   26729     }else{
   26730       /* we could have it if we want it */
   26731       sem_post(pSem);
   26732     }
   26733   }
   26734   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
   26735 
   26736   *pResOut = reserved;
   26737   return rc;
   26738 }
   26739 
   26740 /*
   26741 ** Lock the file with the lock specified by parameter eFileLock - one
   26742 ** of the following:
   26743 **
   26744 **     (1) SHARED_LOCK
   26745 **     (2) RESERVED_LOCK
   26746 **     (3) PENDING_LOCK
   26747 **     (4) EXCLUSIVE_LOCK
   26748 **
   26749 ** Sometimes when requesting one lock state, additional lock states
   26750 ** are inserted in between.  The locking might fail on one of the later
   26751 ** transitions leaving the lock state different from what it started but
   26752 ** still short of its goal.  The following chart shows the allowed
   26753 ** transitions and the inserted intermediate states:
   26754 **
   26755 **    UNLOCKED -> SHARED
   26756 **    SHARED -> RESERVED
   26757 **    SHARED -> (PENDING) -> EXCLUSIVE
   26758 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26759 **    PENDING -> EXCLUSIVE
   26760 **
   26761 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
   26762 ** lock states in the sqlite3_file structure, but all locks SHARED or
   26763 ** above are really EXCLUSIVE locks and exclude all other processes from
   26764 ** access the file.
   26765 **
   26766 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26767 ** routine to lower a locking level.
   26768 */
   26769 static int semLock(sqlite3_file *id, int eFileLock) {
   26770   unixFile *pFile = (unixFile*)id;
   26771   sem_t *pSem = pFile->pInode->pSem;
   26772   int rc = SQLITE_OK;
   26773 
   26774   /* if we already have a lock, it is exclusive.
   26775   ** Just adjust level and punt on outta here. */
   26776   if (pFile->eFileLock > NO_LOCK) {
   26777     pFile->eFileLock = eFileLock;
   26778     rc = SQLITE_OK;
   26779     goto sem_end_lock;
   26780   }
   26781 
   26782   /* lock semaphore now but bail out when already locked. */
   26783   if( sem_trywait(pSem)==-1 ){
   26784     rc = SQLITE_BUSY;
   26785     goto sem_end_lock;
   26786   }
   26787 
   26788   /* got it, set the type and return ok */
   26789   pFile->eFileLock = eFileLock;
   26790 
   26791  sem_end_lock:
   26792   return rc;
   26793 }
   26794 
   26795 /*
   26796 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26797 ** must be either NO_LOCK or SHARED_LOCK.
   26798 **
   26799 ** If the locking level of the file descriptor is already at or below
   26800 ** the requested locking level, this routine is a no-op.
   26801 */
   26802 static int semUnlock(sqlite3_file *id, int eFileLock) {
   26803   unixFile *pFile = (unixFile*)id;
   26804   sem_t *pSem = pFile->pInode->pSem;
   26805 
   26806   assert( pFile );
   26807   assert( pSem );
   26808   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
   26809            pFile->eFileLock, getpid()));
   26810   assert( eFileLock<=SHARED_LOCK );
   26811 
   26812   /* no-op if possible */
   26813   if( pFile->eFileLock==eFileLock ){
   26814     return SQLITE_OK;
   26815   }
   26816 
   26817   /* shared can just be set because we always have an exclusive */
   26818   if (eFileLock==SHARED_LOCK) {
   26819     pFile->eFileLock = eFileLock;
   26820     return SQLITE_OK;
   26821   }
   26822 
   26823   /* no, really unlock. */
   26824   if ( sem_post(pSem)==-1 ) {
   26825     int rc, tErrno = errno;
   26826     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   26827     if( IS_LOCK_ERROR(rc) ){
   26828       pFile->lastErrno = tErrno;
   26829     }
   26830     return rc;
   26831   }
   26832   pFile->eFileLock = NO_LOCK;
   26833   return SQLITE_OK;
   26834 }
   26835 
   26836 /*
   26837  ** Close a file.
   26838  */
   26839 static int semClose(sqlite3_file *id) {
   26840   if( id ){
   26841     unixFile *pFile = (unixFile*)id;
   26842     semUnlock(id, NO_LOCK);
   26843     assert( pFile );
   26844     unixEnterMutex();
   26845     releaseInodeInfo(pFile);
   26846     unixLeaveMutex();
   26847     closeUnixFile(id);
   26848   }
   26849   return SQLITE_OK;
   26850 }
   26851 
   26852 #endif /* OS_VXWORKS */
   26853 /*
   26854 ** Named semaphore locking is only available on VxWorks.
   26855 **
   26856 *************** End of the named semaphore lock implementation ****************
   26857 ******************************************************************************/
   26858 
   26859 
   26860 /******************************************************************************
   26861 *************************** Begin AFP Locking *********************************
   26862 **
   26863 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
   26864 ** on Apple Macintosh computers - both OS9 and OSX.
   26865 **
   26866 ** Third-party implementations of AFP are available.  But this code here
   26867 ** only works on OSX.
   26868 */
   26869 
   26870 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   26871 /*
   26872 ** The afpLockingContext structure contains all afp lock specific state
   26873 */
   26874 typedef struct afpLockingContext afpLockingContext;
   26875 struct afpLockingContext {
   26876   int reserved;
   26877   const char *dbPath;             /* Name of the open file */
   26878 };
   26879 
   26880 struct ByteRangeLockPB2
   26881 {
   26882   unsigned long long offset;        /* offset to first byte to lock */
   26883   unsigned long long length;        /* nbr of bytes to lock */
   26884   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
   26885   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
   26886   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
   26887   int fd;                           /* file desc to assoc this lock with */
   26888 };
   26889 
   26890 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
   26891 
   26892 /*
   26893 ** This is a utility for setting or clearing a bit-range lock on an
   26894 ** AFP filesystem.
   26895 **
   26896 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
   26897 */
   26898 static int afpSetLock(
   26899   const char *path,              /* Name of the file to be locked or unlocked */
   26900   unixFile *pFile,               /* Open file descriptor on path */
   26901   unsigned long long offset,     /* First byte to be locked */
   26902   unsigned long long length,     /* Number of bytes to lock */
   26903   int setLockFlag                /* True to set lock.  False to clear lock */
   26904 ){
   26905   struct ByteRangeLockPB2 pb;
   26906   int err;
   26907 
   26908   pb.unLockFlag = setLockFlag ? 0 : 1;
   26909   pb.startEndFlag = 0;
   26910   pb.offset = offset;
   26911   pb.length = length;
   26912   pb.fd = pFile->h;
   26913 
   26914   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
   26915     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
   26916     offset, length));
   26917   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
   26918   if ( err==-1 ) {
   26919     int rc;
   26920     int tErrno = errno;
   26921     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
   26922              path, tErrno, strerror(tErrno)));
   26923 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   26924     rc = SQLITE_BUSY;
   26925 #else
   26926     rc = sqliteErrorFromPosixError(tErrno,
   26927                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
   26928 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
   26929     if( IS_LOCK_ERROR(rc) ){
   26930       pFile->lastErrno = tErrno;
   26931     }
   26932     return rc;
   26933   } else {
   26934     return SQLITE_OK;
   26935   }
   26936 }
   26937 
   26938 /*
   26939 ** This routine checks if there is a RESERVED lock held on the specified
   26940 ** file by this or any other process. If such a lock is held, set *pResOut
   26941 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26942 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26943 */
   26944 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   26945   int rc = SQLITE_OK;
   26946   int reserved = 0;
   26947   unixFile *pFile = (unixFile*)id;
   26948   afpLockingContext *context;
   26949 
   26950   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26951 
   26952   assert( pFile );
   26953   context = (afpLockingContext *) pFile->lockingContext;
   26954   if( context->reserved ){
   26955     *pResOut = 1;
   26956     return SQLITE_OK;
   26957   }
   26958   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   26959 
   26960   /* Check if a thread in this process holds such a lock */
   26961   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   26962     reserved = 1;
   26963   }
   26964 
   26965   /* Otherwise see if some other process holds it.
   26966    */
   26967   if( !reserved ){
   26968     /* lock the RESERVED byte */
   26969     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   26970     if( SQLITE_OK==lrc ){
   26971       /* if we succeeded in taking the reserved lock, unlock it to restore
   26972       ** the original state */
   26973       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   26974     } else {
   26975       /* if we failed to get the lock then someone else must have it */
   26976       reserved = 1;
   26977     }
   26978     if( IS_LOCK_ERROR(lrc) ){
   26979       rc=lrc;
   26980     }
   26981   }
   26982 
   26983   unixLeaveMutex();
   26984   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
   26985 
   26986   *pResOut = reserved;
   26987   return rc;
   26988 }
   26989 
   26990 /*
   26991 ** Lock the file with the lock specified by parameter eFileLock - one
   26992 ** of the following:
   26993 **
   26994 **     (1) SHARED_LOCK
   26995 **     (2) RESERVED_LOCK
   26996 **     (3) PENDING_LOCK
   26997 **     (4) EXCLUSIVE_LOCK
   26998 **
   26999 ** Sometimes when requesting one lock state, additional lock states
   27000 ** are inserted in between.  The locking might fail on one of the later
   27001 ** transitions leaving the lock state different from what it started but
   27002 ** still short of its goal.  The following chart shows the allowed
   27003 ** transitions and the inserted intermediate states:
   27004 **
   27005 **    UNLOCKED -> SHARED
   27006 **    SHARED -> RESERVED
   27007 **    SHARED -> (PENDING) -> EXCLUSIVE
   27008 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27009 **    PENDING -> EXCLUSIVE
   27010 **
   27011 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27012 ** routine to lower a locking level.
   27013 */
   27014 static int afpLock(sqlite3_file *id, int eFileLock){
   27015   int rc = SQLITE_OK;
   27016   unixFile *pFile = (unixFile*)id;
   27017   unixInodeInfo *pInode = pFile->pInode;
   27018   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   27019 
   27020   assert( pFile );
   27021   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
   27022            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   27023            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
   27024 
   27025   /* If there is already a lock of this type or more restrictive on the
   27026   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
   27027   ** unixEnterMutex() hasn't been called yet.
   27028   */
   27029   if( pFile->eFileLock>=eFileLock ){
   27030     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
   27031            azFileLock(eFileLock)));
   27032     return SQLITE_OK;
   27033   }
   27034 
   27035   /* Make sure the locking sequence is correct
   27036   **  (1) We never move from unlocked to anything higher than shared lock.
   27037   **  (2) SQLite never explicitly requests a pendig lock.
   27038   **  (3) A shared lock is always held when a reserve lock is requested.
   27039   */
   27040   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   27041   assert( eFileLock!=PENDING_LOCK );
   27042   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   27043 
   27044   /* This mutex is needed because pFile->pInode is shared across threads
   27045   */
   27046   unixEnterMutex();
   27047   pInode = pFile->pInode;
   27048 
   27049   /* If some thread using this PID has a lock via a different unixFile*
   27050   ** handle that precludes the requested lock, return BUSY.
   27051   */
   27052   if( (pFile->eFileLock!=pInode->eFileLock &&
   27053        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   27054      ){
   27055     rc = SQLITE_BUSY;
   27056     goto afp_end_lock;
   27057   }
   27058 
   27059   /* If a SHARED lock is requested, and some thread using this PID already
   27060   ** has a SHARED or RESERVED lock, then increment reference counts and
   27061   ** return SQLITE_OK.
   27062   */
   27063   if( eFileLock==SHARED_LOCK &&
   27064      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   27065     assert( eFileLock==SHARED_LOCK );
   27066     assert( pFile->eFileLock==0 );
   27067     assert( pInode->nShared>0 );
   27068     pFile->eFileLock = SHARED_LOCK;
   27069     pInode->nShared++;
   27070     pInode->nLock++;
   27071     goto afp_end_lock;
   27072   }
   27073 
   27074   /* A PENDING lock is needed before acquiring a SHARED lock and before
   27075   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   27076   ** be released.
   27077   */
   27078   if( eFileLock==SHARED_LOCK
   27079       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   27080   ){
   27081     int failed;
   27082     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
   27083     if (failed) {
   27084       rc = failed;
   27085       goto afp_end_lock;
   27086     }
   27087   }
   27088 
   27089   /* If control gets to this point, then actually go ahead and make
   27090   ** operating system calls for the specified lock.
   27091   */
   27092   if( eFileLock==SHARED_LOCK ){
   27093     int lrc1, lrc2, lrc1Errno = 0;
   27094     long lk, mask;
   27095 
   27096     assert( pInode->nShared==0 );
   27097     assert( pInode->eFileLock==0 );
   27098 
   27099     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
   27100     /* Now get the read-lock SHARED_LOCK */
   27101     /* note that the quality of the randomness doesn't matter that much */
   27102     lk = random();
   27103     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
   27104     lrc1 = afpSetLock(context->dbPath, pFile,
   27105           SHARED_FIRST+pInode->sharedByte, 1, 1);
   27106     if( IS_LOCK_ERROR(lrc1) ){
   27107       lrc1Errno = pFile->lastErrno;
   27108     }
   27109     /* Drop the temporary PENDING lock */
   27110     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   27111 
   27112     if( IS_LOCK_ERROR(lrc1) ) {
   27113       pFile->lastErrno = lrc1Errno;
   27114       rc = lrc1;
   27115       goto afp_end_lock;
   27116     } else if( IS_LOCK_ERROR(lrc2) ){
   27117       rc = lrc2;
   27118       goto afp_end_lock;
   27119     } else if( lrc1 != SQLITE_OK ) {
   27120       rc = lrc1;
   27121     } else {
   27122       pFile->eFileLock = SHARED_LOCK;
   27123       pInode->nLock++;
   27124       pInode->nShared = 1;
   27125     }
   27126   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   27127     /* We are trying for an exclusive lock but another thread in this
   27128      ** same process is still holding a shared lock. */
   27129     rc = SQLITE_BUSY;
   27130   }else{
   27131     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   27132     ** assumed that there is a SHARED or greater lock on the file
   27133     ** already.
   27134     */
   27135     int failed = 0;
   27136     assert( 0!=pFile->eFileLock );
   27137     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
   27138         /* Acquire a RESERVED lock */
   27139         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   27140       if( !failed ){
   27141         context->reserved = 1;
   27142       }
   27143     }
   27144     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
   27145       /* Acquire an EXCLUSIVE lock */
   27146 
   27147       /* Remove the shared lock before trying the range.  we'll need to
   27148       ** reestablish the shared lock if we can't get the  afpUnlock
   27149       */
   27150       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
   27151                          pInode->sharedByte, 1, 0)) ){
   27152         int failed2 = SQLITE_OK;
   27153         /* now attemmpt to get the exclusive lock range */
   27154         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
   27155                                SHARED_SIZE, 1);
   27156         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
   27157                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
   27158           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
   27159           ** a critical I/O error
   27160           */
   27161           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
   27162                SQLITE_IOERR_LOCK;
   27163           goto afp_end_lock;
   27164         }
   27165       }else{
   27166         rc = failed;
   27167       }
   27168     }
   27169     if( failed ){
   27170       rc = failed;
   27171     }
   27172   }
   27173 
   27174   if( rc==SQLITE_OK ){
   27175     pFile->eFileLock = eFileLock;
   27176     pInode->eFileLock = eFileLock;
   27177   }else if( eFileLock==EXCLUSIVE_LOCK ){
   27178     pFile->eFileLock = PENDING_LOCK;
   27179     pInode->eFileLock = PENDING_LOCK;
   27180   }
   27181 
   27182 afp_end_lock:
   27183   unixLeaveMutex();
   27184   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
   27185          rc==SQLITE_OK ? "ok" : "failed"));
   27186   return rc;
   27187 }
   27188 
   27189 /*
   27190 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27191 ** must be either NO_LOCK or SHARED_LOCK.
   27192 **
   27193 ** If the locking level of the file descriptor is already at or below
   27194 ** the requested locking level, this routine is a no-op.
   27195 */
   27196 static int afpUnlock(sqlite3_file *id, int eFileLock) {
   27197   int rc = SQLITE_OK;
   27198   unixFile *pFile = (unixFile*)id;
   27199   unixInodeInfo *pInode;
   27200   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   27201   int skipShared = 0;
   27202 #ifdef SQLITE_TEST
   27203   int h = pFile->h;
   27204 #endif
   27205 
   27206   assert( pFile );
   27207   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
   27208            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   27209            getpid()));
   27210 
   27211   assert( eFileLock<=SHARED_LOCK );
   27212   if( pFile->eFileLock<=eFileLock ){
   27213     return SQLITE_OK;
   27214   }
   27215   unixEnterMutex();
   27216   pInode = pFile->pInode;
   27217   assert( pInode->nShared!=0 );
   27218   if( pFile->eFileLock>SHARED_LOCK ){
   27219     assert( pInode->eFileLock==pFile->eFileLock );
   27220     SimulateIOErrorBenign(1);
   27221     SimulateIOError( h=(-1) )
   27222     SimulateIOErrorBenign(0);
   27223 
   27224 #ifdef SQLITE_DEBUG
   27225     /* When reducing a lock such that other processes can start
   27226     ** reading the database file again, make sure that the
   27227     ** transaction counter was updated if any part of the database
   27228     ** file changed.  If the transaction counter is not updated,
   27229     ** other connections to the same file might not realize that
   27230     ** the file has changed and hence might not know to flush their
   27231     ** cache.  The use of a stale cache can lead to database corruption.
   27232     */
   27233     assert( pFile->inNormalWrite==0
   27234            || pFile->dbUpdate==0
   27235            || pFile->transCntrChng==1 );
   27236     pFile->inNormalWrite = 0;
   27237 #endif
   27238 
   27239     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
   27240       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
   27241       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
   27242         /* only re-establish the shared lock if necessary */
   27243         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   27244         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
   27245       } else {
   27246         skipShared = 1;
   27247       }
   27248     }
   27249     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
   27250       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   27251     }
   27252     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
   27253       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   27254       if( !rc ){
   27255         context->reserved = 0;
   27256       }
   27257     }
   27258     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
   27259       pInode->eFileLock = SHARED_LOCK;
   27260     }
   27261   }
   27262   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
   27263 
   27264     /* Decrement the shared lock counter.  Release the lock using an
   27265     ** OS call only when all threads in this same process have released
   27266     ** the lock.
   27267     */
   27268     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   27269     pInode->nShared--;
   27270     if( pInode->nShared==0 ){
   27271       SimulateIOErrorBenign(1);
   27272       SimulateIOError( h=(-1) )
   27273       SimulateIOErrorBenign(0);
   27274       if( !skipShared ){
   27275         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
   27276       }
   27277       if( !rc ){
   27278         pInode->eFileLock = NO_LOCK;
   27279         pFile->eFileLock = NO_LOCK;
   27280       }
   27281     }
   27282     if( rc==SQLITE_OK ){
   27283       pInode->nLock--;
   27284       assert( pInode->nLock>=0 );
   27285       if( pInode->nLock==0 ){
   27286         closePendingFds(pFile);
   27287       }
   27288     }
   27289   }
   27290 
   27291   unixLeaveMutex();
   27292   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   27293   return rc;
   27294 }
   27295 
   27296 /*
   27297 ** Close a file & cleanup AFP specific locking context
   27298 */
   27299 static int afpClose(sqlite3_file *id) {
   27300   int rc = SQLITE_OK;
   27301   if( id ){
   27302     unixFile *pFile = (unixFile*)id;
   27303     afpUnlock(id, NO_LOCK);
   27304     unixEnterMutex();
   27305     if( pFile->pInode && pFile->pInode->nLock ){
   27306       /* If there are outstanding locks, do not actually close the file just
   27307       ** yet because that would clear those locks.  Instead, add the file
   27308       ** descriptor to pInode->aPending.  It will be automatically closed when
   27309       ** the last lock is cleared.
   27310       */
   27311       setPendingFd(pFile);
   27312     }
   27313     releaseInodeInfo(pFile);
   27314     sqlite3_free(pFile->lockingContext);
   27315     rc = closeUnixFile(id);
   27316     unixLeaveMutex();
   27317   }
   27318   return rc;
   27319 }
   27320 
   27321 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27322 /*
   27323 ** The code above is the AFP lock implementation.  The code is specific
   27324 ** to MacOSX and does not work on other unix platforms.  No alternative
   27325 ** is available.  If you don't compile for a mac, then the "unix-afp"
   27326 ** VFS is not available.
   27327 **
   27328 ********************* End of the AFP lock implementation **********************
   27329 ******************************************************************************/
   27330 
   27331 /******************************************************************************
   27332 *************************** Begin NFS Locking ********************************/
   27333 
   27334 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27335 /*
   27336  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27337  ** must be either NO_LOCK or SHARED_LOCK.
   27338  **
   27339  ** If the locking level of the file descriptor is already at or below
   27340  ** the requested locking level, this routine is a no-op.
   27341  */
   27342 static int nfsUnlock(sqlite3_file *id, int eFileLock){
   27343   return posixUnlock(id, eFileLock, 1);
   27344 }
   27345 
   27346 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27347 /*
   27348 ** The code above is the NFS lock implementation.  The code is specific
   27349 ** to MacOSX and does not work on other unix platforms.  No alternative
   27350 ** is available.
   27351 **
   27352 ********************* End of the NFS lock implementation **********************
   27353 ******************************************************************************/
   27354 
   27355 /******************************************************************************
   27356 **************** Non-locking sqlite3_file methods *****************************
   27357 **
   27358 ** The next division contains implementations for all methods of the
   27359 ** sqlite3_file object other than the locking methods.  The locking
   27360 ** methods were defined in divisions above (one locking method per
   27361 ** division).  Those methods that are common to all locking modes
   27362 ** are gather together into this division.
   27363 */
   27364 
   27365 /*
   27366 ** Seek to the offset passed as the second argument, then read cnt
   27367 ** bytes into pBuf. Return the number of bytes actually read.
   27368 **
   27369 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
   27370 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
   27371 ** one system to another.  Since SQLite does not define USE_PREAD
   27372 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
   27373 ** See tickets #2741 and #2681.
   27374 **
   27375 ** To avoid stomping the errno value on a failed read the lastErrno value
   27376 ** is set before returning.
   27377 */
   27378 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   27379   int got;
   27380   int prior = 0;
   27381 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   27382   i64 newOffset;
   27383 #endif
   27384   TIMER_START;
   27385   assert( cnt==(cnt&0x1ffff) );
   27386   assert( id->h>2 );
   27387   cnt &= 0x1ffff;
   27388   do{
   27389 #if defined(USE_PREAD)
   27390     got = osPread(id->h, pBuf, cnt, offset);
   27391     SimulateIOError( got = -1 );
   27392 #elif defined(USE_PREAD64)
   27393     got = osPread64(id->h, pBuf, cnt, offset);
   27394     SimulateIOError( got = -1 );
   27395 #else
   27396     newOffset = lseek(id->h, offset, SEEK_SET);
   27397     SimulateIOError( newOffset-- );
   27398     if( newOffset!=offset ){
   27399       if( newOffset == -1 ){
   27400         ((unixFile*)id)->lastErrno = errno;
   27401       }else{
   27402         ((unixFile*)id)->lastErrno = 0;
   27403       }
   27404       return -1;
   27405     }
   27406     got = osRead(id->h, pBuf, cnt);
   27407 #endif
   27408     if( got==cnt ) break;
   27409     if( got<0 ){
   27410       if( errno==EINTR ){ got = 1; continue; }
   27411       prior = 0;
   27412       ((unixFile*)id)->lastErrno = errno;
   27413       break;
   27414     }else if( got>0 ){
   27415       cnt -= got;
   27416       offset += got;
   27417       prior += got;
   27418       pBuf = (void*)(got + (char*)pBuf);
   27419     }
   27420   }while( got>0 );
   27421   TIMER_END;
   27422   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
   27423             id->h, got+prior, offset-prior, TIMER_ELAPSED));
   27424   return got+prior;
   27425 }
   27426 
   27427 /*
   27428 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   27429 ** bytes were read successfully and SQLITE_IOERR if anything goes
   27430 ** wrong.
   27431 */
   27432 static int unixRead(
   27433   sqlite3_file *id,
   27434   void *pBuf,
   27435   int amt,
   27436   sqlite3_int64 offset
   27437 ){
   27438   unixFile *pFile = (unixFile *)id;
   27439   int got;
   27440   assert( id );
   27441   assert( offset>=0 );
   27442   assert( amt>0 );
   27443 
   27444   /* If this is a database file (not a journal, master-journal or temp
   27445   ** file), the bytes in the locking range should never be read or written. */
   27446 #if 0
   27447   assert( pFile->pUnused==0
   27448        || offset>=PENDING_BYTE+512
   27449        || offset+amt<=PENDING_BYTE
   27450   );
   27451 #endif
   27452 
   27453 #if SQLITE_MAX_MMAP_SIZE>0
   27454   /* Deal with as much of this read request as possible by transfering
   27455   ** data from the memory mapping using memcpy().  */
   27456   if( offset<pFile->mmapSize ){
   27457     if( offset+amt <= pFile->mmapSize ){
   27458       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
   27459       return SQLITE_OK;
   27460     }else{
   27461       int nCopy = pFile->mmapSize - offset;
   27462       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
   27463       pBuf = &((u8 *)pBuf)[nCopy];
   27464       amt -= nCopy;
   27465       offset += nCopy;
   27466     }
   27467   }
   27468 #endif
   27469 
   27470   got = seekAndRead(pFile, offset, pBuf, amt);
   27471   if( got==amt ){
   27472     return SQLITE_OK;
   27473   }else if( got<0 ){
   27474     /* lastErrno set by seekAndRead */
   27475     return SQLITE_IOERR_READ;
   27476   }else{
   27477     pFile->lastErrno = 0; /* not a system error */
   27478     /* Unread parts of the buffer must be zero-filled */
   27479     memset(&((char*)pBuf)[got], 0, amt-got);
   27480     return SQLITE_IOERR_SHORT_READ;
   27481   }
   27482 }
   27483 
   27484 /*
   27485 ** Attempt to seek the file-descriptor passed as the first argument to
   27486 ** absolute offset iOff, then attempt to write nBuf bytes of data from
   27487 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
   27488 ** return the actual number of bytes written (which may be less than
   27489 ** nBuf).
   27490 */
   27491 static int seekAndWriteFd(
   27492   int fd,                         /* File descriptor to write to */
   27493   i64 iOff,                       /* File offset to begin writing at */
   27494   const void *pBuf,               /* Copy data from this buffer to the file */
   27495   int nBuf,                       /* Size of buffer pBuf in bytes */
   27496   int *piErrno                    /* OUT: Error number if error occurs */
   27497 ){
   27498   int rc = 0;                     /* Value returned by system call */
   27499 
   27500   assert( nBuf==(nBuf&0x1ffff) );
   27501   assert( fd>2 );
   27502   nBuf &= 0x1ffff;
   27503   TIMER_START;
   27504 
   27505 #if defined(USE_PREAD)
   27506   do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
   27507 #elif defined(USE_PREAD64)
   27508   do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
   27509 #else
   27510   do{
   27511     i64 iSeek = lseek(fd, iOff, SEEK_SET);
   27512     SimulateIOError( iSeek-- );
   27513 
   27514     if( iSeek!=iOff ){
   27515       if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
   27516       return -1;
   27517     }
   27518     rc = osWrite(fd, pBuf, nBuf);
   27519   }while( rc<0 && errno==EINTR );
   27520 #endif
   27521 
   27522   TIMER_END;
   27523   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
   27524 
   27525   if( rc<0 && piErrno ) *piErrno = errno;
   27526   return rc;
   27527 }
   27528 
   27529 
   27530 /*
   27531 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   27532 ** Return the number of bytes actually read.  Update the offset.
   27533 **
   27534 ** To avoid stomping the errno value on a failed write the lastErrno value
   27535 ** is set before returning.
   27536 */
   27537 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   27538   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
   27539 }
   27540 
   27541 
   27542 /*
   27543 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   27544 ** or some other error code on failure.
   27545 */
   27546 static int unixWrite(
   27547   sqlite3_file *id,
   27548   const void *pBuf,
   27549   int amt,
   27550   sqlite3_int64 offset
   27551 ){
   27552   unixFile *pFile = (unixFile*)id;
   27553   int wrote = 0;
   27554   assert( id );
   27555   assert( amt>0 );
   27556 
   27557   /* If this is a database file (not a journal, master-journal or temp
   27558   ** file), the bytes in the locking range should never be read or written. */
   27559 #if 0
   27560   assert( pFile->pUnused==0
   27561        || offset>=PENDING_BYTE+512
   27562        || offset+amt<=PENDING_BYTE
   27563   );
   27564 #endif
   27565 
   27566 #ifdef SQLITE_DEBUG
   27567   /* If we are doing a normal write to a database file (as opposed to
   27568   ** doing a hot-journal rollback or a write to some file other than a
   27569   ** normal database file) then record the fact that the database
   27570   ** has changed.  If the transaction counter is modified, record that
   27571   ** fact too.
   27572   */
   27573   if( pFile->inNormalWrite ){
   27574     pFile->dbUpdate = 1;  /* The database has been modified */
   27575     if( offset<=24 && offset+amt>=27 ){
   27576       int rc;
   27577       char oldCntr[4];
   27578       SimulateIOErrorBenign(1);
   27579       rc = seekAndRead(pFile, 24, oldCntr, 4);
   27580       SimulateIOErrorBenign(0);
   27581       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
   27582         pFile->transCntrChng = 1;  /* The transaction counter has changed */
   27583       }
   27584     }
   27585   }
   27586 #endif
   27587 
   27588 #if SQLITE_MAX_MMAP_SIZE>0
   27589   /* Deal with as much of this write request as possible by transfering
   27590   ** data from the memory mapping using memcpy().  */
   27591   if( offset<pFile->mmapSize ){
   27592     if( offset+amt <= pFile->mmapSize ){
   27593       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
   27594       return SQLITE_OK;
   27595     }else{
   27596       int nCopy = pFile->mmapSize - offset;
   27597       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
   27598       pBuf = &((u8 *)pBuf)[nCopy];
   27599       amt -= nCopy;
   27600       offset += nCopy;
   27601     }
   27602   }
   27603 #endif
   27604 
   27605   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
   27606     amt -= wrote;
   27607     offset += wrote;
   27608     pBuf = &((char*)pBuf)[wrote];
   27609   }
   27610   SimulateIOError(( wrote=(-1), amt=1 ));
   27611   SimulateDiskfullError(( wrote=0, amt=1 ));
   27612 
   27613   if( amt>0 ){
   27614     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
   27615       /* lastErrno set by seekAndWrite */
   27616       return SQLITE_IOERR_WRITE;
   27617     }else{
   27618       pFile->lastErrno = 0; /* not a system error */
   27619       return SQLITE_FULL;
   27620     }
   27621   }
   27622 
   27623   return SQLITE_OK;
   27624 }
   27625 
   27626 #ifdef SQLITE_TEST
   27627 /*
   27628 ** Count the number of fullsyncs and normal syncs.  This is used to test
   27629 ** that syncs and fullsyncs are occurring at the right times.
   27630 */
   27631 SQLITE_API int sqlite3_sync_count = 0;
   27632 SQLITE_API int sqlite3_fullsync_count = 0;
   27633 #endif
   27634 
   27635 /*
   27636 ** We do not trust systems to provide a working fdatasync().  Some do.
   27637 ** Others do no.  To be safe, we will stick with the (slightly slower)
   27638 ** fsync(). If you know that your system does support fdatasync() correctly,
   27639 ** then simply compile with -Dfdatasync=fdatasync
   27640 */
   27641 #if !defined(fdatasync)
   27642 # define fdatasync fsync
   27643 #endif
   27644 
   27645 /*
   27646 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   27647 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   27648 ** only available on Mac OS X.  But that could change.
   27649 */
   27650 #ifdef F_FULLFSYNC
   27651 # define HAVE_FULLFSYNC 1
   27652 #else
   27653 # define HAVE_FULLFSYNC 0
   27654 #endif
   27655 
   27656 
   27657 /*
   27658 ** The fsync() system call does not work as advertised on many
   27659 ** unix systems.  The following procedure is an attempt to make
   27660 ** it work better.
   27661 **
   27662 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   27663 ** for testing when we want to run through the test suite quickly.
   27664 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   27665 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   27666 ** or power failure will likely corrupt the database file.
   27667 **
   27668 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
   27669 ** The idea behind dataOnly is that it should only write the file content
   27670 ** to disk, not the inode.  We only set dataOnly if the file size is
   27671 ** unchanged since the file size is part of the inode.  However,
   27672 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
   27673 ** file size has changed.  The only real difference between fdatasync()
   27674 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
   27675 ** inode if the mtime or owner or other inode attributes have changed.
   27676 ** We only care about the file size, not the other file attributes, so
   27677 ** as far as SQLite is concerned, an fdatasync() is always adequate.
   27678 ** So, we always use fdatasync() if it is available, regardless of
   27679 ** the value of the dataOnly flag.
   27680 */
   27681 static int full_fsync(int fd, int fullSync, int dataOnly){
   27682   int rc;
   27683 
   27684   /* The following "ifdef/elif/else/" block has the same structure as
   27685   ** the one below. It is replicated here solely to avoid cluttering
   27686   ** up the real code with the UNUSED_PARAMETER() macros.
   27687   */
   27688 #ifdef SQLITE_NO_SYNC
   27689   UNUSED_PARAMETER(fd);
   27690   UNUSED_PARAMETER(fullSync);
   27691   UNUSED_PARAMETER(dataOnly);
   27692 #elif HAVE_FULLFSYNC
   27693   UNUSED_PARAMETER(dataOnly);
   27694 #else
   27695   UNUSED_PARAMETER(fullSync);
   27696   UNUSED_PARAMETER(dataOnly);
   27697 #endif
   27698 
   27699   /* Record the number of times that we do a normal fsync() and
   27700   ** FULLSYNC.  This is used during testing to verify that this procedure
   27701   ** gets called with the correct arguments.
   27702   */
   27703 #ifdef SQLITE_TEST
   27704   if( fullSync ) sqlite3_fullsync_count++;
   27705   sqlite3_sync_count++;
   27706 #endif
   27707 
   27708   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   27709   ** no-op
   27710   */
   27711 #ifdef SQLITE_NO_SYNC
   27712   rc = SQLITE_OK;
   27713 #elif HAVE_FULLFSYNC
   27714   if( fullSync ){
   27715     rc = osFcntl(fd, F_FULLFSYNC, 0);
   27716   }else{
   27717     rc = 1;
   27718   }
   27719   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   27720   ** It shouldn't be possible for fullfsync to fail on the local
   27721   ** file system (on OSX), so failure indicates that FULLFSYNC
   27722   ** isn't supported for this file system. So, attempt an fsync
   27723   ** and (for now) ignore the overhead of a superfluous fcntl call.
   27724   ** It'd be better to detect fullfsync support once and avoid
   27725   ** the fcntl call every time sync is called.
   27726   */
   27727   if( rc ) rc = fsync(fd);
   27728 
   27729 #elif defined(__APPLE__)
   27730   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
   27731   ** so currently we default to the macro that redefines fdatasync to fsync
   27732   */
   27733   rc = fsync(fd);
   27734 #else
   27735   rc = fdatasync(fd);
   27736 #if OS_VXWORKS
   27737   if( rc==-1 && errno==ENOTSUP ){
   27738     rc = fsync(fd);
   27739   }
   27740 #endif /* OS_VXWORKS */
   27741 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
   27742 
   27743   if( OS_VXWORKS && rc!= -1 ){
   27744     rc = 0;
   27745   }
   27746   return rc;
   27747 }
   27748 
   27749 /*
   27750 ** Open a file descriptor to the directory containing file zFilename.
   27751 ** If successful, *pFd is set to the opened file descriptor and
   27752 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
   27753 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
   27754 ** value.
   27755 **
   27756 ** The directory file descriptor is used for only one thing - to
   27757 ** fsync() a directory to make sure file creation and deletion events
   27758 ** are flushed to disk.  Such fsyncs are not needed on newer
   27759 ** journaling filesystems, but are required on older filesystems.
   27760 **
   27761 ** This routine can be overridden using the xSetSysCall interface.
   27762 ** The ability to override this routine was added in support of the
   27763 ** chromium sandbox.  Opening a directory is a security risk (we are
   27764 ** told) so making it overrideable allows the chromium sandbox to
   27765 ** replace this routine with a harmless no-op.  To make this routine
   27766 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
   27767 ** *pFd set to a negative number.
   27768 **
   27769 ** If SQLITE_OK is returned, the caller is responsible for closing
   27770 ** the file descriptor *pFd using close().
   27771 */
   27772 static int openDirectory(const char *zFilename, int *pFd){
   27773   int ii;
   27774   int fd = -1;
   27775   char zDirname[MAX_PATHNAME+1];
   27776 
   27777   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
   27778   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
   27779   if( ii>0 ){
   27780     zDirname[ii] = '\0';
   27781     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
   27782     if( fd>=0 ){
   27783       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
   27784     }
   27785   }
   27786   *pFd = fd;
   27787   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
   27788 }
   27789 
   27790 /*
   27791 ** Make sure all writes to a particular file are committed to disk.
   27792 **
   27793 ** If dataOnly==0 then both the file itself and its metadata (file
   27794 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   27795 ** file data is synced.
   27796 **
   27797 ** Under Unix, also make sure that the directory entry for the file
   27798 ** has been created by fsync-ing the directory that contains the file.
   27799 ** If we do not do this and we encounter a power failure, the directory
   27800 ** entry for the journal might not exist after we reboot.  The next
   27801 ** SQLite to access the file will not know that the journal exists (because
   27802 ** the directory entry for the journal was never created) and the transaction
   27803 ** will not roll back - possibly leading to database corruption.
   27804 */
   27805 static int unixSync(sqlite3_file *id, int flags){
   27806   int rc;
   27807   unixFile *pFile = (unixFile*)id;
   27808 
   27809   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   27810   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   27811 
   27812   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   27813   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   27814       || (flags&0x0F)==SQLITE_SYNC_FULL
   27815   );
   27816 
   27817   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   27818   ** line is to test that doing so does not cause any problems.
   27819   */
   27820   SimulateDiskfullError( return SQLITE_FULL );
   27821 
   27822   assert( pFile );
   27823   OSTRACE(("SYNC    %-3d\n", pFile->h));
   27824   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   27825   SimulateIOError( rc=1 );
   27826   if( rc ){
   27827     pFile->lastErrno = errno;
   27828     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
   27829   }
   27830 
   27831   /* Also fsync the directory containing the file if the DIRSYNC flag
   27832   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
   27833   ** are unable to fsync a directory, so ignore errors on the fsync.
   27834   */
   27835   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
   27836     int dirfd;
   27837     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
   27838             HAVE_FULLFSYNC, isFullsync));
   27839     rc = osOpenDirectory(pFile->zPath, &dirfd);
   27840     if( rc==SQLITE_OK && dirfd>=0 ){
   27841       full_fsync(dirfd, 0, 0);
   27842       robust_close(pFile, dirfd, __LINE__);
   27843     }else if( rc==SQLITE_CANTOPEN ){
   27844       rc = SQLITE_OK;
   27845     }
   27846     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
   27847   }
   27848   return rc;
   27849 }
   27850 
   27851 /*
   27852 ** Truncate an open file to a specified size
   27853 */
   27854 static int unixTruncate(sqlite3_file *id, i64 nByte){
   27855   unixFile *pFile = (unixFile *)id;
   27856   int rc;
   27857   assert( pFile );
   27858   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   27859 
   27860   /* If the user has configured a chunk-size for this file, truncate the
   27861   ** file so that it consists of an integer number of chunks (i.e. the
   27862   ** actual file size after the operation may be larger than the requested
   27863   ** size).
   27864   */
   27865   if( pFile->szChunk>0 ){
   27866     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   27867   }
   27868 
   27869   rc = robust_ftruncate(pFile->h, (off_t)nByte);
   27870   if( rc ){
   27871     pFile->lastErrno = errno;
   27872     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   27873   }else{
   27874 #ifdef SQLITE_DEBUG
   27875     /* If we are doing a normal write to a database file (as opposed to
   27876     ** doing a hot-journal rollback or a write to some file other than a
   27877     ** normal database file) and we truncate the file to zero length,
   27878     ** that effectively updates the change counter.  This might happen
   27879     ** when restoring a database using the backup API from a zero-length
   27880     ** source.
   27881     */
   27882     if( pFile->inNormalWrite && nByte==0 ){
   27883       pFile->transCntrChng = 1;
   27884     }
   27885 #endif
   27886 
   27887 #if SQLITE_MAX_MMAP_SIZE>0
   27888     /* If the file was just truncated to a size smaller than the currently
   27889     ** mapped region, reduce the effective mapping size as well. SQLite will
   27890     ** use read() and write() to access data beyond this point from now on.
   27891     */
   27892     if( nByte<pFile->mmapSize ){
   27893       pFile->mmapSize = nByte;
   27894     }
   27895 #endif
   27896 
   27897     return SQLITE_OK;
   27898   }
   27899 }
   27900 
   27901 /*
   27902 ** Determine the current size of a file in bytes
   27903 */
   27904 static int unixFileSize(sqlite3_file *id, i64 *pSize){
   27905   int rc;
   27906   struct stat buf;
   27907   assert( id );
   27908   rc = osFstat(((unixFile*)id)->h, &buf);
   27909   SimulateIOError( rc=1 );
   27910   if( rc!=0 ){
   27911     ((unixFile*)id)->lastErrno = errno;
   27912     return SQLITE_IOERR_FSTAT;
   27913   }
   27914   *pSize = buf.st_size;
   27915 
   27916   /* When opening a zero-size database, the findInodeInfo() procedure
   27917   ** writes a single byte into that file in order to work around a bug
   27918   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
   27919   ** layers, we need to report this file size as zero even though it is
   27920   ** really 1.   Ticket #3260.
   27921   */
   27922   if( *pSize==1 ) *pSize = 0;
   27923 
   27924 
   27925   return SQLITE_OK;
   27926 }
   27927 
   27928 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   27929 /*
   27930 ** Handler for proxy-locking file-control verbs.  Defined below in the
   27931 ** proxying locking division.
   27932 */
   27933 static int proxyFileControl(sqlite3_file*,int,void*);
   27934 #endif
   27935 
   27936 /*
   27937 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
   27938 ** file-control operation.  Enlarge the database to nBytes in size
   27939 ** (rounded up to the next chunk-size).  If the database is already
   27940 ** nBytes or larger, this routine is a no-op.
   27941 */
   27942 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
   27943   if( pFile->szChunk>0 ){
   27944     i64 nSize;                    /* Required file size */
   27945     struct stat buf;              /* Used to hold return values of fstat() */
   27946 
   27947     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
   27948 
   27949     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
   27950     if( nSize>(i64)buf.st_size ){
   27951 
   27952 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   27953       /* The code below is handling the return value of osFallocate()
   27954       ** correctly. posix_fallocate() is defined to "returns zero on success,
   27955       ** or an error number on  failure". See the manpage for details. */
   27956       int err;
   27957       do{
   27958         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
   27959       }while( err==EINTR );
   27960       if( err ) return SQLITE_IOERR_WRITE;
   27961 #else
   27962       /* If the OS does not have posix_fallocate(), fake it. First use
   27963       ** ftruncate() to set the file size, then write a single byte to
   27964       ** the last byte in each block within the extended region. This
   27965       ** is the same technique used by glibc to implement posix_fallocate()
   27966       ** on systems that do not have a real fallocate() system call.
   27967       */
   27968       int nBlk = buf.st_blksize;  /* File-system block size */
   27969       i64 iWrite;                 /* Next offset to write to */
   27970 
   27971       if( robust_ftruncate(pFile->h, nSize) ){
   27972         pFile->lastErrno = errno;
   27973         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   27974       }
   27975       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
   27976       while( iWrite<nSize ){
   27977         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
   27978         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
   27979         iWrite += nBlk;
   27980       }
   27981 #endif
   27982     }
   27983   }
   27984 
   27985 #if SQLITE_MAX_MMAP_SIZE>0
   27986   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
   27987     int rc;
   27988     if( pFile->szChunk<=0 ){
   27989       if( robust_ftruncate(pFile->h, nByte) ){
   27990         pFile->lastErrno = errno;
   27991         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   27992       }
   27993     }
   27994 
   27995     rc = unixMapfile(pFile, nByte);
   27996     return rc;
   27997   }
   27998 #endif
   27999 
   28000   return SQLITE_OK;
   28001 }
   28002 
   28003 /*
   28004 ** If *pArg is inititially negative then this is a query.  Set *pArg to
   28005 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   28006 **
   28007 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   28008 */
   28009 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
   28010   if( *pArg<0 ){
   28011     *pArg = (pFile->ctrlFlags & mask)!=0;
   28012   }else if( (*pArg)==0 ){
   28013     pFile->ctrlFlags &= ~mask;
   28014   }else{
   28015     pFile->ctrlFlags |= mask;
   28016   }
   28017 }
   28018 
   28019 /* Forward declaration */
   28020 static int unixGetTempname(int nBuf, char *zBuf);
   28021 
   28022 /*
   28023 ** Information and control of an open file handle.
   28024 */
   28025 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
   28026   unixFile *pFile = (unixFile*)id;
   28027   switch( op ){
   28028     case SQLITE_FCNTL_LOCKSTATE: {
   28029       *(int*)pArg = pFile->eFileLock;
   28030       return SQLITE_OK;
   28031     }
   28032     case SQLITE_LAST_ERRNO: {
   28033       *(int*)pArg = pFile->lastErrno;
   28034       return SQLITE_OK;
   28035     }
   28036     case SQLITE_FCNTL_CHUNK_SIZE: {
   28037       pFile->szChunk = *(int *)pArg;
   28038       return SQLITE_OK;
   28039     }
   28040     case SQLITE_FCNTL_SIZE_HINT: {
   28041       int rc;
   28042       SimulateIOErrorBenign(1);
   28043       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
   28044       SimulateIOErrorBenign(0);
   28045       return rc;
   28046     }
   28047     case SQLITE_FCNTL_PERSIST_WAL: {
   28048       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
   28049       return SQLITE_OK;
   28050     }
   28051     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   28052       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
   28053       return SQLITE_OK;
   28054     }
   28055     case SQLITE_FCNTL_VFSNAME: {
   28056       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
   28057       return SQLITE_OK;
   28058     }
   28059     case SQLITE_FCNTL_TEMPFILENAME: {
   28060       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
   28061       if( zTFile ){
   28062         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
   28063         *(char**)pArg = zTFile;
   28064       }
   28065       return SQLITE_OK;
   28066     }
   28067     case SQLITE_FCNTL_HAS_MOVED: {
   28068       *(int*)pArg = fileHasMoved(pFile);
   28069       return SQLITE_OK;
   28070     }
   28071 #if SQLITE_MAX_MMAP_SIZE>0
   28072     case SQLITE_FCNTL_MMAP_SIZE: {
   28073       i64 newLimit = *(i64*)pArg;
   28074       int rc = SQLITE_OK;
   28075       if( newLimit>sqlite3GlobalConfig.mxMmap ){
   28076         newLimit = sqlite3GlobalConfig.mxMmap;
   28077       }
   28078       *(i64*)pArg = pFile->mmapSizeMax;
   28079       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
   28080         pFile->mmapSizeMax = newLimit;
   28081         if( pFile->mmapSize>0 ){
   28082           unixUnmapfile(pFile);
   28083           rc = unixMapfile(pFile, -1);
   28084         }
   28085       }
   28086       return rc;
   28087     }
   28088 #endif
   28089 #ifdef SQLITE_DEBUG
   28090     /* The pager calls this method to signal that it has done
   28091     ** a rollback and that the database is therefore unchanged and
   28092     ** it hence it is OK for the transaction change counter to be
   28093     ** unchanged.
   28094     */
   28095     case SQLITE_FCNTL_DB_UNCHANGED: {
   28096       ((unixFile*)id)->dbUpdate = 0;
   28097       return SQLITE_OK;
   28098     }
   28099 #endif
   28100 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   28101     case SQLITE_SET_LOCKPROXYFILE:
   28102     case SQLITE_GET_LOCKPROXYFILE: {
   28103       return proxyFileControl(id,op,pArg);
   28104     }
   28105 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
   28106   }
   28107   return SQLITE_NOTFOUND;
   28108 }
   28109 
   28110 /*
   28111 ** Return the sector size in bytes of the underlying block device for
   28112 ** the specified file. This is almost always 512 bytes, but may be
   28113 ** larger for some devices.
   28114 **
   28115 ** SQLite code assumes this function cannot fail. It also assumes that
   28116 ** if two files are created in the same file-system directory (i.e.
   28117 ** a database and its journal file) that the sector size will be the
   28118 ** same for both.
   28119 */
   28120 #ifndef __QNXNTO__
   28121 static int unixSectorSize(sqlite3_file *NotUsed){
   28122   UNUSED_PARAMETER(NotUsed);
   28123   return SQLITE_DEFAULT_SECTOR_SIZE;
   28124 }
   28125 #endif
   28126 
   28127 /*
   28128 ** The following version of unixSectorSize() is optimized for QNX.
   28129 */
   28130 #ifdef __QNXNTO__
   28131 #include <sys/dcmd_blk.h>
   28132 #include <sys/statvfs.h>
   28133 static int unixSectorSize(sqlite3_file *id){
   28134   unixFile *pFile = (unixFile*)id;
   28135   if( pFile->sectorSize == 0 ){
   28136     struct statvfs fsInfo;
   28137 
   28138     /* Set defaults for non-supported filesystems */
   28139     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
   28140     pFile->deviceCharacteristics = 0;
   28141     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
   28142       return pFile->sectorSize;
   28143     }
   28144 
   28145     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
   28146       pFile->sectorSize = fsInfo.f_bsize;
   28147       pFile->deviceCharacteristics =
   28148         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
   28149         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   28150                                       ** the write succeeds */
   28151         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28152                                       ** so it is ordered */
   28153         0;
   28154     }else if( strstr(fsInfo.f_basetype, "etfs") ){
   28155       pFile->sectorSize = fsInfo.f_bsize;
   28156       pFile->deviceCharacteristics =
   28157         /* etfs cluster size writes are atomic */
   28158         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
   28159         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   28160                                       ** the write succeeds */
   28161         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28162                                       ** so it is ordered */
   28163         0;
   28164     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
   28165       pFile->sectorSize = fsInfo.f_bsize;
   28166       pFile->deviceCharacteristics =
   28167         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
   28168         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   28169                                       ** the write succeeds */
   28170         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28171                                       ** so it is ordered */
   28172         0;
   28173     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
   28174       pFile->sectorSize = fsInfo.f_bsize;
   28175       pFile->deviceCharacteristics =
   28176         /* full bitset of atomics from max sector size and smaller */
   28177         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
   28178         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28179                                       ** so it is ordered */
   28180         0;
   28181     }else if( strstr(fsInfo.f_basetype, "dos") ){
   28182       pFile->sectorSize = fsInfo.f_bsize;
   28183       pFile->deviceCharacteristics =
   28184         /* full bitset of atomics from max sector size and smaller */
   28185         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
   28186         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   28187                                       ** so it is ordered */
   28188         0;
   28189     }else{
   28190       pFile->deviceCharacteristics =
   28191         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
   28192         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   28193                                       ** the write succeeds */
   28194         0;
   28195     }
   28196   }
   28197   /* Last chance verification.  If the sector size isn't a multiple of 512
   28198   ** then it isn't valid.*/
   28199   if( pFile->sectorSize % 512 != 0 ){
   28200     pFile->deviceCharacteristics = 0;
   28201     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
   28202   }
   28203   return pFile->sectorSize;
   28204 }
   28205 #endif /* __QNXNTO__ */
   28206 
   28207 /*
   28208 ** Return the device characteristics for the file.
   28209 **
   28210 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
   28211 ** However, that choice is contraversial since technically the underlying
   28212 ** file system does not always provide powersafe overwrites.  (In other
   28213 ** words, after a power-loss event, parts of the file that were never
   28214 ** written might end up being altered.)  However, non-PSOW behavior is very,
   28215 ** very rare.  And asserting PSOW makes a large reduction in the amount
   28216 ** of required I/O for journaling, since a lot of padding is eliminated.
   28217 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
   28218 ** available to turn it off and URI query parameter available to turn it off.
   28219 */
   28220 static int unixDeviceCharacteristics(sqlite3_file *id){
   28221   unixFile *p = (unixFile*)id;
   28222   int rc = 0;
   28223 #ifdef __QNXNTO__
   28224   if( p->sectorSize==0 ) unixSectorSize(id);
   28225   rc = p->deviceCharacteristics;
   28226 #endif
   28227   if( p->ctrlFlags & UNIXFILE_PSOW ){
   28228     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
   28229   }
   28230   return rc;
   28231 }
   28232 
   28233 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   28234 
   28235 /*
   28236 ** Return the system page size.
   28237 **
   28238 ** This function should not be called directly by other code in this file.
   28239 ** Instead, it should be called via macro osGetpagesize().
   28240 */
   28241 static int unixGetpagesize(void){
   28242 #if defined(_BSD_SOURCE)
   28243   return getpagesize();
   28244 #else
   28245   return (int)sysconf(_SC_PAGESIZE);
   28246 #endif
   28247 }
   28248 
   28249 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
   28250 
   28251 #ifndef SQLITE_OMIT_WAL
   28252 
   28253 /*
   28254 ** Object used to represent an shared memory buffer.
   28255 **
   28256 ** When multiple threads all reference the same wal-index, each thread
   28257 ** has its own unixShm object, but they all point to a single instance
   28258 ** of this unixShmNode object.  In other words, each wal-index is opened
   28259 ** only once per process.
   28260 **
   28261 ** Each unixShmNode object is connected to a single unixInodeInfo object.
   28262 ** We could coalesce this object into unixInodeInfo, but that would mean
   28263 ** every open file that does not use shared memory (in other words, most
   28264 ** open files) would have to carry around this extra information.  So
   28265 ** the unixInodeInfo object contains a pointer to this unixShmNode object
   28266 ** and the unixShmNode object is created only when needed.
   28267 **
   28268 ** unixMutexHeld() must be true when creating or destroying
   28269 ** this object or while reading or writing the following fields:
   28270 **
   28271 **      nRef
   28272 **
   28273 ** The following fields are read-only after the object is created:
   28274 **
   28275 **      fid
   28276 **      zFilename
   28277 **
   28278 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
   28279 ** unixMutexHeld() is true when reading or writing any other field
   28280 ** in this structure.
   28281 */
   28282 struct unixShmNode {
   28283   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
   28284   sqlite3_mutex *mutex;      /* Mutex to access this object */
   28285   char *zFilename;           /* Name of the mmapped file */
   28286   int h;                     /* Open file descriptor */
   28287   int szRegion;              /* Size of shared-memory regions */
   28288   u16 nRegion;               /* Size of array apRegion */
   28289   u8 isReadonly;             /* True if read-only */
   28290   char **apRegion;           /* Array of mapped shared-memory regions */
   28291   int nRef;                  /* Number of unixShm objects pointing to this */
   28292   unixShm *pFirst;           /* All unixShm objects pointing to this */
   28293 #ifdef SQLITE_DEBUG
   28294   u8 exclMask;               /* Mask of exclusive locks held */
   28295   u8 sharedMask;             /* Mask of shared locks held */
   28296   u8 nextShmId;              /* Next available unixShm.id value */
   28297 #endif
   28298 };
   28299 
   28300 /*
   28301 ** Structure used internally by this VFS to record the state of an
   28302 ** open shared memory connection.
   28303 **
   28304 ** The following fields are initialized when this object is created and
   28305 ** are read-only thereafter:
   28306 **
   28307 **    unixShm.pFile
   28308 **    unixShm.id
   28309 **
   28310 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
   28311 ** while accessing any read/write fields.
   28312 */
   28313 struct unixShm {
   28314   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
   28315   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
   28316   u8 hasMutex;               /* True if holding the unixShmNode mutex */
   28317   u8 id;                     /* Id of this connection within its unixShmNode */
   28318   u16 sharedMask;            /* Mask of shared locks held */
   28319   u16 exclMask;              /* Mask of exclusive locks held */
   28320 };
   28321 
   28322 /*
   28323 ** Constants used for locking
   28324 */
   28325 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
   28326 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   28327 
   28328 /*
   28329 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
   28330 **
   28331 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
   28332 ** otherwise.
   28333 */
   28334 static int unixShmSystemLock(
   28335   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
   28336   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
   28337   int ofst,              /* First byte of the locking range */
   28338   int n                  /* Number of bytes to lock */
   28339 ){
   28340   struct flock f;       /* The posix advisory locking structure */
   28341   int rc = SQLITE_OK;   /* Result code form fcntl() */
   28342 
   28343   /* Access to the unixShmNode object is serialized by the caller */
   28344   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
   28345 
   28346   /* Shared locks never span more than one byte */
   28347   assert( n==1 || lockType!=F_RDLCK );
   28348 
   28349   /* Locks are within range */
   28350   assert( n>=1 && n<SQLITE_SHM_NLOCK );
   28351 
   28352   if( pShmNode->h>=0 ){
   28353     /* Initialize the locking parameters */
   28354     memset(&f, 0, sizeof(f));
   28355     f.l_type = lockType;
   28356     f.l_whence = SEEK_SET;
   28357     f.l_start = ofst;
   28358     f.l_len = n;
   28359 
   28360     rc = osFcntl(pShmNode->h, F_SETLK, &f);
   28361     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
   28362   }
   28363 
   28364   /* Update the global lock state and do debug tracing */
   28365 #ifdef SQLITE_DEBUG
   28366   { u16 mask;
   28367   OSTRACE(("SHM-LOCK "));
   28368   mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
   28369   if( rc==SQLITE_OK ){
   28370     if( lockType==F_UNLCK ){
   28371       OSTRACE(("unlock %d ok", ofst));
   28372       pShmNode->exclMask &= ~mask;
   28373       pShmNode->sharedMask &= ~mask;
   28374     }else if( lockType==F_RDLCK ){
   28375       OSTRACE(("read-lock %d ok", ofst));
   28376       pShmNode->exclMask &= ~mask;
   28377       pShmNode->sharedMask |= mask;
   28378     }else{
   28379       assert( lockType==F_WRLCK );
   28380       OSTRACE(("write-lock %d ok", ofst));
   28381       pShmNode->exclMask |= mask;
   28382       pShmNode->sharedMask &= ~mask;
   28383     }
   28384   }else{
   28385     if( lockType==F_UNLCK ){
   28386       OSTRACE(("unlock %d failed", ofst));
   28387     }else if( lockType==F_RDLCK ){
   28388       OSTRACE(("read-lock failed"));
   28389     }else{
   28390       assert( lockType==F_WRLCK );
   28391       OSTRACE(("write-lock %d failed", ofst));
   28392     }
   28393   }
   28394   OSTRACE((" - afterwards %03x,%03x\n",
   28395            pShmNode->sharedMask, pShmNode->exclMask));
   28396   }
   28397 #endif
   28398 
   28399   return rc;
   28400 }
   28401 
   28402 /*
   28403 ** Return the minimum number of 32KB shm regions that should be mapped at
   28404 ** a time, assuming that each mapping must be an integer multiple of the
   28405 ** current system page-size.
   28406 **
   28407 ** Usually, this is 1. The exception seems to be systems that are configured
   28408 ** to use 64KB pages - in this case each mapping must cover at least two
   28409 ** shm regions.
   28410 */
   28411 static int unixShmRegionPerMap(void){
   28412   int shmsz = 32*1024;            /* SHM region size */
   28413   int pgsz = osGetpagesize();   /* System page size */
   28414   assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
   28415   if( pgsz<shmsz ) return 1;
   28416   return pgsz/shmsz;
   28417 }
   28418 
   28419 /*
   28420 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
   28421 **
   28422 ** This is not a VFS shared-memory method; it is a utility function called
   28423 ** by VFS shared-memory methods.
   28424 */
   28425 static void unixShmPurge(unixFile *pFd){
   28426   unixShmNode *p = pFd->pInode->pShmNode;
   28427   assert( unixMutexHeld() );
   28428   if( p && p->nRef==0 ){
   28429     int nShmPerMap = unixShmRegionPerMap();
   28430     int i;
   28431     assert( p->pInode==pFd->pInode );
   28432     sqlite3_mutex_free(p->mutex);
   28433     for(i=0; i<p->nRegion; i+=nShmPerMap){
   28434       if( p->h>=0 ){
   28435         osMunmap(p->apRegion[i], p->szRegion);
   28436       }else{
   28437         sqlite3_free(p->apRegion[i]);
   28438       }
   28439     }
   28440     sqlite3_free(p->apRegion);
   28441     if( p->h>=0 ){
   28442       robust_close(pFd, p->h, __LINE__);
   28443       p->h = -1;
   28444     }
   28445     p->pInode->pShmNode = 0;
   28446     sqlite3_free(p);
   28447   }
   28448 }
   28449 
   28450 /*
   28451 ** Open a shared-memory area associated with open database file pDbFd.
   28452 ** This particular implementation uses mmapped files.
   28453 **
   28454 ** The file used to implement shared-memory is in the same directory
   28455 ** as the open database file and has the same name as the open database
   28456 ** file with the "-shm" suffix added.  For example, if the database file
   28457 ** is "/home/user1/config.db" then the file that is created and mmapped
   28458 ** for shared memory will be called "/home/user1/config.db-shm".
   28459 **
   28460 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
   28461 ** some other tmpfs mount. But if a file in a different directory
   28462 ** from the database file is used, then differing access permissions
   28463 ** or a chroot() might cause two different processes on the same
   28464 ** database to end up using different files for shared memory -
   28465 ** meaning that their memory would not really be shared - resulting
   28466 ** in database corruption.  Nevertheless, this tmpfs file usage
   28467 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
   28468 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
   28469 ** option results in an incompatible build of SQLite;  builds of SQLite
   28470 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
   28471 ** same database file at the same time, database corruption will likely
   28472 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
   28473 ** "unsupported" and may go away in a future SQLite release.
   28474 **
   28475 ** When opening a new shared-memory file, if no other instances of that
   28476 ** file are currently open, in this process or in other processes, then
   28477 ** the file must be truncated to zero length or have its header cleared.
   28478 **
   28479 ** If the original database file (pDbFd) is using the "unix-excl" VFS
   28480 ** that means that an exclusive lock is held on the database file and
   28481 ** that no other processes are able to read or write the database.  In
   28482 ** that case, we do not really need shared memory.  No shared memory
   28483 ** file is created.  The shared memory will be simulated with heap memory.
   28484 */
   28485 static int unixOpenSharedMemory(unixFile *pDbFd){
   28486   struct unixShm *p = 0;          /* The connection to be opened */
   28487   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
   28488   int rc;                         /* Result code */
   28489   unixInodeInfo *pInode;          /* The inode of fd */
   28490   char *zShmFilename;             /* Name of the file used for SHM */
   28491   int nShmFilename;               /* Size of the SHM filename in bytes */
   28492 
   28493   /* Allocate space for the new unixShm object. */
   28494   p = sqlite3_malloc( sizeof(*p) );
   28495   if( p==0 ) return SQLITE_NOMEM;
   28496   memset(p, 0, sizeof(*p));
   28497   assert( pDbFd->pShm==0 );
   28498 
   28499   /* Check to see if a unixShmNode object already exists. Reuse an existing
   28500   ** one if present. Create a new one if necessary.
   28501   */
   28502   unixEnterMutex();
   28503   pInode = pDbFd->pInode;
   28504   pShmNode = pInode->pShmNode;
   28505   if( pShmNode==0 ){
   28506     struct stat sStat;                 /* fstat() info for database file */
   28507 
   28508     /* Call fstat() to figure out the permissions on the database file. If
   28509     ** a new *-shm file is created, an attempt will be made to create it
   28510     ** with the same permissions.
   28511     */
   28512     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
   28513       rc = SQLITE_IOERR_FSTAT;
   28514       goto shm_open_err;
   28515     }
   28516 
   28517 #ifdef SQLITE_SHM_DIRECTORY
   28518     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
   28519 #else
   28520     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
   28521 #endif
   28522     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
   28523     if( pShmNode==0 ){
   28524       rc = SQLITE_NOMEM;
   28525       goto shm_open_err;
   28526     }
   28527     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
   28528     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
   28529 #ifdef SQLITE_SHM_DIRECTORY
   28530     sqlite3_snprintf(nShmFilename, zShmFilename,
   28531                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
   28532                      (u32)sStat.st_ino, (u32)sStat.st_dev);
   28533 #else
   28534     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
   28535     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
   28536 #endif
   28537     pShmNode->h = -1;
   28538     pDbFd->pInode->pShmNode = pShmNode;
   28539     pShmNode->pInode = pDbFd->pInode;
   28540     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   28541     if( pShmNode->mutex==0 ){
   28542       rc = SQLITE_NOMEM;
   28543       goto shm_open_err;
   28544     }
   28545 
   28546     if( pInode->bProcessLock==0 ){
   28547       int openFlags = O_RDWR | O_CREAT;
   28548       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
   28549         openFlags = O_RDONLY;
   28550         pShmNode->isReadonly = 1;
   28551       }
   28552       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
   28553       if( pShmNode->h<0 ){
   28554         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
   28555         goto shm_open_err;
   28556       }
   28557 
   28558       /* If this process is running as root, make sure that the SHM file
   28559       ** is owned by the same user that owns the original database.  Otherwise,
   28560       ** the original owner will not be able to connect.
   28561       */
   28562       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
   28563 
   28564       /* Check to see if another process is holding the dead-man switch.
   28565       ** If not, truncate the file to zero length.
   28566       */
   28567       rc = SQLITE_OK;
   28568       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
   28569         if( robust_ftruncate(pShmNode->h, 0) ){
   28570           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
   28571         }
   28572       }
   28573       if( rc==SQLITE_OK ){
   28574         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
   28575       }
   28576       if( rc ) goto shm_open_err;
   28577     }
   28578   }
   28579 
   28580   /* Make the new connection a child of the unixShmNode */
   28581   p->pShmNode = pShmNode;
   28582 #ifdef SQLITE_DEBUG
   28583   p->id = pShmNode->nextShmId++;
   28584 #endif
   28585   pShmNode->nRef++;
   28586   pDbFd->pShm = p;
   28587   unixLeaveMutex();
   28588 
   28589   /* The reference count on pShmNode has already been incremented under
   28590   ** the cover of the unixEnterMutex() mutex and the pointer from the
   28591   ** new (struct unixShm) object to the pShmNode has been set. All that is
   28592   ** left to do is to link the new object into the linked list starting
   28593   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   28594   ** mutex.
   28595   */
   28596   sqlite3_mutex_enter(pShmNode->mutex);
   28597   p->pNext = pShmNode->pFirst;
   28598   pShmNode->pFirst = p;
   28599   sqlite3_mutex_leave(pShmNode->mutex);
   28600   return SQLITE_OK;
   28601 
   28602   /* Jump here on any error */
   28603 shm_open_err:
   28604   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
   28605   sqlite3_free(p);
   28606   unixLeaveMutex();
   28607   return rc;
   28608 }
   28609 
   28610 /*
   28611 ** This function is called to obtain a pointer to region iRegion of the
   28612 ** shared-memory associated with the database file fd. Shared-memory regions
   28613 ** are numbered starting from zero. Each shared-memory region is szRegion
   28614 ** bytes in size.
   28615 **
   28616 ** If an error occurs, an error code is returned and *pp is set to NULL.
   28617 **
   28618 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
   28619 ** region has not been allocated (by any client, including one running in a
   28620 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   28621 ** bExtend is non-zero and the requested shared-memory region has not yet
   28622 ** been allocated, it is allocated by this function.
   28623 **
   28624 ** If the shared-memory region has already been allocated or is allocated by
   28625 ** this call as described above, then it is mapped into this processes
   28626 ** address space (if it is not already), *pp is set to point to the mapped
   28627 ** memory and SQLITE_OK returned.
   28628 */
   28629 static int unixShmMap(
   28630   sqlite3_file *fd,               /* Handle open on database file */
   28631   int iRegion,                    /* Region to retrieve */
   28632   int szRegion,                   /* Size of regions */
   28633   int bExtend,                    /* True to extend file if necessary */
   28634   void volatile **pp              /* OUT: Mapped memory */
   28635 ){
   28636   unixFile *pDbFd = (unixFile*)fd;
   28637   unixShm *p;
   28638   unixShmNode *pShmNode;
   28639   int rc = SQLITE_OK;
   28640   int nShmPerMap = unixShmRegionPerMap();
   28641   int nReqRegion;
   28642 
   28643   /* If the shared-memory file has not yet been opened, open it now. */
   28644   if( pDbFd->pShm==0 ){
   28645     rc = unixOpenSharedMemory(pDbFd);
   28646     if( rc!=SQLITE_OK ) return rc;
   28647   }
   28648 
   28649   p = pDbFd->pShm;
   28650   pShmNode = p->pShmNode;
   28651   sqlite3_mutex_enter(pShmNode->mutex);
   28652   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   28653   assert( pShmNode->pInode==pDbFd->pInode );
   28654   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   28655   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   28656 
   28657   /* Minimum number of regions required to be mapped. */
   28658   nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
   28659 
   28660   if( pShmNode->nRegion<nReqRegion ){
   28661     char **apNew;                      /* New apRegion[] array */
   28662     int nByte = nReqRegion*szRegion;   /* Minimum required file size */
   28663     struct stat sStat;                 /* Used by fstat() */
   28664 
   28665     pShmNode->szRegion = szRegion;
   28666 
   28667     if( pShmNode->h>=0 ){
   28668       /* The requested region is not mapped into this processes address space.
   28669       ** Check to see if it has been allocated (i.e. if the wal-index file is
   28670       ** large enough to contain the requested region).
   28671       */
   28672       if( osFstat(pShmNode->h, &sStat) ){
   28673         rc = SQLITE_IOERR_SHMSIZE;
   28674         goto shmpage_out;
   28675       }
   28676 
   28677       if( sStat.st_size<nByte ){
   28678         /* The requested memory region does not exist. If bExtend is set to
   28679         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
   28680         */
   28681         if( !bExtend ){
   28682           goto shmpage_out;
   28683         }
   28684 
   28685         /* Alternatively, if bExtend is true, extend the file. Do this by
   28686         ** writing a single byte to the end of each (OS) page being
   28687         ** allocated or extended. Technically, we need only write to the
   28688         ** last page in order to extend the file. But writing to all new
   28689         ** pages forces the OS to allocate them immediately, which reduces
   28690         ** the chances of SIGBUS while accessing the mapped region later on.
   28691         */
   28692         else{
   28693           static const int pgsz = 4096;
   28694           int iPg;
   28695 
   28696           /* Write to the last byte of each newly allocated or extended page */
   28697           assert( (nByte % pgsz)==0 );
   28698           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
   28699             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
   28700               const char *zFile = pShmNode->zFilename;
   28701               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
   28702               goto shmpage_out;
   28703             }
   28704           }
   28705         }
   28706       }
   28707     }
   28708 
   28709     /* Map the requested memory region into this processes address space. */
   28710     apNew = (char **)sqlite3_realloc(
   28711         pShmNode->apRegion, nReqRegion*sizeof(char *)
   28712     );
   28713     if( !apNew ){
   28714       rc = SQLITE_IOERR_NOMEM;
   28715       goto shmpage_out;
   28716     }
   28717     pShmNode->apRegion = apNew;
   28718     while( pShmNode->nRegion<nReqRegion ){
   28719       int nMap = szRegion*nShmPerMap;
   28720       int i;
   28721       void *pMem;
   28722       if( pShmNode->h>=0 ){
   28723         pMem = osMmap(0, nMap,
   28724             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
   28725             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
   28726         );
   28727         if( pMem==MAP_FAILED ){
   28728           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
   28729           goto shmpage_out;
   28730         }
   28731       }else{
   28732         pMem = sqlite3_malloc(szRegion);
   28733         if( pMem==0 ){
   28734           rc = SQLITE_NOMEM;
   28735           goto shmpage_out;
   28736         }
   28737         memset(pMem, 0, szRegion);
   28738       }
   28739 
   28740       for(i=0; i<nShmPerMap; i++){
   28741         pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
   28742       }
   28743       pShmNode->nRegion += nShmPerMap;
   28744     }
   28745   }
   28746 
   28747 shmpage_out:
   28748   if( pShmNode->nRegion>iRegion ){
   28749     *pp = pShmNode->apRegion[iRegion];
   28750   }else{
   28751     *pp = 0;
   28752   }
   28753   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
   28754   sqlite3_mutex_leave(pShmNode->mutex);
   28755   return rc;
   28756 }
   28757 
   28758 /*
   28759 ** Change the lock state for a shared-memory segment.
   28760 **
   28761 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
   28762 ** different here than in posix.  In xShmLock(), one can go from unlocked
   28763 ** to shared and back or from unlocked to exclusive and back.  But one may
   28764 ** not go from shared to exclusive or from exclusive to shared.
   28765 */
   28766 static int unixShmLock(
   28767   sqlite3_file *fd,          /* Database file holding the shared memory */
   28768   int ofst,                  /* First lock to acquire or release */
   28769   int n,                     /* Number of locks to acquire or release */
   28770   int flags                  /* What to do with the lock */
   28771 ){
   28772   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
   28773   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
   28774   unixShm *pX;                          /* For looping over all siblings */
   28775   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
   28776   int rc = SQLITE_OK;                   /* Result code */
   28777   u16 mask;                             /* Mask of locks to take or release */
   28778 
   28779   assert( pShmNode==pDbFd->pInode->pShmNode );
   28780   assert( pShmNode->pInode==pDbFd->pInode );
   28781   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   28782   assert( n>=1 );
   28783   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   28784        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   28785        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   28786        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   28787   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   28788   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   28789   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   28790 
   28791   mask = (1<<(ofst+n)) - (1<<ofst);
   28792   assert( n>1 || mask==(1<<ofst) );
   28793   sqlite3_mutex_enter(pShmNode->mutex);
   28794   if( flags & SQLITE_SHM_UNLOCK ){
   28795     u16 allMask = 0; /* Mask of locks held by siblings */
   28796 
   28797     /* See if any siblings hold this same lock */
   28798     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   28799       if( pX==p ) continue;
   28800       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   28801       allMask |= pX->sharedMask;
   28802     }
   28803 
   28804     /* Unlock the system-level locks */
   28805     if( (mask & allMask)==0 ){
   28806       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
   28807     }else{
   28808       rc = SQLITE_OK;
   28809     }
   28810 
   28811     /* Undo the local locks */
   28812     if( rc==SQLITE_OK ){
   28813       p->exclMask &= ~mask;
   28814       p->sharedMask &= ~mask;
   28815     }
   28816   }else if( flags & SQLITE_SHM_SHARED ){
   28817     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   28818 
   28819     /* Find out which shared locks are already held by sibling connections.
   28820     ** If any sibling already holds an exclusive lock, go ahead and return
   28821     ** SQLITE_BUSY.
   28822     */
   28823     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   28824       if( (pX->exclMask & mask)!=0 ){
   28825         rc = SQLITE_BUSY;
   28826         break;
   28827       }
   28828       allShared |= pX->sharedMask;
   28829     }
   28830 
   28831     /* Get shared locks at the system level, if necessary */
   28832     if( rc==SQLITE_OK ){
   28833       if( (allShared & mask)==0 ){
   28834         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
   28835       }else{
   28836         rc = SQLITE_OK;
   28837       }
   28838     }
   28839 
   28840     /* Get the local shared locks */
   28841     if( rc==SQLITE_OK ){
   28842       p->sharedMask |= mask;
   28843     }
   28844   }else{
   28845     /* Make sure no sibling connections hold locks that will block this
   28846     ** lock.  If any do, return SQLITE_BUSY right away.
   28847     */
   28848     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   28849       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   28850         rc = SQLITE_BUSY;
   28851         break;
   28852       }
   28853     }
   28854 
   28855     /* Get the exclusive locks at the system level.  Then if successful
   28856     ** also mark the local connection as being locked.
   28857     */
   28858     if( rc==SQLITE_OK ){
   28859       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
   28860       if( rc==SQLITE_OK ){
   28861         assert( (p->sharedMask & mask)==0 );
   28862         p->exclMask |= mask;
   28863       }
   28864     }
   28865   }
   28866   sqlite3_mutex_leave(pShmNode->mutex);
   28867   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
   28868            p->id, getpid(), p->sharedMask, p->exclMask));
   28869   return rc;
   28870 }
   28871 
   28872 /*
   28873 ** Implement a memory barrier or memory fence on shared memory.
   28874 **
   28875 ** All loads and stores begun before the barrier must complete before
   28876 ** any load or store begun after the barrier.
   28877 */
   28878 static void unixShmBarrier(
   28879   sqlite3_file *fd                /* Database file holding the shared memory */
   28880 ){
   28881   UNUSED_PARAMETER(fd);
   28882   unixEnterMutex();
   28883   unixLeaveMutex();
   28884 }
   28885 
   28886 /*
   28887 ** Close a connection to shared-memory.  Delete the underlying
   28888 ** storage if deleteFlag is true.
   28889 **
   28890 ** If there is no shared memory associated with the connection then this
   28891 ** routine is a harmless no-op.
   28892 */
   28893 static int unixShmUnmap(
   28894   sqlite3_file *fd,               /* The underlying database file */
   28895   int deleteFlag                  /* Delete shared-memory if true */
   28896 ){
   28897   unixShm *p;                     /* The connection to be closed */
   28898   unixShmNode *pShmNode;          /* The underlying shared-memory file */
   28899   unixShm **pp;                   /* For looping over sibling connections */
   28900   unixFile *pDbFd;                /* The underlying database file */
   28901 
   28902   pDbFd = (unixFile*)fd;
   28903   p = pDbFd->pShm;
   28904   if( p==0 ) return SQLITE_OK;
   28905   pShmNode = p->pShmNode;
   28906 
   28907   assert( pShmNode==pDbFd->pInode->pShmNode );
   28908   assert( pShmNode->pInode==pDbFd->pInode );
   28909 
   28910   /* Remove connection p from the set of connections associated
   28911   ** with pShmNode */
   28912   sqlite3_mutex_enter(pShmNode->mutex);
   28913   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   28914   *pp = p->pNext;
   28915 
   28916   /* Free the connection p */
   28917   sqlite3_free(p);
   28918   pDbFd->pShm = 0;
   28919   sqlite3_mutex_leave(pShmNode->mutex);
   28920 
   28921   /* If pShmNode->nRef has reached 0, then close the underlying
   28922   ** shared-memory file, too */
   28923   unixEnterMutex();
   28924   assert( pShmNode->nRef>0 );
   28925   pShmNode->nRef--;
   28926   if( pShmNode->nRef==0 ){
   28927     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
   28928     unixShmPurge(pDbFd);
   28929   }
   28930   unixLeaveMutex();
   28931 
   28932   return SQLITE_OK;
   28933 }
   28934 
   28935 
   28936 #else
   28937 # define unixShmMap     0
   28938 # define unixShmLock    0
   28939 # define unixShmBarrier 0
   28940 # define unixShmUnmap   0
   28941 #endif /* #ifndef SQLITE_OMIT_WAL */
   28942 
   28943 #if SQLITE_MAX_MMAP_SIZE>0
   28944 /*
   28945 ** If it is currently memory mapped, unmap file pFd.
   28946 */
   28947 static void unixUnmapfile(unixFile *pFd){
   28948   assert( pFd->nFetchOut==0 );
   28949   if( pFd->pMapRegion ){
   28950     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
   28951     pFd->pMapRegion = 0;
   28952     pFd->mmapSize = 0;
   28953     pFd->mmapSizeActual = 0;
   28954   }
   28955 }
   28956 
   28957 /*
   28958 ** Attempt to set the size of the memory mapping maintained by file
   28959 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
   28960 **
   28961 ** If successful, this function sets the following variables:
   28962 **
   28963 **       unixFile.pMapRegion
   28964 **       unixFile.mmapSize
   28965 **       unixFile.mmapSizeActual
   28966 **
   28967 ** If unsuccessful, an error message is logged via sqlite3_log() and
   28968 ** the three variables above are zeroed. In this case SQLite should
   28969 ** continue accessing the database using the xRead() and xWrite()
   28970 ** methods.
   28971 */
   28972 static void unixRemapfile(
   28973   unixFile *pFd,                  /* File descriptor object */
   28974   i64 nNew                        /* Required mapping size */
   28975 ){
   28976   const char *zErr = "mmap";
   28977   int h = pFd->h;                      /* File descriptor open on db file */
   28978   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
   28979   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
   28980   u8 *pNew = 0;                        /* Location of new mapping */
   28981   int flags = PROT_READ;               /* Flags to pass to mmap() */
   28982 
   28983   assert( pFd->nFetchOut==0 );
   28984   assert( nNew>pFd->mmapSize );
   28985   assert( nNew<=pFd->mmapSizeMax );
   28986   assert( nNew>0 );
   28987   assert( pFd->mmapSizeActual>=pFd->mmapSize );
   28988   assert( MAP_FAILED!=0 );
   28989 
   28990   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
   28991 
   28992   if( pOrig ){
   28993 #if HAVE_MREMAP
   28994     i64 nReuse = pFd->mmapSize;
   28995 #else
   28996     const int szSyspage = osGetpagesize();
   28997     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
   28998 #endif
   28999     u8 *pReq = &pOrig[nReuse];
   29000 
   29001     /* Unmap any pages of the existing mapping that cannot be reused. */
   29002     if( nReuse!=nOrig ){
   29003       osMunmap(pReq, nOrig-nReuse);
   29004     }
   29005 
   29006 #if HAVE_MREMAP
   29007     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
   29008     zErr = "mremap";
   29009 #else
   29010     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
   29011     if( pNew!=MAP_FAILED ){
   29012       if( pNew!=pReq ){
   29013         osMunmap(pNew, nNew - nReuse);
   29014         pNew = 0;
   29015       }else{
   29016         pNew = pOrig;
   29017       }
   29018     }
   29019 #endif
   29020 
   29021     /* The attempt to extend the existing mapping failed. Free it. */
   29022     if( pNew==MAP_FAILED || pNew==0 ){
   29023       osMunmap(pOrig, nReuse);
   29024     }
   29025   }
   29026 
   29027   /* If pNew is still NULL, try to create an entirely new mapping. */
   29028   if( pNew==0 ){
   29029     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
   29030   }
   29031 
   29032   if( pNew==MAP_FAILED ){
   29033     pNew = 0;
   29034     nNew = 0;
   29035     unixLogError(SQLITE_OK, zErr, pFd->zPath);
   29036 
   29037     /* If the mmap() above failed, assume that all subsequent mmap() calls
   29038     ** will probably fail too. Fall back to using xRead/xWrite exclusively
   29039     ** in this case.  */
   29040     pFd->mmapSizeMax = 0;
   29041   }
   29042   pFd->pMapRegion = (void *)pNew;
   29043   pFd->mmapSize = pFd->mmapSizeActual = nNew;
   29044 }
   29045 
   29046 /*
   29047 ** Memory map or remap the file opened by file-descriptor pFd (if the file
   29048 ** is already mapped, the existing mapping is replaced by the new). Or, if
   29049 ** there already exists a mapping for this file, and there are still
   29050 ** outstanding xFetch() references to it, this function is a no-op.
   29051 **
   29052 ** If parameter nByte is non-negative, then it is the requested size of
   29053 ** the mapping to create. Otherwise, if nByte is less than zero, then the
   29054 ** requested size is the size of the file on disk. The actual size of the
   29055 ** created mapping is either the requested size or the value configured
   29056 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
   29057 **
   29058 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
   29059 ** recreated as a result of outstanding references) or an SQLite error
   29060 ** code otherwise.
   29061 */
   29062 static int unixMapfile(unixFile *pFd, i64 nByte){
   29063   i64 nMap = nByte;
   29064   int rc;
   29065 
   29066   assert( nMap>=0 || pFd->nFetchOut==0 );
   29067   if( pFd->nFetchOut>0 ) return SQLITE_OK;
   29068 
   29069   if( nMap<0 ){
   29070     struct stat statbuf;          /* Low-level file information */
   29071     rc = osFstat(pFd->h, &statbuf);
   29072     if( rc!=SQLITE_OK ){
   29073       return SQLITE_IOERR_FSTAT;
   29074     }
   29075     nMap = statbuf.st_size;
   29076   }
   29077   if( nMap>pFd->mmapSizeMax ){
   29078     nMap = pFd->mmapSizeMax;
   29079   }
   29080 
   29081   if( nMap!=pFd->mmapSize ){
   29082     if( nMap>0 ){
   29083       unixRemapfile(pFd, nMap);
   29084     }else{
   29085       unixUnmapfile(pFd);
   29086     }
   29087   }
   29088 
   29089   return SQLITE_OK;
   29090 }
   29091 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   29092 
   29093 /*
   29094 ** If possible, return a pointer to a mapping of file fd starting at offset
   29095 ** iOff. The mapping must be valid for at least nAmt bytes.
   29096 **
   29097 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
   29098 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
   29099 ** Finally, if an error does occur, return an SQLite error code. The final
   29100 ** value of *pp is undefined in this case.
   29101 **
   29102 ** If this function does return a pointer, the caller must eventually
   29103 ** release the reference by calling unixUnfetch().
   29104 */
   29105 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
   29106 #if SQLITE_MAX_MMAP_SIZE>0
   29107   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
   29108 #endif
   29109   *pp = 0;
   29110 
   29111 #if SQLITE_MAX_MMAP_SIZE>0
   29112   if( pFd->mmapSizeMax>0 ){
   29113     if( pFd->pMapRegion==0 ){
   29114       int rc = unixMapfile(pFd, -1);
   29115       if( rc!=SQLITE_OK ) return rc;
   29116     }
   29117     if( pFd->mmapSize >= iOff+nAmt ){
   29118       *pp = &((u8 *)pFd->pMapRegion)[iOff];
   29119       pFd->nFetchOut++;
   29120     }
   29121   }
   29122 #endif
   29123   return SQLITE_OK;
   29124 }
   29125 
   29126 /*
   29127 ** If the third argument is non-NULL, then this function releases a
   29128 ** reference obtained by an earlier call to unixFetch(). The second
   29129 ** argument passed to this function must be the same as the corresponding
   29130 ** argument that was passed to the unixFetch() invocation.
   29131 **
   29132 ** Or, if the third argument is NULL, then this function is being called
   29133 ** to inform the VFS layer that, according to POSIX, any existing mapping
   29134 ** may now be invalid and should be unmapped.
   29135 */
   29136 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
   29137 #if SQLITE_MAX_MMAP_SIZE>0
   29138   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
   29139   UNUSED_PARAMETER(iOff);
   29140 
   29141   /* If p==0 (unmap the entire file) then there must be no outstanding
   29142   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
   29143   ** then there must be at least one outstanding.  */
   29144   assert( (p==0)==(pFd->nFetchOut==0) );
   29145 
   29146   /* If p!=0, it must match the iOff value. */
   29147   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
   29148 
   29149   if( p ){
   29150     pFd->nFetchOut--;
   29151   }else{
   29152     unixUnmapfile(pFd);
   29153   }
   29154 
   29155   assert( pFd->nFetchOut>=0 );
   29156 #else
   29157   UNUSED_PARAMETER(fd);
   29158   UNUSED_PARAMETER(p);
   29159   UNUSED_PARAMETER(iOff);
   29160 #endif
   29161   return SQLITE_OK;
   29162 }
   29163 
   29164 /*
   29165 ** Here ends the implementation of all sqlite3_file methods.
   29166 **
   29167 ********************** End sqlite3_file Methods *******************************
   29168 ******************************************************************************/
   29169 
   29170 /*
   29171 ** This division contains definitions of sqlite3_io_methods objects that
   29172 ** implement various file locking strategies.  It also contains definitions
   29173 ** of "finder" functions.  A finder-function is used to locate the appropriate
   29174 ** sqlite3_io_methods object for a particular database file.  The pAppData
   29175 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
   29176 ** the correct finder-function for that VFS.
   29177 **
   29178 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
   29179 ** object.  The only interesting finder-function is autolockIoFinder, which
   29180 ** looks at the filesystem type and tries to guess the best locking
   29181 ** strategy from that.
   29182 **
   29183 ** For finder-funtion F, two objects are created:
   29184 **
   29185 **    (1) The real finder-function named "FImpt()".
   29186 **
   29187 **    (2) A constant pointer to this function named just "F".
   29188 **
   29189 **
   29190 ** A pointer to the F pointer is used as the pAppData value for VFS
   29191 ** objects.  We have to do this instead of letting pAppData point
   29192 ** directly at the finder-function since C90 rules prevent a void*
   29193 ** from be cast into a function pointer.
   29194 **
   29195 **
   29196 ** Each instance of this macro generates two objects:
   29197 **
   29198 **   *  A constant sqlite3_io_methods object call METHOD that has locking
   29199 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
   29200 **
   29201 **   *  An I/O method finder function called FINDER that returns a pointer
   29202 **      to the METHOD object in the previous bullet.
   29203 */
   29204 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
   29205 static const sqlite3_io_methods METHOD = {                                   \
   29206    VERSION,                    /* iVersion */                                \
   29207    CLOSE,                      /* xClose */                                  \
   29208    unixRead,                   /* xRead */                                   \
   29209    unixWrite,                  /* xWrite */                                  \
   29210    unixTruncate,               /* xTruncate */                               \
   29211    unixSync,                   /* xSync */                                   \
   29212    unixFileSize,               /* xFileSize */                               \
   29213    LOCK,                       /* xLock */                                   \
   29214    UNLOCK,                     /* xUnlock */                                 \
   29215    CKLOCK,                     /* xCheckReservedLock */                      \
   29216    unixFileControl,            /* xFileControl */                            \
   29217    unixSectorSize,             /* xSectorSize */                             \
   29218    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
   29219    unixShmMap,                 /* xShmMap */                                 \
   29220    unixShmLock,                /* xShmLock */                                \
   29221    unixShmBarrier,             /* xShmBarrier */                             \
   29222    unixShmUnmap,               /* xShmUnmap */                               \
   29223    unixFetch,                  /* xFetch */                                  \
   29224    unixUnfetch,                /* xUnfetch */                                \
   29225 };                                                                           \
   29226 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
   29227   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
   29228   return &METHOD;                                                            \
   29229 }                                                                            \
   29230 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
   29231     = FINDER##Impl;
   29232 
   29233 /*
   29234 ** Here are all of the sqlite3_io_methods objects for each of the
   29235 ** locking strategies.  Functions that return pointers to these methods
   29236 ** are also created.
   29237 */
   29238 IOMETHODS(
   29239   posixIoFinder,            /* Finder function name */
   29240   posixIoMethods,           /* sqlite3_io_methods object name */
   29241   3,                        /* shared memory and mmap are enabled */
   29242   unixClose,                /* xClose method */
   29243   unixLock,                 /* xLock method */
   29244   unixUnlock,               /* xUnlock method */
   29245   unixCheckReservedLock     /* xCheckReservedLock method */
   29246 )
   29247 IOMETHODS(
   29248   nolockIoFinder,           /* Finder function name */
   29249   nolockIoMethods,          /* sqlite3_io_methods object name */
   29250   1,                        /* shared memory is disabled */
   29251   nolockClose,              /* xClose method */
   29252   nolockLock,               /* xLock method */
   29253   nolockUnlock,             /* xUnlock method */
   29254   nolockCheckReservedLock   /* xCheckReservedLock method */
   29255 )
   29256 IOMETHODS(
   29257   dotlockIoFinder,          /* Finder function name */
   29258   dotlockIoMethods,         /* sqlite3_io_methods object name */
   29259   1,                        /* shared memory is disabled */
   29260   dotlockClose,             /* xClose method */
   29261   dotlockLock,              /* xLock method */
   29262   dotlockUnlock,            /* xUnlock method */
   29263   dotlockCheckReservedLock  /* xCheckReservedLock method */
   29264 )
   29265 
   29266 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   29267 IOMETHODS(
   29268   flockIoFinder,            /* Finder function name */
   29269   flockIoMethods,           /* sqlite3_io_methods object name */
   29270   1,                        /* shared memory is disabled */
   29271   flockClose,               /* xClose method */
   29272   flockLock,                /* xLock method */
   29273   flockUnlock,              /* xUnlock method */
   29274   flockCheckReservedLock    /* xCheckReservedLock method */
   29275 )
   29276 #endif
   29277 
   29278 #if OS_VXWORKS
   29279 IOMETHODS(
   29280   semIoFinder,              /* Finder function name */
   29281   semIoMethods,             /* sqlite3_io_methods object name */
   29282   1,                        /* shared memory is disabled */
   29283   semClose,                 /* xClose method */
   29284   semLock,                  /* xLock method */
   29285   semUnlock,                /* xUnlock method */
   29286   semCheckReservedLock      /* xCheckReservedLock method */
   29287 )
   29288 #endif
   29289 
   29290 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29291 IOMETHODS(
   29292   afpIoFinder,              /* Finder function name */
   29293   afpIoMethods,             /* sqlite3_io_methods object name */
   29294   1,                        /* shared memory is disabled */
   29295   afpClose,                 /* xClose method */
   29296   afpLock,                  /* xLock method */
   29297   afpUnlock,                /* xUnlock method */
   29298   afpCheckReservedLock      /* xCheckReservedLock method */
   29299 )
   29300 #endif
   29301 
   29302 /*
   29303 ** The proxy locking method is a "super-method" in the sense that it
   29304 ** opens secondary file descriptors for the conch and lock files and
   29305 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
   29306 ** secondary files.  For this reason, the division that implements
   29307 ** proxy locking is located much further down in the file.  But we need
   29308 ** to go ahead and define the sqlite3_io_methods and finder function
   29309 ** for proxy locking here.  So we forward declare the I/O methods.
   29310 */
   29311 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29312 static int proxyClose(sqlite3_file*);
   29313 static int proxyLock(sqlite3_file*, int);
   29314 static int proxyUnlock(sqlite3_file*, int);
   29315 static int proxyCheckReservedLock(sqlite3_file*, int*);
   29316 IOMETHODS(
   29317   proxyIoFinder,            /* Finder function name */
   29318   proxyIoMethods,           /* sqlite3_io_methods object name */
   29319   1,                        /* shared memory is disabled */
   29320   proxyClose,               /* xClose method */
   29321   proxyLock,                /* xLock method */
   29322   proxyUnlock,              /* xUnlock method */
   29323   proxyCheckReservedLock    /* xCheckReservedLock method */
   29324 )
   29325 #endif
   29326 
   29327 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
   29328 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29329 IOMETHODS(
   29330   nfsIoFinder,               /* Finder function name */
   29331   nfsIoMethods,              /* sqlite3_io_methods object name */
   29332   1,                         /* shared memory is disabled */
   29333   unixClose,                 /* xClose method */
   29334   unixLock,                  /* xLock method */
   29335   nfsUnlock,                 /* xUnlock method */
   29336   unixCheckReservedLock      /* xCheckReservedLock method */
   29337 )
   29338 #endif
   29339 
   29340 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29341 /*
   29342 ** This "finder" function attempts to determine the best locking strategy
   29343 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   29344 ** object that implements that strategy.
   29345 **
   29346 ** This is for MacOSX only.
   29347 */
   29348 static const sqlite3_io_methods *autolockIoFinderImpl(
   29349   const char *filePath,    /* name of the database file */
   29350   unixFile *pNew           /* open file object for the database file */
   29351 ){
   29352   static const struct Mapping {
   29353     const char *zFilesystem;              /* Filesystem type name */
   29354     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
   29355   } aMap[] = {
   29356     { "hfs",    &posixIoMethods },
   29357     { "ufs",    &posixIoMethods },
   29358     { "afpfs",  &afpIoMethods },
   29359     { "smbfs",  &afpIoMethods },
   29360     { "webdav", &nolockIoMethods },
   29361     { 0, 0 }
   29362   };
   29363   int i;
   29364   struct statfs fsInfo;
   29365   struct flock lockInfo;
   29366 
   29367   if( !filePath ){
   29368     /* If filePath==NULL that means we are dealing with a transient file
   29369     ** that does not need to be locked. */
   29370     return &nolockIoMethods;
   29371   }
   29372   if( statfs(filePath, &fsInfo) != -1 ){
   29373     if( fsInfo.f_flags & MNT_RDONLY ){
   29374       return &nolockIoMethods;
   29375     }
   29376     for(i=0; aMap[i].zFilesystem; i++){
   29377       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
   29378         return aMap[i].pMethods;
   29379       }
   29380     }
   29381   }
   29382 
   29383   /* Default case. Handles, amongst others, "nfs".
   29384   ** Test byte-range lock using fcntl(). If the call succeeds,
   29385   ** assume that the file-system supports POSIX style locks.
   29386   */
   29387   lockInfo.l_len = 1;
   29388   lockInfo.l_start = 0;
   29389   lockInfo.l_whence = SEEK_SET;
   29390   lockInfo.l_type = F_RDLCK;
   29391   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   29392     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
   29393       return &nfsIoMethods;
   29394     } else {
   29395       return &posixIoMethods;
   29396     }
   29397   }else{
   29398     return &dotlockIoMethods;
   29399   }
   29400 }
   29401 static const sqlite3_io_methods
   29402   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   29403 
   29404 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   29405 
   29406 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
   29407 /*
   29408 ** This "finder" function attempts to determine the best locking strategy
   29409 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   29410 ** object that implements that strategy.
   29411 **
   29412 ** This is for VXWorks only.
   29413 */
   29414 static const sqlite3_io_methods *autolockIoFinderImpl(
   29415   const char *filePath,    /* name of the database file */
   29416   unixFile *pNew           /* the open file object */
   29417 ){
   29418   struct flock lockInfo;
   29419 
   29420   if( !filePath ){
   29421     /* If filePath==NULL that means we are dealing with a transient file
   29422     ** that does not need to be locked. */
   29423     return &nolockIoMethods;
   29424   }
   29425 
   29426   /* Test if fcntl() is supported and use POSIX style locks.
   29427   ** Otherwise fall back to the named semaphore method.
   29428   */
   29429   lockInfo.l_len = 1;
   29430   lockInfo.l_start = 0;
   29431   lockInfo.l_whence = SEEK_SET;
   29432   lockInfo.l_type = F_RDLCK;
   29433   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   29434     return &posixIoMethods;
   29435   }else{
   29436     return &semIoMethods;
   29437   }
   29438 }
   29439 static const sqlite3_io_methods
   29440   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   29441 
   29442 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
   29443 
   29444 /*
   29445 ** An abstract type for a pointer to a IO method finder function:
   29446 */
   29447 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
   29448 
   29449 
   29450 /****************************************************************************
   29451 **************************** sqlite3_vfs methods ****************************
   29452 **
   29453 ** This division contains the implementation of methods on the
   29454 ** sqlite3_vfs object.
   29455 */
   29456 
   29457 /*
   29458 ** Initialize the contents of the unixFile structure pointed to by pId.
   29459 */
   29460 static int fillInUnixFile(
   29461   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
   29462   int h,                  /* Open file descriptor of file being opened */
   29463   sqlite3_file *pId,      /* Write to the unixFile structure here */
   29464   const char *zFilename,  /* Name of the file being opened */
   29465   int ctrlFlags           /* Zero or more UNIXFILE_* values */
   29466 ){
   29467   const sqlite3_io_methods *pLockingStyle;
   29468   unixFile *pNew = (unixFile *)pId;
   29469   int rc = SQLITE_OK;
   29470 
   29471   assert( pNew->pInode==NULL );
   29472 
   29473   /* Usually the path zFilename should not be a relative pathname. The
   29474   ** exception is when opening the proxy "conch" file in builds that
   29475   ** include the special Apple locking styles.
   29476   */
   29477 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29478   assert( zFilename==0 || zFilename[0]=='/'
   29479     || pVfs->pAppData==(void*)&autolockIoFinder );
   29480 #else
   29481   assert( zFilename==0 || zFilename[0]=='/' );
   29482 #endif
   29483 
   29484   /* No locking occurs in temporary files */
   29485   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
   29486 
   29487   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
   29488   pNew->h = h;
   29489   pNew->pVfs = pVfs;
   29490   pNew->zPath = zFilename;
   29491   pNew->ctrlFlags = (u8)ctrlFlags;
   29492 #if SQLITE_MAX_MMAP_SIZE>0
   29493   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
   29494 #endif
   29495   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
   29496                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   29497     pNew->ctrlFlags |= UNIXFILE_PSOW;
   29498   }
   29499   if( strcmp(pVfs->zName,"unix-excl")==0 ){
   29500     pNew->ctrlFlags |= UNIXFILE_EXCL;
   29501   }
   29502 
   29503 #if OS_VXWORKS
   29504   pNew->pId = vxworksFindFileId(zFilename);
   29505   if( pNew->pId==0 ){
   29506     ctrlFlags |= UNIXFILE_NOLOCK;
   29507     rc = SQLITE_NOMEM;
   29508   }
   29509 #endif
   29510 
   29511   if( ctrlFlags & UNIXFILE_NOLOCK ){
   29512     pLockingStyle = &nolockIoMethods;
   29513   }else{
   29514     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
   29515 #if SQLITE_ENABLE_LOCKING_STYLE
   29516     /* Cache zFilename in the locking context (AFP and dotlock override) for
   29517     ** proxyLock activation is possible (remote proxy is based on db name)
   29518     ** zFilename remains valid until file is closed, to support */
   29519     pNew->lockingContext = (void*)zFilename;
   29520 #endif
   29521   }
   29522 
   29523   if( pLockingStyle == &posixIoMethods
   29524 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29525     || pLockingStyle == &nfsIoMethods
   29526 #endif
   29527   ){
   29528     unixEnterMutex();
   29529     rc = findInodeInfo(pNew, &pNew->pInode);
   29530     if( rc!=SQLITE_OK ){
   29531       /* If an error occurred in findInodeInfo(), close the file descriptor
   29532       ** immediately, before releasing the mutex. findInodeInfo() may fail
   29533       ** in two scenarios:
   29534       **
   29535       **   (a) A call to fstat() failed.
   29536       **   (b) A malloc failed.
   29537       **
   29538       ** Scenario (b) may only occur if the process is holding no other
   29539       ** file descriptors open on the same file. If there were other file
   29540       ** descriptors on this file, then no malloc would be required by
   29541       ** findInodeInfo(). If this is the case, it is quite safe to close
   29542       ** handle h - as it is guaranteed that no posix locks will be released
   29543       ** by doing so.
   29544       **
   29545       ** If scenario (a) caused the error then things are not so safe. The
   29546       ** implicit assumption here is that if fstat() fails, things are in
   29547       ** such bad shape that dropping a lock or two doesn't matter much.
   29548       */
   29549       robust_close(pNew, h, __LINE__);
   29550       h = -1;
   29551     }
   29552     unixLeaveMutex();
   29553   }
   29554 
   29555 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29556   else if( pLockingStyle == &afpIoMethods ){
   29557     /* AFP locking uses the file path so it needs to be included in
   29558     ** the afpLockingContext.
   29559     */
   29560     afpLockingContext *pCtx;
   29561     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
   29562     if( pCtx==0 ){
   29563       rc = SQLITE_NOMEM;
   29564     }else{
   29565       /* NB: zFilename exists and remains valid until the file is closed
   29566       ** according to requirement F11141.  So we do not need to make a
   29567       ** copy of the filename. */
   29568       pCtx->dbPath = zFilename;
   29569       pCtx->reserved = 0;
   29570       srandomdev();
   29571       unixEnterMutex();
   29572       rc = findInodeInfo(pNew, &pNew->pInode);
   29573       if( rc!=SQLITE_OK ){
   29574         sqlite3_free(pNew->lockingContext);
   29575         robust_close(pNew, h, __LINE__);
   29576         h = -1;
   29577       }
   29578       unixLeaveMutex();
   29579     }
   29580   }
   29581 #endif
   29582 
   29583   else if( pLockingStyle == &dotlockIoMethods ){
   29584     /* Dotfile locking uses the file path so it needs to be included in
   29585     ** the dotlockLockingContext
   29586     */
   29587     char *zLockFile;
   29588     int nFilename;
   29589     assert( zFilename!=0 );
   29590     nFilename = (int)strlen(zFilename) + 6;
   29591     zLockFile = (char *)sqlite3_malloc(nFilename);
   29592     if( zLockFile==0 ){
   29593       rc = SQLITE_NOMEM;
   29594     }else{
   29595       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
   29596     }
   29597     pNew->lockingContext = zLockFile;
   29598   }
   29599 
   29600 #if OS_VXWORKS
   29601   else if( pLockingStyle == &semIoMethods ){
   29602     /* Named semaphore locking uses the file path so it needs to be
   29603     ** included in the semLockingContext
   29604     */
   29605     unixEnterMutex();
   29606     rc = findInodeInfo(pNew, &pNew->pInode);
   29607     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
   29608       char *zSemName = pNew->pInode->aSemName;
   29609       int n;
   29610       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
   29611                        pNew->pId->zCanonicalName);
   29612       for( n=1; zSemName[n]; n++ )
   29613         if( zSemName[n]=='/' ) zSemName[n] = '_';
   29614       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
   29615       if( pNew->pInode->pSem == SEM_FAILED ){
   29616         rc = SQLITE_NOMEM;
   29617         pNew->pInode->aSemName[0] = '\0';
   29618       }
   29619     }
   29620     unixLeaveMutex();
   29621   }
   29622 #endif
   29623 
   29624   pNew->lastErrno = 0;
   29625 #if OS_VXWORKS
   29626   if( rc!=SQLITE_OK ){
   29627     if( h>=0 ) robust_close(pNew, h, __LINE__);
   29628     h = -1;
   29629     osUnlink(zFilename);
   29630     pNew->ctrlFlags |= UNIXFILE_DELETE;
   29631   }
   29632 #endif
   29633   if( rc!=SQLITE_OK ){
   29634     if( h>=0 ) robust_close(pNew, h, __LINE__);
   29635   }else{
   29636     pNew->pMethod = pLockingStyle;
   29637     OpenCounter(+1);
   29638     verifyDbFile(pNew);
   29639   }
   29640   return rc;
   29641 }
   29642 
   29643 /*
   29644 ** Return the name of a directory in which to put temporary files.
   29645 ** If no suitable temporary file directory can be found, return NULL.
   29646 */
   29647 static const char *unixTempFileDir(void){
   29648   static const char *azDirs[] = {
   29649      0,
   29650      0,
   29651      0,
   29652      "/var/tmp",
   29653      "/usr/tmp",
   29654      "/tmp",
   29655      0        /* List terminator */
   29656   };
   29657   unsigned int i;
   29658   struct stat buf;
   29659   const char *zDir = 0;
   29660 
   29661   azDirs[0] = sqlite3_temp_directory;
   29662   if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
   29663   if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
   29664   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   29665     if( zDir==0 ) continue;
   29666     if( osStat(zDir, &buf) ) continue;
   29667     if( !S_ISDIR(buf.st_mode) ) continue;
   29668     if( osAccess(zDir, 07) ) continue;
   29669     break;
   29670   }
   29671   return zDir;
   29672 }
   29673 
   29674 /*
   29675 ** Create a temporary file name in zBuf.  zBuf must be allocated
   29676 ** by the calling process and must be big enough to hold at least
   29677 ** pVfs->mxPathname bytes.
   29678 */
   29679 static int unixGetTempname(int nBuf, char *zBuf){
   29680   static const unsigned char zChars[] =
   29681     "abcdefghijklmnopqrstuvwxyz"
   29682     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   29683     "0123456789";
   29684   unsigned int i, j;
   29685   const char *zDir;
   29686 
   29687   /* It's odd to simulate an io-error here, but really this is just
   29688   ** using the io-error infrastructure to test that SQLite handles this
   29689   ** function failing.
   29690   */
   29691   SimulateIOError( return SQLITE_IOERR );
   29692 
   29693   zDir = unixTempFileDir();
   29694   if( zDir==0 ) zDir = ".";
   29695 
   29696   /* Check that the output buffer is large enough for the temporary file
   29697   ** name. If it is not, return SQLITE_ERROR.
   29698   */
   29699   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
   29700     return SQLITE_ERROR;
   29701   }
   29702 
   29703   do{
   29704     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
   29705     j = (int)strlen(zBuf);
   29706     sqlite3_randomness(15, &zBuf[j]);
   29707     for(i=0; i<15; i++, j++){
   29708       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   29709     }
   29710     zBuf[j] = 0;
   29711     zBuf[j+1] = 0;
   29712   }while( osAccess(zBuf,0)==0 );
   29713   return SQLITE_OK;
   29714 }
   29715 
   29716 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29717 /*
   29718 ** Routine to transform a unixFile into a proxy-locking unixFile.
   29719 ** Implementation in the proxy-lock division, but used by unixOpen()
   29720 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
   29721 */
   29722 static int proxyTransformUnixFile(unixFile*, const char*);
   29723 #endif
   29724 
   29725 /*
   29726 ** Search for an unused file descriptor that was opened on the database
   29727 ** file (not a journal or master-journal file) identified by pathname
   29728 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
   29729 ** argument to this function.
   29730 **
   29731 ** Such a file descriptor may exist if a database connection was closed
   29732 ** but the associated file descriptor could not be closed because some
   29733 ** other file descriptor open on the same file is holding a file-lock.
   29734 ** Refer to comments in the unixClose() function and the lengthy comment
   29735 ** describing "Posix Advisory Locking" at the start of this file for
   29736 ** further details. Also, ticket #4018.
   29737 **
   29738 ** If a suitable file descriptor is found, then it is returned. If no
   29739 ** such file descriptor is located, -1 is returned.
   29740 */
   29741 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
   29742   UnixUnusedFd *pUnused = 0;
   29743 
   29744   /* Do not search for an unused file descriptor on vxworks. Not because
   29745   ** vxworks would not benefit from the change (it might, we're not sure),
   29746   ** but because no way to test it is currently available. It is better
   29747   ** not to risk breaking vxworks support for the sake of such an obscure
   29748   ** feature.  */
   29749 #if !OS_VXWORKS
   29750   struct stat sStat;                   /* Results of stat() call */
   29751 
   29752   /* A stat() call may fail for various reasons. If this happens, it is
   29753   ** almost certain that an open() call on the same path will also fail.
   29754   ** For this reason, if an error occurs in the stat() call here, it is
   29755   ** ignored and -1 is returned. The caller will try to open a new file
   29756   ** descriptor on the same path, fail, and return an error to SQLite.
   29757   **
   29758   ** Even if a subsequent open() call does succeed, the consequences of
   29759   ** not searching for a resusable file descriptor are not dire.  */
   29760   if( 0==osStat(zPath, &sStat) ){
   29761     unixInodeInfo *pInode;
   29762 
   29763     unixEnterMutex();
   29764     pInode = inodeList;
   29765     while( pInode && (pInode->fileId.dev!=sStat.st_dev
   29766                      || pInode->fileId.ino!=sStat.st_ino) ){
   29767        pInode = pInode->pNext;
   29768     }
   29769     if( pInode ){
   29770       UnixUnusedFd **pp;
   29771       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
   29772       pUnused = *pp;
   29773       if( pUnused ){
   29774         *pp = pUnused->pNext;
   29775       }
   29776     }
   29777     unixLeaveMutex();
   29778   }
   29779 #endif    /* if !OS_VXWORKS */
   29780   return pUnused;
   29781 }
   29782 
   29783 /*
   29784 ** This function is called by unixOpen() to determine the unix permissions
   29785 ** to create new files with. If no error occurs, then SQLITE_OK is returned
   29786 ** and a value suitable for passing as the third argument to open(2) is
   29787 ** written to *pMode. If an IO error occurs, an SQLite error code is
   29788 ** returned and the value of *pMode is not modified.
   29789 **
   29790 ** In most cases cases, this routine sets *pMode to 0, which will become
   29791 ** an indication to robust_open() to create the file using
   29792 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
   29793 ** But if the file being opened is a WAL or regular journal file, then
   29794 ** this function queries the file-system for the permissions on the
   29795 ** corresponding database file and sets *pMode to this value. Whenever
   29796 ** possible, WAL and journal files are created using the same permissions
   29797 ** as the associated database file.
   29798 **
   29799 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
   29800 ** original filename is unavailable.  But 8_3_NAMES is only used for
   29801 ** FAT filesystems and permissions do not matter there, so just use
   29802 ** the default permissions.
   29803 */
   29804 static int findCreateFileMode(
   29805   const char *zPath,              /* Path of file (possibly) being created */
   29806   int flags,                      /* Flags passed as 4th argument to xOpen() */
   29807   mode_t *pMode,                  /* OUT: Permissions to open file with */
   29808   uid_t *pUid,                    /* OUT: uid to set on the file */
   29809   gid_t *pGid                     /* OUT: gid to set on the file */
   29810 ){
   29811   int rc = SQLITE_OK;             /* Return Code */
   29812   *pMode = 0;
   29813   *pUid = 0;
   29814   *pGid = 0;
   29815   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   29816     char zDb[MAX_PATHNAME+1];     /* Database file path */
   29817     int nDb;                      /* Number of valid bytes in zDb */
   29818     struct stat sStat;            /* Output of stat() on database file */
   29819 
   29820     /* zPath is a path to a WAL or journal file. The following block derives
   29821     ** the path to the associated database file from zPath. This block handles
   29822     ** the following naming conventions:
   29823     **
   29824     **   "<path to db>-journal"
   29825     **   "<path to db>-wal"
   29826     **   "<path to db>-journalNN"
   29827     **   "<path to db>-walNN"
   29828     **
   29829     ** where NN is a decimal number. The NN naming schemes are
   29830     ** used by the test_multiplex.c module.
   29831     */
   29832     nDb = sqlite3Strlen30(zPath) - 1;
   29833 #ifdef SQLITE_ENABLE_8_3_NAMES
   29834     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
   29835     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
   29836 #else
   29837     while( zPath[nDb]!='-' ){
   29838       assert( nDb>0 );
   29839       assert( zPath[nDb]!='\n' );
   29840       nDb--;
   29841     }
   29842 #endif
   29843     memcpy(zDb, zPath, nDb);
   29844     zDb[nDb] = '\0';
   29845 
   29846     if( 0==osStat(zDb, &sStat) ){
   29847       *pMode = sStat.st_mode & 0777;
   29848       *pUid = sStat.st_uid;
   29849       *pGid = sStat.st_gid;
   29850     }else{
   29851       rc = SQLITE_IOERR_FSTAT;
   29852     }
   29853   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   29854     *pMode = 0600;
   29855   }
   29856   return rc;
   29857 }
   29858 
   29859 /*
   29860 ** Open the file zPath.
   29861 **
   29862 ** Previously, the SQLite OS layer used three functions in place of this
   29863 ** one:
   29864 **
   29865 **     sqlite3OsOpenReadWrite();
   29866 **     sqlite3OsOpenReadOnly();
   29867 **     sqlite3OsOpenExclusive();
   29868 **
   29869 ** These calls correspond to the following combinations of flags:
   29870 **
   29871 **     ReadWrite() ->     (READWRITE | CREATE)
   29872 **     ReadOnly()  ->     (READONLY)
   29873 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
   29874 **
   29875 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
   29876 ** true, the file was configured to be automatically deleted when the
   29877 ** file handle closed. To achieve the same effect using this new
   29878 ** interface, add the DELETEONCLOSE flag to those specified above for
   29879 ** OpenExclusive().
   29880 */
   29881 static int unixOpen(
   29882   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
   29883   const char *zPath,           /* Pathname of file to be opened */
   29884   sqlite3_file *pFile,         /* The file descriptor to be filled in */
   29885   int flags,                   /* Input flags to control the opening */
   29886   int *pOutFlags               /* Output flags returned to SQLite core */
   29887 ){
   29888   unixFile *p = (unixFile *)pFile;
   29889   int fd = -1;                   /* File descriptor returned by open() */
   29890   int openFlags = 0;             /* Flags to pass to open() */
   29891   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   29892   int noLock;                    /* True to omit locking primitives */
   29893   int rc = SQLITE_OK;            /* Function Return Code */
   29894   int ctrlFlags = 0;             /* UNIXFILE_* flags */
   29895 
   29896   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   29897   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   29898   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   29899   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   29900   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   29901 #if SQLITE_ENABLE_LOCKING_STYLE
   29902   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
   29903 #endif
   29904 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   29905   struct statfs fsInfo;
   29906 #endif
   29907 
   29908   /* If creating a master or main-file journal, this function will open
   29909   ** a file-descriptor on the directory too. The first time unixSync()
   29910   ** is called the directory file descriptor will be fsync()ed and close()d.
   29911   */
   29912   int syncDir = (isCreate && (
   29913         eType==SQLITE_OPEN_MASTER_JOURNAL
   29914      || eType==SQLITE_OPEN_MAIN_JOURNAL
   29915      || eType==SQLITE_OPEN_WAL
   29916   ));
   29917 
   29918   /* If argument zPath is a NULL pointer, this function is required to open
   29919   ** a temporary file. Use this buffer to store the file name in.
   29920   */
   29921   char zTmpname[MAX_PATHNAME+2];
   29922   const char *zName = zPath;
   29923 
   29924   /* Check the following statements are true:
   29925   **
   29926   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   29927   **   (b) if CREATE is set, then READWRITE must also be set, and
   29928   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   29929   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   29930   */
   29931   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   29932   assert(isCreate==0 || isReadWrite);
   29933   assert(isExclusive==0 || isCreate);
   29934   assert(isDelete==0 || isCreate);
   29935 
   29936   /* The main DB, main journal, WAL file and master journal are never
   29937   ** automatically deleted. Nor are they ever temporary files.  */
   29938   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   29939   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   29940   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   29941   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   29942 
   29943   /* Assert that the upper layer has set one of the "file-type" flags. */
   29944   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   29945        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   29946        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   29947        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   29948   );
   29949 
   29950   /* Detect a pid change and reset the PRNG.  There is a race condition
   29951   ** here such that two or more threads all trying to open databases at
   29952   ** the same instant might all reset the PRNG.  But multiple resets
   29953   ** are harmless.
   29954   */
   29955   if( randomnessPid!=getpid() ){
   29956     randomnessPid = getpid();
   29957     sqlite3_randomness(0,0);
   29958   }
   29959 
   29960   memset(p, 0, sizeof(unixFile));
   29961 
   29962   if( eType==SQLITE_OPEN_MAIN_DB ){
   29963     UnixUnusedFd *pUnused;
   29964     pUnused = findReusableFd(zName, flags);
   29965     if( pUnused ){
   29966       fd = pUnused->fd;
   29967     }else{
   29968       pUnused = sqlite3_malloc(sizeof(*pUnused));
   29969       if( !pUnused ){
   29970         return SQLITE_NOMEM;
   29971       }
   29972     }
   29973     p->pUnused = pUnused;
   29974 
   29975     /* Database filenames are double-zero terminated if they are not
   29976     ** URIs with parameters.  Hence, they can always be passed into
   29977     ** sqlite3_uri_parameter(). */
   29978     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
   29979 
   29980   }else if( !zName ){
   29981     /* If zName is NULL, the upper layer is requesting a temp file. */
   29982     assert(isDelete && !syncDir);
   29983     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
   29984     if( rc!=SQLITE_OK ){
   29985       return rc;
   29986     }
   29987     zName = zTmpname;
   29988 
   29989     /* Generated temporary filenames are always double-zero terminated
   29990     ** for use by sqlite3_uri_parameter(). */
   29991     assert( zName[strlen(zName)+1]==0 );
   29992   }
   29993 
   29994   /* Determine the value of the flags parameter passed to POSIX function
   29995   ** open(). These must be calculated even if open() is not called, as
   29996   ** they may be stored as part of the file handle and used by the
   29997   ** 'conch file' locking functions later on.  */
   29998   if( isReadonly )  openFlags |= O_RDONLY;
   29999   if( isReadWrite ) openFlags |= O_RDWR;
   30000   if( isCreate )    openFlags |= O_CREAT;
   30001   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
   30002   openFlags |= (O_LARGEFILE|O_BINARY);
   30003 
   30004   if( fd<0 ){
   30005     mode_t openMode;              /* Permissions to create file with */
   30006     uid_t uid;                    /* Userid for the file */
   30007     gid_t gid;                    /* Groupid for the file */
   30008     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
   30009     if( rc!=SQLITE_OK ){
   30010       assert( !p->pUnused );
   30011       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
   30012       return rc;
   30013     }
   30014     fd = robust_open(zName, openFlags, openMode);
   30015     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
   30016     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
   30017       /* Failed to open the file for read/write access. Try read-only. */
   30018       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   30019       openFlags &= ~(O_RDWR|O_CREAT);
   30020       flags |= SQLITE_OPEN_READONLY;
   30021       openFlags |= O_RDONLY;
   30022       isReadonly = 1;
   30023       fd = robust_open(zName, openFlags, openMode);
   30024     }
   30025     if( fd<0 ){
   30026       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
   30027       goto open_finished;
   30028     }
   30029 
   30030     /* If this process is running as root and if creating a new rollback
   30031     ** journal or WAL file, set the ownership of the journal or WAL to be
   30032     ** the same as the original database.
   30033     */
   30034     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   30035       osFchown(fd, uid, gid);
   30036     }
   30037   }
   30038   assert( fd>=0 );
   30039   if( pOutFlags ){
   30040     *pOutFlags = flags;
   30041   }
   30042 
   30043   if( p->pUnused ){
   30044     p->pUnused->fd = fd;
   30045     p->pUnused->flags = flags;
   30046   }
   30047 
   30048   if( isDelete ){
   30049 #if OS_VXWORKS
   30050     zPath = zName;
   30051 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
   30052     zPath = sqlite3_mprintf("%s", zName);
   30053     if( zPath==0 ){
   30054       robust_close(p, fd, __LINE__);
   30055       return SQLITE_NOMEM;
   30056     }
   30057 #else
   30058     osUnlink(zName);
   30059 #endif
   30060   }
   30061 #if SQLITE_ENABLE_LOCKING_STYLE
   30062   else{
   30063     p->openFlags = openFlags;
   30064   }
   30065 #endif
   30066 
   30067   noLock = eType!=SQLITE_OPEN_MAIN_DB;
   30068 
   30069 
   30070 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   30071   if( fstatfs(fd, &fsInfo) == -1 ){
   30072     ((unixFile*)pFile)->lastErrno = errno;
   30073     robust_close(p, fd, __LINE__);
   30074     return SQLITE_IOERR_ACCESS;
   30075   }
   30076   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
   30077     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
   30078   }
   30079 #endif
   30080 
   30081   /* Set up appropriate ctrlFlags */
   30082   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
   30083   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
   30084   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
   30085   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
   30086   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
   30087 
   30088 #if SQLITE_ENABLE_LOCKING_STYLE
   30089 #if SQLITE_PREFER_PROXY_LOCKING
   30090   isAutoProxy = 1;
   30091 #endif
   30092   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
   30093     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
   30094     int useProxy = 0;
   30095 
   30096     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
   30097     ** never use proxy, NULL means use proxy for non-local files only.  */
   30098     if( envforce!=NULL ){
   30099       useProxy = atoi(envforce)>0;
   30100     }else{
   30101       if( statfs(zPath, &fsInfo) == -1 ){
   30102         /* In theory, the close(fd) call is sub-optimal. If the file opened
   30103         ** with fd is a database file, and there are other connections open
   30104         ** on that file that are currently holding advisory locks on it,
   30105         ** then the call to close() will cancel those locks. In practice,
   30106         ** we're assuming that statfs() doesn't fail very often. At least
   30107         ** not while other file descriptors opened by the same process on
   30108         ** the same file are working.  */
   30109         p->lastErrno = errno;
   30110         robust_close(p, fd, __LINE__);
   30111         rc = SQLITE_IOERR_ACCESS;
   30112         goto open_finished;
   30113       }
   30114       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
   30115     }
   30116     if( useProxy ){
   30117       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   30118       if( rc==SQLITE_OK ){
   30119         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
   30120         if( rc!=SQLITE_OK ){
   30121           /* Use unixClose to clean up the resources added in fillInUnixFile
   30122           ** and clear all the structure's references.  Specifically,
   30123           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
   30124           */
   30125           unixClose(pFile);
   30126           return rc;
   30127         }
   30128       }
   30129       goto open_finished;
   30130     }
   30131   }
   30132 #endif
   30133 
   30134   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   30135 
   30136 open_finished:
   30137   if( rc!=SQLITE_OK ){
   30138     sqlite3_free(p->pUnused);
   30139   }
   30140   return rc;
   30141 }
   30142 
   30143 
   30144 /*
   30145 ** Delete the file at zPath. If the dirSync argument is true, fsync()
   30146 ** the directory after deleting the file.
   30147 */
   30148 static int unixDelete(
   30149   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
   30150   const char *zPath,        /* Name of file to be deleted */
   30151   int dirSync               /* If true, fsync() directory after deleting file */
   30152 ){
   30153   int rc = SQLITE_OK;
   30154   UNUSED_PARAMETER(NotUsed);
   30155   SimulateIOError(return SQLITE_IOERR_DELETE);
   30156   if( osUnlink(zPath)==(-1) ){
   30157     if( errno==ENOENT
   30158 #if OS_VXWORKS
   30159         || errno==0x380003
   30160 #endif
   30161     ){
   30162       rc = SQLITE_IOERR_DELETE_NOENT;
   30163     }else{
   30164       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
   30165     }
   30166     return rc;
   30167   }
   30168 #ifndef SQLITE_DISABLE_DIRSYNC
   30169   if( (dirSync & 1)!=0 ){
   30170     int fd;
   30171     rc = osOpenDirectory(zPath, &fd);
   30172     if( rc==SQLITE_OK ){
   30173 #if OS_VXWORKS
   30174       if( fsync(fd)==-1 )
   30175 #else
   30176       if( fsync(fd) )
   30177 #endif
   30178       {
   30179         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
   30180       }
   30181       robust_close(0, fd, __LINE__);
   30182     }else if( rc==SQLITE_CANTOPEN ){
   30183       rc = SQLITE_OK;
   30184     }
   30185   }
   30186 #endif
   30187   return rc;
   30188 }
   30189 
   30190 /*
   30191 ** Test the existence of or access permissions of file zPath. The
   30192 ** test performed depends on the value of flags:
   30193 **
   30194 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
   30195 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
   30196 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
   30197 **
   30198 ** Otherwise return 0.
   30199 */
   30200 static int unixAccess(
   30201   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
   30202   const char *zPath,      /* Path of the file to examine */
   30203   int flags,              /* What do we want to learn about the zPath file? */
   30204   int *pResOut            /* Write result boolean here */
   30205 ){
   30206   int amode = 0;
   30207   UNUSED_PARAMETER(NotUsed);
   30208   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   30209   switch( flags ){
   30210     case SQLITE_ACCESS_EXISTS:
   30211       amode = F_OK;
   30212       break;
   30213     case SQLITE_ACCESS_READWRITE:
   30214       amode = W_OK|R_OK;
   30215       break;
   30216     case SQLITE_ACCESS_READ:
   30217       amode = R_OK;
   30218       break;
   30219 
   30220     default:
   30221       assert(!"Invalid flags argument");
   30222   }
   30223   *pResOut = (osAccess(zPath, amode)==0);
   30224   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
   30225     struct stat buf;
   30226     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
   30227       *pResOut = 0;
   30228     }
   30229   }
   30230   return SQLITE_OK;
   30231 }
   30232 
   30233 
   30234 /*
   30235 ** Turn a relative pathname into a full pathname. The relative path
   30236 ** is stored as a nul-terminated string in the buffer pointed to by
   30237 ** zPath.
   30238 **
   30239 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
   30240 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
   30241 ** this buffer before returning.
   30242 */
   30243 static int unixFullPathname(
   30244   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   30245   const char *zPath,            /* Possibly relative input path */
   30246   int nOut,                     /* Size of output buffer in bytes */
   30247   char *zOut                    /* Output buffer */
   30248 ){
   30249 
   30250   /* It's odd to simulate an io-error here, but really this is just
   30251   ** using the io-error infrastructure to test that SQLite handles this
   30252   ** function failing. This function could fail if, for example, the
   30253   ** current working directory has been unlinked.
   30254   */
   30255   SimulateIOError( return SQLITE_ERROR );
   30256 
   30257   assert( pVfs->mxPathname==MAX_PATHNAME );
   30258   UNUSED_PARAMETER(pVfs);
   30259 
   30260   zOut[nOut-1] = '\0';
   30261   if( zPath[0]=='/' ){
   30262     sqlite3_snprintf(nOut, zOut, "%s", zPath);
   30263   }else{
   30264     int nCwd;
   30265     if( osGetcwd(zOut, nOut-1)==0 ){
   30266       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
   30267     }
   30268     nCwd = (int)strlen(zOut);
   30269     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
   30270   }
   30271   return SQLITE_OK;
   30272 }
   30273 
   30274 
   30275 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   30276 /*
   30277 ** Interfaces for opening a shared library, finding entry points
   30278 ** within the shared library, and closing the shared library.
   30279 */
   30280 #include <dlfcn.h>
   30281 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
   30282   UNUSED_PARAMETER(NotUsed);
   30283   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
   30284 }
   30285 
   30286 /*
   30287 ** SQLite calls this function immediately after a call to unixDlSym() or
   30288 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
   30289 ** message is available, it is written to zBufOut. If no error message
   30290 ** is available, zBufOut is left unmodified and SQLite uses a default
   30291 ** error message.
   30292 */
   30293 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   30294   const char *zErr;
   30295   UNUSED_PARAMETER(NotUsed);
   30296   unixEnterMutex();
   30297   zErr = dlerror();
   30298   if( zErr ){
   30299     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
   30300   }
   30301   unixLeaveMutex();
   30302 }
   30303 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   30304   /*
   30305   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   30306   ** cast into a pointer to a function.  And yet the library dlsym() routine
   30307   ** returns a void* which is really a pointer to a function.  So how do we
   30308   ** use dlsym() with -pedantic-errors?
   30309   **
   30310   ** Variable x below is defined to be a pointer to a function taking
   30311   ** parameters void* and const char* and returning a pointer to a function.
   30312   ** We initialize x by assigning it a pointer to the dlsym() function.
   30313   ** (That assignment requires a cast.)  Then we call the function that
   30314   ** x points to.
   30315   **
   30316   ** This work-around is unlikely to work correctly on any system where
   30317   ** you really cannot cast a function pointer into void*.  But then, on the
   30318   ** other hand, dlsym() will not work on such a system either, so we have
   30319   ** not really lost anything.
   30320   */
   30321   void (*(*x)(void*,const char*))(void);
   30322   UNUSED_PARAMETER(NotUsed);
   30323   x = (void(*(*)(void*,const char*))(void))dlsym;
   30324   return (*x)(p, zSym);
   30325 }
   30326 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
   30327   UNUSED_PARAMETER(NotUsed);
   30328   dlclose(pHandle);
   30329 }
   30330 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   30331   #define unixDlOpen  0
   30332   #define unixDlError 0
   30333   #define unixDlSym   0
   30334   #define unixDlClose 0
   30335 #endif
   30336 
   30337 /*
   30338 ** Write nBuf bytes of random data to the supplied buffer zBuf.
   30339 */
   30340 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   30341   UNUSED_PARAMETER(NotUsed);
   30342   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
   30343 
   30344   /* We have to initialize zBuf to prevent valgrind from reporting
   30345   ** errors.  The reports issued by valgrind are incorrect - we would
   30346   ** prefer that the randomness be increased by making use of the
   30347   ** uninitialized space in zBuf - but valgrind errors tend to worry
   30348   ** some users.  Rather than argue, it seems easier just to initialize
   30349   ** the whole array and silence valgrind, even if that means less randomness
   30350   ** in the random seed.
   30351   **
   30352   ** When testing, initializing zBuf[] to zero is all we do.  That means
   30353   ** that we always use the same random number sequence.  This makes the
   30354   ** tests repeatable.
   30355   */
   30356   memset(zBuf, 0, nBuf);
   30357   randomnessPid = getpid();
   30358 #if !defined(SQLITE_TEST)
   30359   {
   30360     int fd, got;
   30361     fd = robust_open("/dev/urandom", O_RDONLY, 0);
   30362     if( fd<0 ){
   30363       time_t t;
   30364       time(&t);
   30365       memcpy(zBuf, &t, sizeof(t));
   30366       memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
   30367       assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
   30368       nBuf = sizeof(t) + sizeof(randomnessPid);
   30369     }else{
   30370       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
   30371       robust_close(0, fd, __LINE__);
   30372     }
   30373   }
   30374 #endif
   30375   return nBuf;
   30376 }
   30377 
   30378 
   30379 /*
   30380 ** Sleep for a little while.  Return the amount of time slept.
   30381 ** The argument is the number of microseconds we want to sleep.
   30382 ** The return value is the number of microseconds of sleep actually
   30383 ** requested from the underlying operating system, a number which
   30384 ** might be greater than or equal to the argument, but not less
   30385 ** than the argument.
   30386 */
   30387 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   30388 #if OS_VXWORKS
   30389   struct timespec sp;
   30390 
   30391   sp.tv_sec = microseconds / 1000000;
   30392   sp.tv_nsec = (microseconds % 1000000) * 1000;
   30393   nanosleep(&sp, NULL);
   30394   UNUSED_PARAMETER(NotUsed);
   30395   return microseconds;
   30396 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
   30397   usleep(microseconds);
   30398   UNUSED_PARAMETER(NotUsed);
   30399   return microseconds;
   30400 #else
   30401   int seconds = (microseconds+999999)/1000000;
   30402   sleep(seconds);
   30403   UNUSED_PARAMETER(NotUsed);
   30404   return seconds*1000000;
   30405 #endif
   30406 }
   30407 
   30408 /*
   30409 ** The following variable, if set to a non-zero value, is interpreted as
   30410 ** the number of seconds since 1970 and is used to set the result of
   30411 ** sqlite3OsCurrentTime() during testing.
   30412 */
   30413 #ifdef SQLITE_TEST
   30414 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   30415 #endif
   30416 
   30417 /*
   30418 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   30419 ** the current time and date as a Julian Day number times 86_400_000.  In
   30420 ** other words, write into *piNow the number of milliseconds since the Julian
   30421 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   30422 ** proleptic Gregorian calendar.
   30423 **
   30424 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   30425 ** cannot be found.
   30426 */
   30427 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
   30428   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   30429   int rc = SQLITE_OK;
   30430 #if defined(NO_GETTOD)
   30431   time_t t;
   30432   time(&t);
   30433   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
   30434 #elif OS_VXWORKS
   30435   struct timespec sNow;
   30436   clock_gettime(CLOCK_REALTIME, &sNow);
   30437   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
   30438 #else
   30439   struct timeval sNow;
   30440   if( gettimeofday(&sNow, 0)==0 ){
   30441     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
   30442   }else{
   30443     rc = SQLITE_ERROR;
   30444   }
   30445 #endif
   30446 
   30447 #ifdef SQLITE_TEST
   30448   if( sqlite3_current_time ){
   30449     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   30450   }
   30451 #endif
   30452   UNUSED_PARAMETER(NotUsed);
   30453   return rc;
   30454 }
   30455 
   30456 /*
   30457 ** Find the current time (in Universal Coordinated Time).  Write the
   30458 ** current time and date as a Julian Day number into *prNow and
   30459 ** return 0.  Return 1 if the time and date cannot be found.
   30460 */
   30461 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
   30462   sqlite3_int64 i = 0;
   30463   int rc;
   30464   UNUSED_PARAMETER(NotUsed);
   30465   rc = unixCurrentTimeInt64(0, &i);
   30466   *prNow = i/86400000.0;
   30467   return rc;
   30468 }
   30469 
   30470 /*
   30471 ** We added the xGetLastError() method with the intention of providing
   30472 ** better low-level error messages when operating-system problems come up
   30473 ** during SQLite operation.  But so far, none of that has been implemented
   30474 ** in the core.  So this routine is never called.  For now, it is merely
   30475 ** a place-holder.
   30476 */
   30477 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
   30478   UNUSED_PARAMETER(NotUsed);
   30479   UNUSED_PARAMETER(NotUsed2);
   30480   UNUSED_PARAMETER(NotUsed3);
   30481   return 0;
   30482 }
   30483 
   30484 
   30485 /*
   30486 ************************ End of sqlite3_vfs methods ***************************
   30487 ******************************************************************************/
   30488 
   30489 /******************************************************************************
   30490 ************************** Begin Proxy Locking ********************************
   30491 **
   30492 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
   30493 ** other locking methods on secondary lock files.  Proxy locking is a
   30494 ** meta-layer over top of the primitive locking implemented above.  For
   30495 ** this reason, the division that implements of proxy locking is deferred
   30496 ** until late in the file (here) after all of the other I/O methods have
   30497 ** been defined - so that the primitive locking methods are available
   30498 ** as services to help with the implementation of proxy locking.
   30499 **
   30500 ****
   30501 **
   30502 ** The default locking schemes in SQLite use byte-range locks on the
   30503 ** database file to coordinate safe, concurrent access by multiple readers
   30504 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
   30505 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
   30506 ** as POSIX read & write locks over fixed set of locations (via fsctl),
   30507 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
   30508 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
   30509 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
   30510 ** address in the shared range is taken for a SHARED lock, the entire
   30511 ** shared range is taken for an EXCLUSIVE lock):
   30512 **
   30513 **      PENDING_BYTE        0x40000000
   30514 **      RESERVED_BYTE       0x40000001
   30515 **      SHARED_RANGE        0x40000002 -> 0x40000200
   30516 **
   30517 ** This works well on the local file system, but shows a nearly 100x
   30518 ** slowdown in read performance on AFP because the AFP client disables
   30519 ** the read cache when byte-range locks are present.  Enabling the read
   30520 ** cache exposes a cache coherency problem that is present on all OS X
   30521 ** supported network file systems.  NFS and AFP both observe the
   30522 ** close-to-open semantics for ensuring cache coherency
   30523 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
   30524 ** address the requirements for concurrent database access by multiple
   30525 ** readers and writers
   30526 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
   30527 **
   30528 ** To address the performance and cache coherency issues, proxy file locking
   30529 ** changes the way database access is controlled by limiting access to a
   30530 ** single host at a time and moving file locks off of the database file
   30531 ** and onto a proxy file on the local file system.
   30532 **
   30533 **
   30534 ** Using proxy locks
   30535 ** -----------------
   30536 **
   30537 ** C APIs
   30538 **
   30539 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
   30540 **                       <proxy_path> | ":auto:");
   30541 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
   30542 **
   30543 **
   30544 ** SQL pragmas
   30545 **
   30546 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
   30547 **  PRAGMA [database.]lock_proxy_file
   30548 **
   30549 ** Specifying ":auto:" means that if there is a conch file with a matching
   30550 ** host ID in it, the proxy path in the conch file will be used, otherwise
   30551 ** a proxy path based on the user's temp dir
   30552 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
   30553 ** actual proxy file name is generated from the name and path of the
   30554 ** database file.  For example:
   30555 **
   30556 **       For database path "/Users/me/foo.db"
   30557 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
   30558 **
   30559 ** Once a lock proxy is configured for a database connection, it can not
   30560 ** be removed, however it may be switched to a different proxy path via
   30561 ** the above APIs (assuming the conch file is not being held by another
   30562 ** connection or process).
   30563 **
   30564 **
   30565 ** How proxy locking works
   30566 ** -----------------------
   30567 **
   30568 ** Proxy file locking relies primarily on two new supporting files:
   30569 **
   30570 **   *  conch file to limit access to the database file to a single host
   30571 **      at a time
   30572 **
   30573 **   *  proxy file to act as a proxy for the advisory locks normally
   30574 **      taken on the database
   30575 **
   30576 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
   30577 ** by taking an sqlite-style shared lock on the conch file, reading the
   30578 ** contents and comparing the host's unique host ID (see below) and lock
   30579 ** proxy path against the values stored in the conch.  The conch file is
   30580 ** stored in the same directory as the database file and the file name
   30581 ** is patterned after the database file name as ".<databasename>-conch".
   30582 ** If the conch file does not exist, or it's contents do not match the
   30583 ** host ID and/or proxy path, then the lock is escalated to an exclusive
   30584 ** lock and the conch file contents is updated with the host ID and proxy
   30585 ** path and the lock is downgraded to a shared lock again.  If the conch
   30586 ** is held by another process (with a shared lock), the exclusive lock
   30587 ** will fail and SQLITE_BUSY is returned.
   30588 **
   30589 ** The proxy file - a single-byte file used for all advisory file locks
   30590 ** normally taken on the database file.   This allows for safe sharing
   30591 ** of the database file for multiple readers and writers on the same
   30592 ** host (the conch ensures that they all use the same local lock file).
   30593 **
   30594 ** Requesting the lock proxy does not immediately take the conch, it is
   30595 ** only taken when the first request to lock database file is made.
   30596 ** This matches the semantics of the traditional locking behavior, where
   30597 ** opening a connection to a database file does not take a lock on it.
   30598 ** The shared lock and an open file descriptor are maintained until
   30599 ** the connection to the database is closed.
   30600 **
   30601 ** The proxy file and the lock file are never deleted so they only need
   30602 ** to be created the first time they are used.
   30603 **
   30604 ** Configuration options
   30605 ** ---------------------
   30606 **
   30607 **  SQLITE_PREFER_PROXY_LOCKING
   30608 **
   30609 **       Database files accessed on non-local file systems are
   30610 **       automatically configured for proxy locking, lock files are
   30611 **       named automatically using the same logic as
   30612 **       PRAGMA lock_proxy_file=":auto:"
   30613 **
   30614 **  SQLITE_PROXY_DEBUG
   30615 **
   30616 **       Enables the logging of error messages during host id file
   30617 **       retrieval and creation
   30618 **
   30619 **  LOCKPROXYDIR
   30620 **
   30621 **       Overrides the default directory used for lock proxy files that
   30622 **       are named automatically via the ":auto:" setting
   30623 **
   30624 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   30625 **
   30626 **       Permissions to use when creating a directory for storing the
   30627 **       lock proxy files, only used when LOCKPROXYDIR is not set.
   30628 **
   30629 **
   30630 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
   30631 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
   30632 ** force proxy locking to be used for every database file opened, and 0
   30633 ** will force automatic proxy locking to be disabled for all database
   30634 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
   30635 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
   30636 */
   30637 
   30638 /*
   30639 ** Proxy locking is only available on MacOSX
   30640 */
   30641 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   30642 
   30643 /*
   30644 ** The proxyLockingContext has the path and file structures for the remote
   30645 ** and local proxy files in it
   30646 */
   30647 typedef struct proxyLockingContext proxyLockingContext;
   30648 struct proxyLockingContext {
   30649   unixFile *conchFile;         /* Open conch file */
   30650   char *conchFilePath;         /* Name of the conch file */
   30651   unixFile *lockProxy;         /* Open proxy lock file */
   30652   char *lockProxyPath;         /* Name of the proxy lock file */
   30653   char *dbPath;                /* Name of the open file */
   30654   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
   30655   void *oldLockingContext;     /* Original lockingcontext to restore on close */
   30656   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
   30657 };
   30658 
   30659 /*
   30660 ** The proxy lock file path for the database at dbPath is written into lPath,
   30661 ** which must point to valid, writable memory large enough for a maxLen length
   30662 ** file path.
   30663 */
   30664 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   30665   int len;
   30666   int dbLen;
   30667   int i;
   30668 
   30669 #ifdef LOCKPROXYDIR
   30670   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
   30671 #else
   30672 # ifdef _CS_DARWIN_USER_TEMP_DIR
   30673   {
   30674     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
   30675       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
   30676                lPath, errno, getpid()));
   30677       return SQLITE_IOERR_LOCK;
   30678     }
   30679     len = strlcat(lPath, "sqliteplocks", maxLen);
   30680   }
   30681 # else
   30682   len = strlcpy(lPath, "/tmp/", maxLen);
   30683 # endif
   30684 #endif
   30685 
   30686   if( lPath[len-1]!='/' ){
   30687     len = strlcat(lPath, "/", maxLen);
   30688   }
   30689 
   30690   /* transform the db path to a unique cache name */
   30691   dbLen = (int)strlen(dbPath);
   30692   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
   30693     char c = dbPath[i];
   30694     lPath[i+len] = (c=='/')?'_':c;
   30695   }
   30696   lPath[i+len]='\0';
   30697   strlcat(lPath, ":auto:", maxLen);
   30698   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
   30699   return SQLITE_OK;
   30700 }
   30701 
   30702 /*
   30703  ** Creates the lock file and any missing directories in lockPath
   30704  */
   30705 static int proxyCreateLockPath(const char *lockPath){
   30706   int i, len;
   30707   char buf[MAXPATHLEN];
   30708   int start = 0;
   30709 
   30710   assert(lockPath!=NULL);
   30711   /* try to create all the intermediate directories */
   30712   len = (int)strlen(lockPath);
   30713   buf[0] = lockPath[0];
   30714   for( i=1; i<len; i++ ){
   30715     if( lockPath[i] == '/' && (i - start > 0) ){
   30716       /* only mkdir if leaf dir != "." or "/" or ".." */
   30717       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
   30718          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
   30719         buf[i]='\0';
   30720         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
   30721           int err=errno;
   30722           if( err!=EEXIST ) {
   30723             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
   30724                      "'%s' proxy lock path=%s pid=%d\n",
   30725                      buf, strerror(err), lockPath, getpid()));
   30726             return err;
   30727           }
   30728         }
   30729       }
   30730       start=i+1;
   30731     }
   30732     buf[i] = lockPath[i];
   30733   }
   30734   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
   30735   return 0;
   30736 }
   30737 
   30738 /*
   30739 ** Create a new VFS file descriptor (stored in memory obtained from
   30740 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
   30741 **
   30742 ** The caller is responsible not only for closing the file descriptor
   30743 ** but also for freeing the memory associated with the file descriptor.
   30744 */
   30745 static int proxyCreateUnixFile(
   30746     const char *path,        /* path for the new unixFile */
   30747     unixFile **ppFile,       /* unixFile created and returned by ref */
   30748     int islockfile           /* if non zero missing dirs will be created */
   30749 ) {
   30750   int fd = -1;
   30751   unixFile *pNew;
   30752   int rc = SQLITE_OK;
   30753   int openFlags = O_RDWR | O_CREAT;
   30754   sqlite3_vfs dummyVfs;
   30755   int terrno = 0;
   30756   UnixUnusedFd *pUnused = NULL;
   30757 
   30758   /* 1. first try to open/create the file
   30759   ** 2. if that fails, and this is a lock file (not-conch), try creating
   30760   ** the parent directories and then try again.
   30761   ** 3. if that fails, try to open the file read-only
   30762   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
   30763   */
   30764   pUnused = findReusableFd(path, openFlags);
   30765   if( pUnused ){
   30766     fd = pUnused->fd;
   30767   }else{
   30768     pUnused = sqlite3_malloc(sizeof(*pUnused));
   30769     if( !pUnused ){
   30770       return SQLITE_NOMEM;
   30771     }
   30772   }
   30773   if( fd<0 ){
   30774     fd = robust_open(path, openFlags, 0);
   30775     terrno = errno;
   30776     if( fd<0 && errno==ENOENT && islockfile ){
   30777       if( proxyCreateLockPath(path) == SQLITE_OK ){
   30778         fd = robust_open(path, openFlags, 0);
   30779       }
   30780     }
   30781   }
   30782   if( fd<0 ){
   30783     openFlags = O_RDONLY;
   30784     fd = robust_open(path, openFlags, 0);
   30785     terrno = errno;
   30786   }
   30787   if( fd<0 ){
   30788     if( islockfile ){
   30789       return SQLITE_BUSY;
   30790     }
   30791     switch (terrno) {
   30792       case EACCES:
   30793         return SQLITE_PERM;
   30794       case EIO:
   30795         return SQLITE_IOERR_LOCK; /* even though it is the conch */
   30796       default:
   30797         return SQLITE_CANTOPEN_BKPT;
   30798     }
   30799   }
   30800 
   30801   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
   30802   if( pNew==NULL ){
   30803     rc = SQLITE_NOMEM;
   30804     goto end_create_proxy;
   30805   }
   30806   memset(pNew, 0, sizeof(unixFile));
   30807   pNew->openFlags = openFlags;
   30808   memset(&dummyVfs, 0, sizeof(dummyVfs));
   30809   dummyVfs.pAppData = (void*)&autolockIoFinder;
   30810   dummyVfs.zName = "dummy";
   30811   pUnused->fd = fd;
   30812   pUnused->flags = openFlags;
   30813   pNew->pUnused = pUnused;
   30814 
   30815   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
   30816   if( rc==SQLITE_OK ){
   30817     *ppFile = pNew;
   30818     return SQLITE_OK;
   30819   }
   30820 end_create_proxy:
   30821   robust_close(pNew, fd, __LINE__);
   30822   sqlite3_free(pNew);
   30823   sqlite3_free(pUnused);
   30824   return rc;
   30825 }
   30826 
   30827 #ifdef SQLITE_TEST
   30828 /* simulate multiple hosts by creating unique hostid file paths */
   30829 SQLITE_API int sqlite3_hostid_num = 0;
   30830 #endif
   30831 
   30832 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
   30833 
   30834 /* Not always defined in the headers as it ought to be */
   30835 extern int gethostuuid(uuid_t id, const struct timespec *wait);
   30836 
   30837 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
   30838 ** bytes of writable memory.
   30839 */
   30840 static int proxyGetHostID(unsigned char *pHostID, int *pError){
   30841   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
   30842   memset(pHostID, 0, PROXY_HOSTIDLEN);
   30843 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
   30844                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
   30845   {
   30846     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
   30847     if( gethostuuid(pHostID, &timeout) ){
   30848       int err = errno;
   30849       if( pError ){
   30850         *pError = err;
   30851       }
   30852       return SQLITE_IOERR;
   30853     }
   30854   }
   30855 #else
   30856   UNUSED_PARAMETER(pError);
   30857 #endif
   30858 #ifdef SQLITE_TEST
   30859   /* simulate multiple hosts by creating unique hostid file paths */
   30860   if( sqlite3_hostid_num != 0){
   30861     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
   30862   }
   30863 #endif
   30864 
   30865   return SQLITE_OK;
   30866 }
   30867 
   30868 /* The conch file contains the header, host id and lock file path
   30869  */
   30870 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
   30871 #define PROXY_HEADERLEN    1   /* conch file header length */
   30872 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
   30873 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
   30874 
   30875 /*
   30876 ** Takes an open conch file, copies the contents to a new path and then moves
   30877 ** it back.  The newly created file's file descriptor is assigned to the
   30878 ** conch file structure and finally the original conch file descriptor is
   30879 ** closed.  Returns zero if successful.
   30880 */
   30881 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
   30882   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   30883   unixFile *conchFile = pCtx->conchFile;
   30884   char tPath[MAXPATHLEN];
   30885   char buf[PROXY_MAXCONCHLEN];
   30886   char *cPath = pCtx->conchFilePath;
   30887   size_t readLen = 0;
   30888   size_t pathLen = 0;
   30889   char errmsg[64] = "";
   30890   int fd = -1;
   30891   int rc = -1;
   30892   UNUSED_PARAMETER(myHostID);
   30893 
   30894   /* create a new path by replace the trailing '-conch' with '-break' */
   30895   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
   30896   if( pathLen>MAXPATHLEN || pathLen<6 ||
   30897      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
   30898     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
   30899     goto end_breaklock;
   30900   }
   30901   /* read the conch content */
   30902   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
   30903   if( readLen<PROXY_PATHINDEX ){
   30904     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
   30905     goto end_breaklock;
   30906   }
   30907   /* write it out to the temporary break file */
   30908   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
   30909   if( fd<0 ){
   30910     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
   30911     goto end_breaklock;
   30912   }
   30913   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
   30914     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
   30915     goto end_breaklock;
   30916   }
   30917   if( rename(tPath, cPath) ){
   30918     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
   30919     goto end_breaklock;
   30920   }
   30921   rc = 0;
   30922   fprintf(stderr, "broke stale lock on %s\n", cPath);
   30923   robust_close(pFile, conchFile->h, __LINE__);
   30924   conchFile->h = fd;
   30925   conchFile->openFlags = O_RDWR | O_CREAT;
   30926 
   30927 end_breaklock:
   30928   if( rc ){
   30929     if( fd>=0 ){
   30930       osUnlink(tPath);
   30931       robust_close(pFile, fd, __LINE__);
   30932     }
   30933     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
   30934   }
   30935   return rc;
   30936 }
   30937 
   30938 /* Take the requested lock on the conch file and break a stale lock if the
   30939 ** host id matches.
   30940 */
   30941 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
   30942   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   30943   unixFile *conchFile = pCtx->conchFile;
   30944   int rc = SQLITE_OK;
   30945   int nTries = 0;
   30946   struct timespec conchModTime;
   30947 
   30948   memset(&conchModTime, 0, sizeof(conchModTime));
   30949   do {
   30950     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   30951     nTries ++;
   30952     if( rc==SQLITE_BUSY ){
   30953       /* If the lock failed (busy):
   30954        * 1st try: get the mod time of the conch, wait 0.5s and try again.
   30955        * 2nd try: fail if the mod time changed or host id is different, wait
   30956        *           10 sec and try again
   30957        * 3rd try: break the lock unless the mod time has changed.
   30958        */
   30959       struct stat buf;
   30960       if( osFstat(conchFile->h, &buf) ){
   30961         pFile->lastErrno = errno;
   30962         return SQLITE_IOERR_LOCK;
   30963       }
   30964 
   30965       if( nTries==1 ){
   30966         conchModTime = buf.st_mtimespec;
   30967         usleep(500000); /* wait 0.5 sec and try the lock again*/
   30968         continue;
   30969       }
   30970 
   30971       assert( nTries>1 );
   30972       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
   30973          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
   30974         return SQLITE_BUSY;
   30975       }
   30976 
   30977       if( nTries==2 ){
   30978         char tBuf[PROXY_MAXCONCHLEN];
   30979         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
   30980         if( len<0 ){
   30981           pFile->lastErrno = errno;
   30982           return SQLITE_IOERR_LOCK;
   30983         }
   30984         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
   30985           /* don't break the lock if the host id doesn't match */
   30986           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
   30987             return SQLITE_BUSY;
   30988           }
   30989         }else{
   30990           /* don't break the lock on short read or a version mismatch */
   30991           return SQLITE_BUSY;
   30992         }
   30993         usleep(10000000); /* wait 10 sec and try the lock again */
   30994         continue;
   30995       }
   30996 
   30997       assert( nTries==3 );
   30998       if( 0==proxyBreakConchLock(pFile, myHostID) ){
   30999         rc = SQLITE_OK;
   31000         if( lockType==EXCLUSIVE_LOCK ){
   31001           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
   31002         }
   31003         if( !rc ){
   31004           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   31005         }
   31006       }
   31007     }
   31008   } while( rc==SQLITE_BUSY && nTries<3 );
   31009 
   31010   return rc;
   31011 }
   31012 
   31013 /* Takes the conch by taking a shared lock and read the contents conch, if
   31014 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
   31015 ** lockPath means that the lockPath in the conch file will be used if the
   31016 ** host IDs match, or a new lock path will be generated automatically
   31017 ** and written to the conch file.
   31018 */
   31019 static int proxyTakeConch(unixFile *pFile){
   31020   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31021 
   31022   if( pCtx->conchHeld!=0 ){
   31023     return SQLITE_OK;
   31024   }else{
   31025     unixFile *conchFile = pCtx->conchFile;
   31026     uuid_t myHostID;
   31027     int pError = 0;
   31028     char readBuf[PROXY_MAXCONCHLEN];
   31029     char lockPath[MAXPATHLEN];
   31030     char *tempLockPath = NULL;
   31031     int rc = SQLITE_OK;
   31032     int createConch = 0;
   31033     int hostIdMatch = 0;
   31034     int readLen = 0;
   31035     int tryOldLockPath = 0;
   31036     int forceNewLockPath = 0;
   31037 
   31038     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
   31039              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
   31040 
   31041     rc = proxyGetHostID(myHostID, &pError);
   31042     if( (rc&0xff)==SQLITE_IOERR ){
   31043       pFile->lastErrno = pError;
   31044       goto end_takeconch;
   31045     }
   31046     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
   31047     if( rc!=SQLITE_OK ){
   31048       goto end_takeconch;
   31049     }
   31050     /* read the existing conch file */
   31051     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
   31052     if( readLen<0 ){
   31053       /* I/O error: lastErrno set by seekAndRead */
   31054       pFile->lastErrno = conchFile->lastErrno;
   31055       rc = SQLITE_IOERR_READ;
   31056       goto end_takeconch;
   31057     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
   31058              readBuf[0]!=(char)PROXY_CONCHVERSION ){
   31059       /* a short read or version format mismatch means we need to create a new
   31060       ** conch file.
   31061       */
   31062       createConch = 1;
   31063     }
   31064     /* if the host id matches and the lock path already exists in the conch
   31065     ** we'll try to use the path there, if we can't open that path, we'll
   31066     ** retry with a new auto-generated path
   31067     */
   31068     do { /* in case we need to try again for an :auto: named lock file */
   31069 
   31070       if( !createConch && !forceNewLockPath ){
   31071         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
   31072                                   PROXY_HOSTIDLEN);
   31073         /* if the conch has data compare the contents */
   31074         if( !pCtx->lockProxyPath ){
   31075           /* for auto-named local lock file, just check the host ID and we'll
   31076            ** use the local lock file path that's already in there
   31077            */
   31078           if( hostIdMatch ){
   31079             size_t pathLen = (readLen - PROXY_PATHINDEX);
   31080 
   31081             if( pathLen>=MAXPATHLEN ){
   31082               pathLen=MAXPATHLEN-1;
   31083             }
   31084             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
   31085             lockPath[pathLen] = 0;
   31086             tempLockPath = lockPath;
   31087             tryOldLockPath = 1;
   31088             /* create a copy of the lock path if the conch is taken */
   31089             goto end_takeconch;
   31090           }
   31091         }else if( hostIdMatch
   31092                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
   31093                            readLen-PROXY_PATHINDEX)
   31094         ){
   31095           /* conch host and lock path match */
   31096           goto end_takeconch;
   31097         }
   31098       }
   31099 
   31100       /* if the conch isn't writable and doesn't match, we can't take it */
   31101       if( (conchFile->openFlags&O_RDWR) == 0 ){
   31102         rc = SQLITE_BUSY;
   31103         goto end_takeconch;
   31104       }
   31105 
   31106       /* either the conch didn't match or we need to create a new one */
   31107       if( !pCtx->lockProxyPath ){
   31108         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   31109         tempLockPath = lockPath;
   31110         /* create a copy of the lock path _only_ if the conch is taken */
   31111       }
   31112 
   31113       /* update conch with host and path (this will fail if other process
   31114       ** has a shared lock already), if the host id matches, use the big
   31115       ** stick.
   31116       */
   31117       futimes(conchFile->h, NULL);
   31118       if( hostIdMatch && !createConch ){
   31119         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
   31120           /* We are trying for an exclusive lock but another thread in this
   31121            ** same process is still holding a shared lock. */
   31122           rc = SQLITE_BUSY;
   31123         } else {
   31124           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   31125         }
   31126       }else{
   31127         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
   31128       }
   31129       if( rc==SQLITE_OK ){
   31130         char writeBuffer[PROXY_MAXCONCHLEN];
   31131         int writeSize = 0;
   31132 
   31133         writeBuffer[0] = (char)PROXY_CONCHVERSION;
   31134         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
   31135         if( pCtx->lockProxyPath!=NULL ){
   31136           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
   31137         }else{
   31138           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
   31139         }
   31140         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
   31141         robust_ftruncate(conchFile->h, writeSize);
   31142         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
   31143         fsync(conchFile->h);
   31144         /* If we created a new conch file (not just updated the contents of a
   31145          ** valid conch file), try to match the permissions of the database
   31146          */
   31147         if( rc==SQLITE_OK && createConch ){
   31148           struct stat buf;
   31149           int err = osFstat(pFile->h, &buf);
   31150           if( err==0 ){
   31151             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
   31152                                         S_IROTH|S_IWOTH);
   31153             /* try to match the database file R/W permissions, ignore failure */
   31154 #ifndef SQLITE_PROXY_DEBUG
   31155             osFchmod(conchFile->h, cmode);
   31156 #else
   31157             do{
   31158               rc = osFchmod(conchFile->h, cmode);
   31159             }while( rc==(-1) && errno==EINTR );
   31160             if( rc!=0 ){
   31161               int code = errno;
   31162               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   31163                       cmode, code, strerror(code));
   31164             } else {
   31165               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
   31166             }
   31167           }else{
   31168             int code = errno;
   31169             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   31170                     err, code, strerror(code));
   31171 #endif
   31172           }
   31173         }
   31174       }
   31175       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   31176 
   31177     end_takeconch:
   31178       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
   31179       if( rc==SQLITE_OK && pFile->openFlags ){
   31180         int fd;
   31181         if( pFile->h>=0 ){
   31182           robust_close(pFile, pFile->h, __LINE__);
   31183         }
   31184         pFile->h = -1;
   31185         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
   31186         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
   31187         if( fd>=0 ){
   31188           pFile->h = fd;
   31189         }else{
   31190           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
   31191            during locking */
   31192         }
   31193       }
   31194       if( rc==SQLITE_OK && !pCtx->lockProxy ){
   31195         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
   31196         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
   31197         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
   31198           /* we couldn't create the proxy lock file with the old lock file path
   31199            ** so try again via auto-naming
   31200            */
   31201           forceNewLockPath = 1;
   31202           tryOldLockPath = 0;
   31203           continue; /* go back to the do {} while start point, try again */
   31204         }
   31205       }
   31206       if( rc==SQLITE_OK ){
   31207         /* Need to make a copy of path if we extracted the value
   31208          ** from the conch file or the path was allocated on the stack
   31209          */
   31210         if( tempLockPath ){
   31211           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
   31212           if( !pCtx->lockProxyPath ){
   31213             rc = SQLITE_NOMEM;
   31214           }
   31215         }
   31216       }
   31217       if( rc==SQLITE_OK ){
   31218         pCtx->conchHeld = 1;
   31219 
   31220         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   31221           afpLockingContext *afpCtx;
   31222           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
   31223           afpCtx->dbPath = pCtx->lockProxyPath;
   31224         }
   31225       } else {
   31226         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   31227       }
   31228       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
   31229                rc==SQLITE_OK?"ok":"failed"));
   31230       return rc;
   31231     } while (1); /* in case we need to retry the :auto: lock file -
   31232                  ** we should never get here except via the 'continue' call. */
   31233   }
   31234 }
   31235 
   31236 /*
   31237 ** If pFile holds a lock on a conch file, then release that lock.
   31238 */
   31239 static int proxyReleaseConch(unixFile *pFile){
   31240   int rc = SQLITE_OK;         /* Subroutine return code */
   31241   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
   31242   unixFile *conchFile;        /* Name of the conch file */
   31243 
   31244   pCtx = (proxyLockingContext *)pFile->lockingContext;
   31245   conchFile = pCtx->conchFile;
   31246   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
   31247            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   31248            getpid()));
   31249   if( pCtx->conchHeld>0 ){
   31250     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   31251   }
   31252   pCtx->conchHeld = 0;
   31253   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
   31254            (rc==SQLITE_OK ? "ok" : "failed")));
   31255   return rc;
   31256 }
   31257 
   31258 /*
   31259 ** Given the name of a database file, compute the name of its conch file.
   31260 ** Store the conch filename in memory obtained from sqlite3_malloc().
   31261 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
   31262 ** or SQLITE_NOMEM if unable to obtain memory.
   31263 **
   31264 ** The caller is responsible for ensuring that the allocated memory
   31265 ** space is eventually freed.
   31266 **
   31267 ** *pConchPath is set to NULL if a memory allocation error occurs.
   31268 */
   31269 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   31270   int i;                        /* Loop counter */
   31271   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
   31272   char *conchPath;              /* buffer in which to construct conch name */
   31273 
   31274   /* Allocate space for the conch filename and initialize the name to
   31275   ** the name of the original database file. */
   31276   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
   31277   if( conchPath==0 ){
   31278     return SQLITE_NOMEM;
   31279   }
   31280   memcpy(conchPath, dbPath, len+1);
   31281 
   31282   /* now insert a "." before the last / character */
   31283   for( i=(len-1); i>=0; i-- ){
   31284     if( conchPath[i]=='/' ){
   31285       i++;
   31286       break;
   31287     }
   31288   }
   31289   conchPath[i]='.';
   31290   while ( i<len ){
   31291     conchPath[i+1]=dbPath[i];
   31292     i++;
   31293   }
   31294 
   31295   /* append the "-conch" suffix to the file */
   31296   memcpy(&conchPath[i+1], "-conch", 7);
   31297   assert( (int)strlen(conchPath) == len+7 );
   31298 
   31299   return SQLITE_OK;
   31300 }
   31301 
   31302 
   31303 /* Takes a fully configured proxy locking-style unix file and switches
   31304 ** the local lock file path
   31305 */
   31306 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   31307   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   31308   char *oldPath = pCtx->lockProxyPath;
   31309   int rc = SQLITE_OK;
   31310 
   31311   if( pFile->eFileLock!=NO_LOCK ){
   31312     return SQLITE_BUSY;
   31313   }
   31314 
   31315   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   31316   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
   31317     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
   31318     return SQLITE_OK;
   31319   }else{
   31320     unixFile *lockProxy = pCtx->lockProxy;
   31321     pCtx->lockProxy=NULL;
   31322     pCtx->conchHeld = 0;
   31323     if( lockProxy!=NULL ){
   31324       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
   31325       if( rc ) return rc;
   31326       sqlite3_free(lockProxy);
   31327     }
   31328     sqlite3_free(oldPath);
   31329     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   31330   }
   31331 
   31332   return rc;
   31333 }
   31334 
   31335 /*
   31336 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
   31337 ** is a string buffer at least MAXPATHLEN+1 characters in size.
   31338 **
   31339 ** This routine find the filename associated with pFile and writes it
   31340 ** int dbPath.
   31341 */
   31342 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
   31343 #if defined(__APPLE__)
   31344   if( pFile->pMethod == &afpIoMethods ){
   31345     /* afp style keeps a reference to the db path in the filePath field
   31346     ** of the struct */
   31347     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   31348     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
   31349   } else
   31350 #endif
   31351   if( pFile->pMethod == &dotlockIoMethods ){
   31352     /* dot lock style uses the locking context to store the dot lock
   31353     ** file path */
   31354     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
   31355     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
   31356   }else{
   31357     /* all other styles use the locking context to store the db file path */
   31358     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   31359     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
   31360   }
   31361   return SQLITE_OK;
   31362 }
   31363 
   31364 /*
   31365 ** Takes an already filled in unix file and alters it so all file locking
   31366 ** will be performed on the local proxy lock file.  The following fields
   31367 ** are preserved in the locking context so that they can be restored and
   31368 ** the unix structure properly cleaned up at close time:
   31369 **  ->lockingContext
   31370 **  ->pMethod
   31371 */
   31372 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   31373   proxyLockingContext *pCtx;
   31374   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   31375   char *lockPath=NULL;
   31376   int rc = SQLITE_OK;
   31377 
   31378   if( pFile->eFileLock!=NO_LOCK ){
   31379     return SQLITE_BUSY;
   31380   }
   31381   proxyGetDbPathForUnixFile(pFile, dbPath);
   31382   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
   31383     lockPath=NULL;
   31384   }else{
   31385     lockPath=(char *)path;
   31386   }
   31387 
   31388   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
   31389            (lockPath ? lockPath : ":auto:"), getpid()));
   31390 
   31391   pCtx = sqlite3_malloc( sizeof(*pCtx) );
   31392   if( pCtx==0 ){
   31393     return SQLITE_NOMEM;
   31394   }
   31395   memset(pCtx, 0, sizeof(*pCtx));
   31396 
   31397   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
   31398   if( rc==SQLITE_OK ){
   31399     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
   31400     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
   31401       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
   31402       ** (c) the file system is read-only, then enable no-locking access.
   31403       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
   31404       ** that openFlags will have only one of O_RDONLY or O_RDWR.
   31405       */
   31406       struct statfs fsInfo;
   31407       struct stat conchInfo;
   31408       int goLockless = 0;
   31409 
   31410       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
   31411         int err = errno;
   31412         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
   31413           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
   31414         }
   31415       }
   31416       if( goLockless ){
   31417         pCtx->conchHeld = -1; /* read only FS/ lockless */
   31418         rc = SQLITE_OK;
   31419       }
   31420     }
   31421   }
   31422   if( rc==SQLITE_OK && lockPath ){
   31423     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   31424   }
   31425 
   31426   if( rc==SQLITE_OK ){
   31427     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
   31428     if( pCtx->dbPath==NULL ){
   31429       rc = SQLITE_NOMEM;
   31430     }
   31431   }
   31432   if( rc==SQLITE_OK ){
   31433     /* all memory is allocated, proxys are created and assigned,
   31434     ** switch the locking context and pMethod then return.
   31435     */
   31436     pCtx->oldLockingContext = pFile->lockingContext;
   31437     pFile->lockingContext = pCtx;
   31438     pCtx->pOldMethod = pFile->pMethod;
   31439     pFile->pMethod = &proxyIoMethods;
   31440   }else{
   31441     if( pCtx->conchFile ){
   31442       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
   31443       sqlite3_free(pCtx->conchFile);
   31444     }
   31445     sqlite3DbFree(0, pCtx->lockProxyPath);
   31446     sqlite3_free(pCtx->conchFilePath);
   31447     sqlite3_free(pCtx);
   31448   }
   31449   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
   31450            (rc==SQLITE_OK ? "ok" : "failed")));
   31451   return rc;
   31452 }
   31453 
   31454 
   31455 /*
   31456 ** This routine handles sqlite3_file_control() calls that are specific
   31457 ** to proxy locking.
   31458 */
   31459 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
   31460   switch( op ){
   31461     case SQLITE_GET_LOCKPROXYFILE: {
   31462       unixFile *pFile = (unixFile*)id;
   31463       if( pFile->pMethod == &proxyIoMethods ){
   31464         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   31465         proxyTakeConch(pFile);
   31466         if( pCtx->lockProxyPath ){
   31467           *(const char **)pArg = pCtx->lockProxyPath;
   31468         }else{
   31469           *(const char **)pArg = ":auto: (not held)";
   31470         }
   31471       } else {
   31472         *(const char **)pArg = NULL;
   31473       }
   31474       return SQLITE_OK;
   31475     }
   31476     case SQLITE_SET_LOCKPROXYFILE: {
   31477       unixFile *pFile = (unixFile*)id;
   31478       int rc = SQLITE_OK;
   31479       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
   31480       if( pArg==NULL || (const char *)pArg==0 ){
   31481         if( isProxyStyle ){
   31482           /* turn off proxy locking - not supported */
   31483           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
   31484         }else{
   31485           /* turn off proxy locking - already off - NOOP */
   31486           rc = SQLITE_OK;
   31487         }
   31488       }else{
   31489         const char *proxyPath = (const char *)pArg;
   31490         if( isProxyStyle ){
   31491           proxyLockingContext *pCtx =
   31492             (proxyLockingContext*)pFile->lockingContext;
   31493           if( !strcmp(pArg, ":auto:")
   31494            || (pCtx->lockProxyPath &&
   31495                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
   31496           ){
   31497             rc = SQLITE_OK;
   31498           }else{
   31499             rc = switchLockProxyPath(pFile, proxyPath);
   31500           }
   31501         }else{
   31502           /* turn on proxy file locking */
   31503           rc = proxyTransformUnixFile(pFile, proxyPath);
   31504         }
   31505       }
   31506       return rc;
   31507     }
   31508     default: {
   31509       assert( 0 );  /* The call assures that only valid opcodes are sent */
   31510     }
   31511   }
   31512   /*NOTREACHED*/
   31513   return SQLITE_ERROR;
   31514 }
   31515 
   31516 /*
   31517 ** Within this division (the proxying locking implementation) the procedures
   31518 ** above this point are all utilities.  The lock-related methods of the
   31519 ** proxy-locking sqlite3_io_method object follow.
   31520 */
   31521 
   31522 
   31523 /*
   31524 ** This routine checks if there is a RESERVED lock held on the specified
   31525 ** file by this or any other process. If such a lock is held, set *pResOut
   31526 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   31527 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   31528 */
   31529 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
   31530   unixFile *pFile = (unixFile*)id;
   31531   int rc = proxyTakeConch(pFile);
   31532   if( rc==SQLITE_OK ){
   31533     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31534     if( pCtx->conchHeld>0 ){
   31535       unixFile *proxy = pCtx->lockProxy;
   31536       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
   31537     }else{ /* conchHeld < 0 is lockless */
   31538       pResOut=0;
   31539     }
   31540   }
   31541   return rc;
   31542 }
   31543 
   31544 /*
   31545 ** Lock the file with the lock specified by parameter eFileLock - one
   31546 ** of the following:
   31547 **
   31548 **     (1) SHARED_LOCK
   31549 **     (2) RESERVED_LOCK
   31550 **     (3) PENDING_LOCK
   31551 **     (4) EXCLUSIVE_LOCK
   31552 **
   31553 ** Sometimes when requesting one lock state, additional lock states
   31554 ** are inserted in between.  The locking might fail on one of the later
   31555 ** transitions leaving the lock state different from what it started but
   31556 ** still short of its goal.  The following chart shows the allowed
   31557 ** transitions and the inserted intermediate states:
   31558 **
   31559 **    UNLOCKED -> SHARED
   31560 **    SHARED -> RESERVED
   31561 **    SHARED -> (PENDING) -> EXCLUSIVE
   31562 **    RESERVED -> (PENDING) -> EXCLUSIVE
   31563 **    PENDING -> EXCLUSIVE
   31564 **
   31565 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   31566 ** routine to lower a locking level.
   31567 */
   31568 static int proxyLock(sqlite3_file *id, int eFileLock) {
   31569   unixFile *pFile = (unixFile*)id;
   31570   int rc = proxyTakeConch(pFile);
   31571   if( rc==SQLITE_OK ){
   31572     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31573     if( pCtx->conchHeld>0 ){
   31574       unixFile *proxy = pCtx->lockProxy;
   31575       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
   31576       pFile->eFileLock = proxy->eFileLock;
   31577     }else{
   31578       /* conchHeld < 0 is lockless */
   31579     }
   31580   }
   31581   return rc;
   31582 }
   31583 
   31584 
   31585 /*
   31586 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   31587 ** must be either NO_LOCK or SHARED_LOCK.
   31588 **
   31589 ** If the locking level of the file descriptor is already at or below
   31590 ** the requested locking level, this routine is a no-op.
   31591 */
   31592 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
   31593   unixFile *pFile = (unixFile*)id;
   31594   int rc = proxyTakeConch(pFile);
   31595   if( rc==SQLITE_OK ){
   31596     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31597     if( pCtx->conchHeld>0 ){
   31598       unixFile *proxy = pCtx->lockProxy;
   31599       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
   31600       pFile->eFileLock = proxy->eFileLock;
   31601     }else{
   31602       /* conchHeld < 0 is lockless */
   31603     }
   31604   }
   31605   return rc;
   31606 }
   31607 
   31608 /*
   31609 ** Close a file that uses proxy locks.
   31610 */
   31611 static int proxyClose(sqlite3_file *id) {
   31612   if( id ){
   31613     unixFile *pFile = (unixFile*)id;
   31614     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31615     unixFile *lockProxy = pCtx->lockProxy;
   31616     unixFile *conchFile = pCtx->conchFile;
   31617     int rc = SQLITE_OK;
   31618 
   31619     if( lockProxy ){
   31620       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
   31621       if( rc ) return rc;
   31622       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
   31623       if( rc ) return rc;
   31624       sqlite3_free(lockProxy);
   31625       pCtx->lockProxy = 0;
   31626     }
   31627     if( conchFile ){
   31628       if( pCtx->conchHeld ){
   31629         rc = proxyReleaseConch(pFile);
   31630         if( rc ) return rc;
   31631       }
   31632       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
   31633       if( rc ) return rc;
   31634       sqlite3_free(conchFile);
   31635     }
   31636     sqlite3DbFree(0, pCtx->lockProxyPath);
   31637     sqlite3_free(pCtx->conchFilePath);
   31638     sqlite3DbFree(0, pCtx->dbPath);
   31639     /* restore the original locking context and pMethod then close it */
   31640     pFile->lockingContext = pCtx->oldLockingContext;
   31641     pFile->pMethod = pCtx->pOldMethod;
   31642     sqlite3_free(pCtx);
   31643     return pFile->pMethod->xClose(id);
   31644   }
   31645   return SQLITE_OK;
   31646 }
   31647 
   31648 
   31649 
   31650 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   31651 /*
   31652 ** The proxy locking style is intended for use with AFP filesystems.
   31653 ** And since AFP is only supported on MacOSX, the proxy locking is also
   31654 ** restricted to MacOSX.
   31655 **
   31656 **
   31657 ******************* End of the proxy lock implementation **********************
   31658 ******************************************************************************/
   31659 
   31660 /*
   31661 ** Initialize the operating system interface.
   31662 **
   31663 ** This routine registers all VFS implementations for unix-like operating
   31664 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
   31665 ** should be the only routines in this file that are visible from other
   31666 ** files.
   31667 **
   31668 ** This routine is called once during SQLite initialization and by a
   31669 ** single thread.  The memory allocation and mutex subsystems have not
   31670 ** necessarily been initialized when this routine is called, and so they
   31671 ** should not be used.
   31672 */
   31673 SQLITE_API int sqlite3_os_init(void){
   31674   /*
   31675   ** The following macro defines an initializer for an sqlite3_vfs object.
   31676   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   31677   ** to the "finder" function.  (pAppData is a pointer to a pointer because
   31678   ** silly C90 rules prohibit a void* from being cast to a function pointer
   31679   ** and so we have to go through the intermediate pointer to avoid problems
   31680   ** when compiling with -pedantic-errors on GCC.)
   31681   **
   31682   ** The FINDER parameter to this macro is the name of the pointer to the
   31683   ** finder-function.  The finder-function returns a pointer to the
   31684   ** sqlite_io_methods object that implements the desired locking
   31685   ** behaviors.  See the division above that contains the IOMETHODS
   31686   ** macro for addition information on finder-functions.
   31687   **
   31688   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   31689   ** object.  But the "autolockIoFinder" available on MacOSX does a little
   31690   ** more than that; it looks at the filesystem type that hosts the
   31691   ** database file and tries to choose an locking method appropriate for
   31692   ** that filesystem time.
   31693   */
   31694   #define UNIXVFS(VFSNAME, FINDER) {                        \
   31695     3,                    /* iVersion */                    \
   31696     sizeof(unixFile),     /* szOsFile */                    \
   31697     MAX_PATHNAME,         /* mxPathname */                  \
   31698     0,                    /* pNext */                       \
   31699     VFSNAME,              /* zName */                       \
   31700     (void*)&FINDER,       /* pAppData */                    \
   31701     unixOpen,             /* xOpen */                       \
   31702     unixDelete,           /* xDelete */                     \
   31703     unixAccess,           /* xAccess */                     \
   31704     unixFullPathname,     /* xFullPathname */               \
   31705     unixDlOpen,           /* xDlOpen */                     \
   31706     unixDlError,          /* xDlError */                    \
   31707     unixDlSym,            /* xDlSym */                      \
   31708     unixDlClose,          /* xDlClose */                    \
   31709     unixRandomness,       /* xRandomness */                 \
   31710     unixSleep,            /* xSleep */                      \
   31711     unixCurrentTime,      /* xCurrentTime */                \
   31712     unixGetLastError,     /* xGetLastError */               \
   31713     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
   31714     unixSetSystemCall,    /* xSetSystemCall */              \
   31715     unixGetSystemCall,    /* xGetSystemCall */              \
   31716     unixNextSystemCall,   /* xNextSystemCall */             \
   31717   }
   31718 
   31719   /*
   31720   ** All default VFSes for unix are contained in the following array.
   31721   **
   31722   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
   31723   ** by the SQLite core when the VFS is registered.  So the following
   31724   ** array cannot be const.
   31725   */
   31726   static sqlite3_vfs aVfs[] = {
   31727 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
   31728     UNIXVFS("unix",          autolockIoFinder ),
   31729 #else
   31730     UNIXVFS("unix",          posixIoFinder ),
   31731 #endif
   31732     UNIXVFS("unix-none",     nolockIoFinder ),
   31733     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
   31734     UNIXVFS("unix-excl",     posixIoFinder ),
   31735 #if OS_VXWORKS
   31736     UNIXVFS("unix-namedsem", semIoFinder ),
   31737 #endif
   31738 #if SQLITE_ENABLE_LOCKING_STYLE
   31739     UNIXVFS("unix-posix",    posixIoFinder ),
   31740 #if !OS_VXWORKS
   31741     UNIXVFS("unix-flock",    flockIoFinder ),
   31742 #endif
   31743 #endif
   31744 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   31745     UNIXVFS("unix-afp",      afpIoFinder ),
   31746     UNIXVFS("unix-nfs",      nfsIoFinder ),
   31747     UNIXVFS("unix-proxy",    proxyIoFinder ),
   31748 #endif
   31749   };
   31750   unsigned int i;          /* Loop counter */
   31751 
   31752   /* Double-check that the aSyscall[] array has been constructed
   31753   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   31754   assert( ArraySize(aSyscall)==25 );
   31755 
   31756   /* Register all VFSes defined in the aVfs[] array */
   31757   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
   31758     sqlite3_vfs_register(&aVfs[i], i==0);
   31759   }
   31760   return SQLITE_OK;
   31761 }
   31762 
   31763 /*
   31764 ** Shutdown the operating system interface.
   31765 **
   31766 ** Some operating systems might need to do some cleanup in this routine,
   31767 ** to release dynamically allocated objects.  But not on unix.
   31768 ** This routine is a no-op for unix.
   31769 */
   31770 SQLITE_API int sqlite3_os_end(void){
   31771   return SQLITE_OK;
   31772 }
   31773 
   31774 #endif /* SQLITE_OS_UNIX */
   31775 
   31776 /************** End of os_unix.c *********************************************/
   31777 /************** Begin file os_win.c ******************************************/
   31778 /*
   31779 ** 2004 May 22
   31780 **
   31781 ** The author disclaims copyright to this source code.  In place of
   31782 ** a legal notice, here is a blessing:
   31783 **
   31784 **    May you do good and not evil.
   31785 **    May you find forgiveness for yourself and forgive others.
   31786 **    May you share freely, never taking more than you give.
   31787 **
   31788 ******************************************************************************
   31789 **
   31790 ** This file contains code that is specific to Windows.
   31791 */
   31792 #if SQLITE_OS_WIN               /* This file is used for Windows only */
   31793 
   31794 /*
   31795 ** Include code that is common to all os_*.c files
   31796 */
   31797 /************** Include os_common.h in the middle of os_win.c ****************/
   31798 /************** Begin file os_common.h ***************************************/
   31799 /*
   31800 ** 2004 May 22
   31801 **
   31802 ** The author disclaims copyright to this source code.  In place of
   31803 ** a legal notice, here is a blessing:
   31804 **
   31805 **    May you do good and not evil.
   31806 **    May you find forgiveness for yourself and forgive others.
   31807 **    May you share freely, never taking more than you give.
   31808 **
   31809 ******************************************************************************
   31810 **
   31811 ** This file contains macros and a little bit of code that is common to
   31812 ** all of the platform-specific files (os_*.c) and is #included into those
   31813 ** files.
   31814 **
   31815 ** This file should be #included by the os_*.c files only.  It is not a
   31816 ** general purpose header file.
   31817 */
   31818 #ifndef _OS_COMMON_H_
   31819 #define _OS_COMMON_H_
   31820 
   31821 /*
   31822 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   31823 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   31824 ** switch.  The following code should catch this problem at compile-time.
   31825 */
   31826 #ifdef MEMORY_DEBUG
   31827 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   31828 #endif
   31829 
   31830 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   31831 # ifndef SQLITE_DEBUG_OS_TRACE
   31832 #   define SQLITE_DEBUG_OS_TRACE 0
   31833 # endif
   31834   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   31835 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   31836 #else
   31837 # define OSTRACE(X)
   31838 #endif
   31839 
   31840 /*
   31841 ** Macros for performance tracing.  Normally turned off.  Only works
   31842 ** on i486 hardware.
   31843 */
   31844 #ifdef SQLITE_PERFORMANCE_TRACE
   31845 
   31846 /*
   31847 ** hwtime.h contains inline assembler code for implementing
   31848 ** high-performance timing routines.
   31849 */
   31850 /************** Include hwtime.h in the middle of os_common.h ****************/
   31851 /************** Begin file hwtime.h ******************************************/
   31852 /*
   31853 ** 2008 May 27
   31854 **
   31855 ** The author disclaims copyright to this source code.  In place of
   31856 ** a legal notice, here is a blessing:
   31857 **
   31858 **    May you do good and not evil.
   31859 **    May you find forgiveness for yourself and forgive others.
   31860 **    May you share freely, never taking more than you give.
   31861 **
   31862 ******************************************************************************
   31863 **
   31864 ** This file contains inline asm code for retrieving "high-performance"
   31865 ** counters for x86 class CPUs.
   31866 */
   31867 #ifndef _HWTIME_H_
   31868 #define _HWTIME_H_
   31869 
   31870 /*
   31871 ** The following routine only works on pentium-class (or newer) processors.
   31872 ** It uses the RDTSC opcode to read the cycle count value out of the
   31873 ** processor and returns that value.  This can be used for high-res
   31874 ** profiling.
   31875 */
   31876 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   31877       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   31878 
   31879   #if defined(__GNUC__)
   31880 
   31881   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   31882      unsigned int lo, hi;
   31883      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   31884      return (sqlite_uint64)hi << 32 | lo;
   31885   }
   31886 
   31887   #elif defined(_MSC_VER)
   31888 
   31889   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   31890      __asm {
   31891         rdtsc
   31892         ret       ; return value at EDX:EAX
   31893      }
   31894   }
   31895 
   31896   #endif
   31897 
   31898 #elif (defined(__GNUC__) && defined(__x86_64__))
   31899 
   31900   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   31901       unsigned long val;
   31902       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   31903       return val;
   31904   }
   31905 
   31906 #elif (defined(__GNUC__) && defined(__ppc__))
   31907 
   31908   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   31909       unsigned long long retval;
   31910       unsigned long junk;
   31911       __asm__ __volatile__ ("\n\
   31912           1:      mftbu   %1\n\
   31913                   mftb    %L0\n\
   31914                   mftbu   %0\n\
   31915                   cmpw    %0,%1\n\
   31916                   bne     1b"
   31917                   : "=r" (retval), "=r" (junk));
   31918       return retval;
   31919   }
   31920 
   31921 #else
   31922 
   31923   #error Need implementation of sqlite3Hwtime() for your platform.
   31924 
   31925   /*
   31926   ** To compile without implementing sqlite3Hwtime() for your platform,
   31927   ** you can remove the above #error and use the following
   31928   ** stub function.  You will lose timing support for many
   31929   ** of the debugging and testing utilities, but it should at
   31930   ** least compile and run.
   31931   */
   31932 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   31933 
   31934 #endif
   31935 
   31936 #endif /* !defined(_HWTIME_H_) */
   31937 
   31938 /************** End of hwtime.h **********************************************/
   31939 /************** Continuing where we left off in os_common.h ******************/
   31940 
   31941 static sqlite_uint64 g_start;
   31942 static sqlite_uint64 g_elapsed;
   31943 #define TIMER_START       g_start=sqlite3Hwtime()
   31944 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   31945 #define TIMER_ELAPSED     g_elapsed
   31946 #else
   31947 #define TIMER_START
   31948 #define TIMER_END
   31949 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   31950 #endif
   31951 
   31952 /*
   31953 ** If we compile with the SQLITE_TEST macro set, then the following block
   31954 ** of code will give us the ability to simulate a disk I/O error.  This
   31955 ** is used for testing the I/O recovery logic.
   31956 */
   31957 #ifdef SQLITE_TEST
   31958 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   31959 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   31960 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   31961 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   31962 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   31963 SQLITE_API int sqlite3_diskfull_pending = 0;
   31964 SQLITE_API int sqlite3_diskfull = 0;
   31965 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   31966 #define SimulateIOError(CODE)  \
   31967   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   31968        || sqlite3_io_error_pending-- == 1 )  \
   31969               { local_ioerr(); CODE; }
   31970 static void local_ioerr(){
   31971   IOTRACE(("IOERR\n"));
   31972   sqlite3_io_error_hit++;
   31973   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   31974 }
   31975 #define SimulateDiskfullError(CODE) \
   31976    if( sqlite3_diskfull_pending ){ \
   31977      if( sqlite3_diskfull_pending == 1 ){ \
   31978        local_ioerr(); \
   31979        sqlite3_diskfull = 1; \
   31980        sqlite3_io_error_hit = 1; \
   31981        CODE; \
   31982      }else{ \
   31983        sqlite3_diskfull_pending--; \
   31984      } \
   31985    }
   31986 #else
   31987 #define SimulateIOErrorBenign(X)
   31988 #define SimulateIOError(A)
   31989 #define SimulateDiskfullError(A)
   31990 #endif
   31991 
   31992 /*
   31993 ** When testing, keep a count of the number of open files.
   31994 */
   31995 #ifdef SQLITE_TEST
   31996 SQLITE_API int sqlite3_open_file_count = 0;
   31997 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   31998 #else
   31999 #define OpenCounter(X)
   32000 #endif
   32001 
   32002 #endif /* !defined(_OS_COMMON_H_) */
   32003 
   32004 /************** End of os_common.h *******************************************/
   32005 /************** Continuing where we left off in os_win.c *********************/
   32006 
   32007 /*
   32008 ** Include the header file for the Windows VFS.
   32009 */
   32010 
   32011 /*
   32012 ** Compiling and using WAL mode requires several APIs that are only
   32013 ** available in Windows platforms based on the NT kernel.
   32014 */
   32015 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
   32016 #  error "WAL mode requires support from the Windows NT kernel, compile\
   32017  with SQLITE_OMIT_WAL."
   32018 #endif
   32019 
   32020 /*
   32021 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
   32022 ** based on the sub-platform)?
   32023 */
   32024 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
   32025 #  define SQLITE_WIN32_HAS_ANSI
   32026 #endif
   32027 
   32028 /*
   32029 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
   32030 ** based on the sub-platform)?
   32031 */
   32032 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
   32033     !defined(SQLITE_WIN32_NO_WIDE)
   32034 #  define SQLITE_WIN32_HAS_WIDE
   32035 #endif
   32036 
   32037 /*
   32038 ** Make sure at least one set of Win32 APIs is available.
   32039 */
   32040 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
   32041 #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
   32042  must be defined."
   32043 #endif
   32044 
   32045 /*
   32046 ** Define the required Windows SDK version constants if they are not
   32047 ** already available.
   32048 */
   32049 #ifndef NTDDI_WIN8
   32050 #  define NTDDI_WIN8                        0x06020000
   32051 #endif
   32052 
   32053 #ifndef NTDDI_WINBLUE
   32054 #  define NTDDI_WINBLUE                     0x06030000
   32055 #endif
   32056 
   32057 /*
   32058 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
   32059 ** target system.  GetVersionEx was first deprecated in Win8.1.
   32060 */
   32061 #ifndef SQLITE_WIN32_GETVERSIONEX
   32062 #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
   32063 #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
   32064 #  else
   32065 #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
   32066 #  endif
   32067 #endif
   32068 
   32069 /*
   32070 ** This constant should already be defined (in the "WinDef.h" SDK file).
   32071 */
   32072 #ifndef MAX_PATH
   32073 #  define MAX_PATH                      (260)
   32074 #endif
   32075 
   32076 /*
   32077 ** Maximum pathname length (in chars) for Win32.  This should normally be
   32078 ** MAX_PATH.
   32079 */
   32080 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
   32081 #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
   32082 #endif
   32083 
   32084 /*
   32085 ** This constant should already be defined (in the "WinNT.h" SDK file).
   32086 */
   32087 #ifndef UNICODE_STRING_MAX_CHARS
   32088 #  define UNICODE_STRING_MAX_CHARS      (32767)
   32089 #endif
   32090 
   32091 /*
   32092 ** Maximum pathname length (in chars) for WinNT.  This should normally be
   32093 ** UNICODE_STRING_MAX_CHARS.
   32094 */
   32095 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
   32096 #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
   32097 #endif
   32098 
   32099 /*
   32100 ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
   32101 ** characters, so we allocate 4 bytes per character assuming worst-case of
   32102 ** 4-bytes-per-character for UTF8.
   32103 */
   32104 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
   32105 #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
   32106 #endif
   32107 
   32108 /*
   32109 ** Maximum pathname length (in bytes) for WinNT.  This should normally be
   32110 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
   32111 */
   32112 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
   32113 #  define SQLITE_WINNT_MAX_PATH_BYTES   \
   32114                             (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
   32115 #endif
   32116 
   32117 /*
   32118 ** Maximum error message length (in chars) for WinRT.
   32119 */
   32120 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
   32121 #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
   32122 #endif
   32123 
   32124 /*
   32125 ** Returns non-zero if the character should be treated as a directory
   32126 ** separator.
   32127 */
   32128 #ifndef winIsDirSep
   32129 #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
   32130 #endif
   32131 
   32132 /*
   32133 ** This macro is used when a local variable is set to a value that is
   32134 ** [sometimes] not used by the code (e.g. via conditional compilation).
   32135 */
   32136 #ifndef UNUSED_VARIABLE_VALUE
   32137 #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
   32138 #endif
   32139 
   32140 /*
   32141 ** Returns the character that should be used as the directory separator.
   32142 */
   32143 #ifndef winGetDirSep
   32144 #  define winGetDirSep()                '\\'
   32145 #endif
   32146 
   32147 /*
   32148 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
   32149 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
   32150 ** are not present in the header file)?
   32151 */
   32152 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
   32153 /*
   32154 ** Two of the file mapping APIs are different under WinRT.  Figure out which
   32155 ** set we need.
   32156 */
   32157 #if SQLITE_OS_WINRT
   32158 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
   32159         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
   32160 
   32161 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
   32162 #else
   32163 #if defined(SQLITE_WIN32_HAS_ANSI)
   32164 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
   32165         DWORD, DWORD, DWORD, LPCSTR);
   32166 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
   32167 
   32168 #if defined(SQLITE_WIN32_HAS_WIDE)
   32169 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
   32170         DWORD, DWORD, DWORD, LPCWSTR);
   32171 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
   32172 
   32173 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
   32174 #endif /* SQLITE_OS_WINRT */
   32175 
   32176 /*
   32177 ** This file mapping API is common to both Win32 and WinRT.
   32178 */
   32179 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
   32180 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
   32181 
   32182 /*
   32183 ** Some Microsoft compilers lack this definition.
   32184 */
   32185 #ifndef INVALID_FILE_ATTRIBUTES
   32186 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
   32187 #endif
   32188 
   32189 #ifndef FILE_FLAG_MASK
   32190 # define FILE_FLAG_MASK          (0xFF3C0000)
   32191 #endif
   32192 
   32193 #ifndef FILE_ATTRIBUTE_MASK
   32194 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
   32195 #endif
   32196 
   32197 #ifndef SQLITE_OMIT_WAL
   32198 /* Forward references to structures used for WAL */
   32199 typedef struct winShm winShm;           /* A connection to shared-memory */
   32200 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
   32201 #endif
   32202 
   32203 /*
   32204 ** WinCE lacks native support for file locking so we have to fake it
   32205 ** with some code of our own.
   32206 */
   32207 #if SQLITE_OS_WINCE
   32208 typedef struct winceLock {
   32209   int nReaders;       /* Number of reader locks obtained */
   32210   BOOL bPending;      /* Indicates a pending lock has been obtained */
   32211   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
   32212   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
   32213 } winceLock;
   32214 #endif
   32215 
   32216 /*
   32217 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
   32218 ** portability layer.
   32219 */
   32220 typedef struct winFile winFile;
   32221 struct winFile {
   32222   const sqlite3_io_methods *pMethod; /*** Must be first ***/
   32223   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
   32224   HANDLE h;               /* Handle for accessing the file */
   32225   u8 locktype;            /* Type of lock currently held on this file */
   32226   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
   32227   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
   32228   DWORD lastErrno;        /* The Windows errno from the last I/O error */
   32229 #ifndef SQLITE_OMIT_WAL
   32230   winShm *pShm;           /* Instance of shared memory on this file */
   32231 #endif
   32232   const char *zPath;      /* Full pathname of this file */
   32233   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
   32234 #if SQLITE_OS_WINCE
   32235   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
   32236   HANDLE hMutex;          /* Mutex used to control access to shared lock */
   32237   HANDLE hShared;         /* Shared memory segment used for locking */
   32238   winceLock local;        /* Locks obtained by this instance of winFile */
   32239   winceLock *shared;      /* Global shared lock memory for the file  */
   32240 #endif
   32241 #if SQLITE_MAX_MMAP_SIZE>0
   32242   int nFetchOut;                /* Number of outstanding xFetch references */
   32243   HANDLE hMap;                  /* Handle for accessing memory mapping */
   32244   void *pMapRegion;             /* Area memory mapped */
   32245   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
   32246   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
   32247   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
   32248 #endif
   32249 };
   32250 
   32251 /*
   32252 ** Allowed values for winFile.ctrlFlags
   32253 */
   32254 #define WINFILE_RDONLY          0x02   /* Connection is read only */
   32255 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
   32256 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   32257 
   32258 /*
   32259  * The size of the buffer used by sqlite3_win32_write_debug().
   32260  */
   32261 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
   32262 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
   32263 #endif
   32264 
   32265 /*
   32266  * The value used with sqlite3_win32_set_directory() to specify that
   32267  * the data directory should be changed.
   32268  */
   32269 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
   32270 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
   32271 #endif
   32272 
   32273 /*
   32274  * The value used with sqlite3_win32_set_directory() to specify that
   32275  * the temporary directory should be changed.
   32276  */
   32277 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
   32278 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
   32279 #endif
   32280 
   32281 /*
   32282  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
   32283  * various Win32 API heap functions instead of our own.
   32284  */
   32285 #ifdef SQLITE_WIN32_MALLOC
   32286 
   32287 /*
   32288  * If this is non-zero, an isolated heap will be created by the native Win32
   32289  * allocator subsystem; otherwise, the default process heap will be used.  This
   32290  * setting has no effect when compiling for WinRT.  By default, this is enabled
   32291  * and an isolated heap will be created to store all allocated data.
   32292  *
   32293  ******************************************************************************
   32294  * WARNING: It is important to note that when this setting is non-zero and the
   32295  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
   32296  *          function), all data that was allocated using the isolated heap will
   32297  *          be freed immediately and any attempt to access any of that freed
   32298  *          data will almost certainly result in an immediate access violation.
   32299  ******************************************************************************
   32300  */
   32301 #ifndef SQLITE_WIN32_HEAP_CREATE
   32302 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
   32303 #endif
   32304 
   32305 /*
   32306  * The initial size of the Win32-specific heap.  This value may be zero.
   32307  */
   32308 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
   32309 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
   32310                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
   32311 #endif
   32312 
   32313 /*
   32314  * The maximum size of the Win32-specific heap.  This value may be zero.
   32315  */
   32316 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
   32317 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
   32318 #endif
   32319 
   32320 /*
   32321  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
   32322  * zero for the default behavior.
   32323  */
   32324 #ifndef SQLITE_WIN32_HEAP_FLAGS
   32325 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
   32326 #endif
   32327 
   32328 
   32329 /*
   32330 ** The winMemData structure stores information required by the Win32-specific
   32331 ** sqlite3_mem_methods implementation.
   32332 */
   32333 typedef struct winMemData winMemData;
   32334 struct winMemData {
   32335 #ifndef NDEBUG
   32336   u32 magic1;   /* Magic number to detect structure corruption. */
   32337 #endif
   32338   HANDLE hHeap; /* The handle to our heap. */
   32339   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
   32340 #ifndef NDEBUG
   32341   u32 magic2;   /* Magic number to detect structure corruption. */
   32342 #endif
   32343 };
   32344 
   32345 #ifndef NDEBUG
   32346 #define WINMEM_MAGIC1     0x42b2830b
   32347 #define WINMEM_MAGIC2     0xbd4d7cf4
   32348 #endif
   32349 
   32350 static struct winMemData win_mem_data = {
   32351 #ifndef NDEBUG
   32352   WINMEM_MAGIC1,
   32353 #endif
   32354   NULL, FALSE
   32355 #ifndef NDEBUG
   32356   ,WINMEM_MAGIC2
   32357 #endif
   32358 };
   32359 
   32360 #ifndef NDEBUG
   32361 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
   32362 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
   32363 #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
   32364 #else
   32365 #define winMemAssertMagic()
   32366 #endif
   32367 
   32368 #define winMemGetDataPtr()  &win_mem_data
   32369 #define winMemGetHeap()     win_mem_data.hHeap
   32370 #define winMemGetOwned()    win_mem_data.bOwned
   32371 
   32372 static void *winMemMalloc(int nBytes);
   32373 static void winMemFree(void *pPrior);
   32374 static void *winMemRealloc(void *pPrior, int nBytes);
   32375 static int winMemSize(void *p);
   32376 static int winMemRoundup(int n);
   32377 static int winMemInit(void *pAppData);
   32378 static void winMemShutdown(void *pAppData);
   32379 
   32380 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
   32381 #endif /* SQLITE_WIN32_MALLOC */
   32382 
   32383 /*
   32384 ** The following variable is (normally) set once and never changes
   32385 ** thereafter.  It records whether the operating system is Win9x
   32386 ** or WinNT.
   32387 **
   32388 ** 0:   Operating system unknown.
   32389 ** 1:   Operating system is Win9x.
   32390 ** 2:   Operating system is WinNT.
   32391 **
   32392 ** In order to facilitate testing on a WinNT system, the test fixture
   32393 ** can manually set this value to 1 to emulate Win98 behavior.
   32394 */
   32395 #ifdef SQLITE_TEST
   32396 SQLITE_API LONG volatile sqlite3_os_type = 0;
   32397 #else
   32398 static LONG volatile sqlite3_os_type = 0;
   32399 #endif
   32400 
   32401 #ifndef SYSCALL
   32402 #  define SYSCALL sqlite3_syscall_ptr
   32403 #endif
   32404 
   32405 /*
   32406 ** This function is not available on Windows CE or WinRT.
   32407  */
   32408 
   32409 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
   32410 #  define osAreFileApisANSI()       1
   32411 #endif
   32412 
   32413 /*
   32414 ** Many system calls are accessed through pointer-to-functions so that
   32415 ** they may be overridden at runtime to facilitate fault injection during
   32416 ** testing and sandboxing.  The following array holds the names and pointers
   32417 ** to all overrideable system calls.
   32418 */
   32419 static struct win_syscall {
   32420   const char *zName;            /* Name of the system call */
   32421   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   32422   sqlite3_syscall_ptr pDefault; /* Default value */
   32423 } aSyscall[] = {
   32424 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   32425   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
   32426 #else
   32427   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
   32428 #endif
   32429 
   32430 #ifndef osAreFileApisANSI
   32431 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
   32432 #endif
   32433 
   32434 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32435   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
   32436 #else
   32437   { "CharLowerW",              (SYSCALL)0,                       0 },
   32438 #endif
   32439 
   32440 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
   32441 
   32442 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32443   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
   32444 #else
   32445   { "CharUpperW",              (SYSCALL)0,                       0 },
   32446 #endif
   32447 
   32448 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
   32449 
   32450   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
   32451 
   32452 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
   32453 
   32454 #if defined(SQLITE_WIN32_HAS_ANSI)
   32455   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
   32456 #else
   32457   { "CreateFileA",             (SYSCALL)0,                       0 },
   32458 #endif
   32459 
   32460 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
   32461         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
   32462 
   32463 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32464   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
   32465 #else
   32466   { "CreateFileW",             (SYSCALL)0,                       0 },
   32467 #endif
   32468 
   32469 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
   32470         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
   32471 
   32472 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
   32473         !defined(SQLITE_OMIT_WAL))
   32474   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
   32475 #else
   32476   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
   32477 #endif
   32478 
   32479 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   32480         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
   32481 
   32482 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   32483         !defined(SQLITE_OMIT_WAL))
   32484   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
   32485 #else
   32486   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
   32487 #endif
   32488 
   32489 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   32490         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
   32491 
   32492 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32493   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
   32494 #else
   32495   { "CreateMutexW",            (SYSCALL)0,                       0 },
   32496 #endif
   32497 
   32498 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
   32499         LPCWSTR))aSyscall[8].pCurrent)
   32500 
   32501 #if defined(SQLITE_WIN32_HAS_ANSI)
   32502   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
   32503 #else
   32504   { "DeleteFileA",             (SYSCALL)0,                       0 },
   32505 #endif
   32506 
   32507 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
   32508 
   32509 #if defined(SQLITE_WIN32_HAS_WIDE)
   32510   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
   32511 #else
   32512   { "DeleteFileW",             (SYSCALL)0,                       0 },
   32513 #endif
   32514 
   32515 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
   32516 
   32517 #if SQLITE_OS_WINCE
   32518   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
   32519 #else
   32520   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
   32521 #endif
   32522 
   32523 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   32524         LPFILETIME))aSyscall[11].pCurrent)
   32525 
   32526 #if SQLITE_OS_WINCE
   32527   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
   32528 #else
   32529   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
   32530 #endif
   32531 
   32532 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   32533         LPSYSTEMTIME))aSyscall[12].pCurrent)
   32534 
   32535   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
   32536 
   32537 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
   32538 
   32539 #if defined(SQLITE_WIN32_HAS_ANSI)
   32540   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
   32541 #else
   32542   { "FormatMessageA",          (SYSCALL)0,                       0 },
   32543 #endif
   32544 
   32545 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
   32546         DWORD,va_list*))aSyscall[14].pCurrent)
   32547 
   32548 #if defined(SQLITE_WIN32_HAS_WIDE)
   32549   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
   32550 #else
   32551   { "FormatMessageW",          (SYSCALL)0,                       0 },
   32552 #endif
   32553 
   32554 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
   32555         DWORD,va_list*))aSyscall[15].pCurrent)
   32556 
   32557 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32558   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
   32559 #else
   32560   { "FreeLibrary",             (SYSCALL)0,                       0 },
   32561 #endif
   32562 
   32563 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
   32564 
   32565   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
   32566 
   32567 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
   32568 
   32569 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   32570   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
   32571 #else
   32572   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
   32573 #endif
   32574 
   32575 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
   32576         LPDWORD))aSyscall[18].pCurrent)
   32577 
   32578 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32579   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
   32580 #else
   32581   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
   32582 #endif
   32583 
   32584 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
   32585         LPDWORD))aSyscall[19].pCurrent)
   32586 
   32587 #if defined(SQLITE_WIN32_HAS_ANSI)
   32588   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
   32589 #else
   32590   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
   32591 #endif
   32592 
   32593 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
   32594 
   32595 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32596   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
   32597 #else
   32598   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
   32599 #endif
   32600 
   32601 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
   32602 
   32603 #if defined(SQLITE_WIN32_HAS_WIDE)
   32604   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
   32605 #else
   32606   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
   32607 #endif
   32608 
   32609 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
   32610         LPVOID))aSyscall[22].pCurrent)
   32611 
   32612 #if !SQLITE_OS_WINRT
   32613   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
   32614 #else
   32615   { "GetFileSize",             (SYSCALL)0,                       0 },
   32616 #endif
   32617 
   32618 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
   32619 
   32620 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   32621   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
   32622 #else
   32623   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
   32624 #endif
   32625 
   32626 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
   32627         LPSTR*))aSyscall[24].pCurrent)
   32628 
   32629 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32630   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
   32631 #else
   32632   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
   32633 #endif
   32634 
   32635 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
   32636         LPWSTR*))aSyscall[25].pCurrent)
   32637 
   32638   { "GetLastError",            (SYSCALL)GetLastError,            0 },
   32639 
   32640 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
   32641 
   32642 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32643 #if SQLITE_OS_WINCE
   32644   /* The GetProcAddressA() routine is only available on Windows CE. */
   32645   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
   32646 #else
   32647   /* All other Windows platforms expect GetProcAddress() to take
   32648   ** an ANSI string regardless of the _UNICODE setting */
   32649   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
   32650 #endif
   32651 #else
   32652   { "GetProcAddressA",         (SYSCALL)0,                       0 },
   32653 #endif
   32654 
   32655 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
   32656         LPCSTR))aSyscall[27].pCurrent)
   32657 
   32658 #if !SQLITE_OS_WINRT
   32659   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
   32660 #else
   32661   { "GetSystemInfo",           (SYSCALL)0,                       0 },
   32662 #endif
   32663 
   32664 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
   32665 
   32666   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
   32667 
   32668 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
   32669 
   32670 #if !SQLITE_OS_WINCE
   32671   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
   32672 #else
   32673   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
   32674 #endif
   32675 
   32676 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
   32677         LPFILETIME))aSyscall[30].pCurrent)
   32678 
   32679 #if defined(SQLITE_WIN32_HAS_ANSI)
   32680   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
   32681 #else
   32682   { "GetTempPathA",            (SYSCALL)0,                       0 },
   32683 #endif
   32684 
   32685 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
   32686 
   32687 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   32688   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
   32689 #else
   32690   { "GetTempPathW",            (SYSCALL)0,                       0 },
   32691 #endif
   32692 
   32693 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
   32694 
   32695 #if !SQLITE_OS_WINRT
   32696   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
   32697 #else
   32698   { "GetTickCount",            (SYSCALL)0,                       0 },
   32699 #endif
   32700 
   32701 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
   32702 
   32703 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
   32704         SQLITE_WIN32_GETVERSIONEX
   32705   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
   32706 #else
   32707   { "GetVersionExA",           (SYSCALL)0,                       0 },
   32708 #endif
   32709 
   32710 #define osGetVersionExA ((BOOL(WINAPI*)( \
   32711         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
   32712 
   32713 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   32714         defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
   32715   { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
   32716 #else
   32717   { "GetVersionExW",           (SYSCALL)0,                       0 },
   32718 #endif
   32719 
   32720 #define osGetVersionExW ((BOOL(WINAPI*)( \
   32721         LPOSVERSIONINFOW))aSyscall[35].pCurrent)
   32722 
   32723   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
   32724 
   32725 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
   32726         SIZE_T))aSyscall[36].pCurrent)
   32727 
   32728 #if !SQLITE_OS_WINRT
   32729   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
   32730 #else
   32731   { "HeapCreate",              (SYSCALL)0,                       0 },
   32732 #endif
   32733 
   32734 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
   32735         SIZE_T))aSyscall[37].pCurrent)
   32736 
   32737 #if !SQLITE_OS_WINRT
   32738   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
   32739 #else
   32740   { "HeapDestroy",             (SYSCALL)0,                       0 },
   32741 #endif
   32742 
   32743 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
   32744 
   32745   { "HeapFree",                (SYSCALL)HeapFree,                0 },
   32746 
   32747 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
   32748 
   32749   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
   32750 
   32751 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
   32752         SIZE_T))aSyscall[40].pCurrent)
   32753 
   32754   { "HeapSize",                (SYSCALL)HeapSize,                0 },
   32755 
   32756 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
   32757         LPCVOID))aSyscall[41].pCurrent)
   32758 
   32759 #if !SQLITE_OS_WINRT
   32760   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
   32761 #else
   32762   { "HeapValidate",            (SYSCALL)0,                       0 },
   32763 #endif
   32764 
   32765 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
   32766         LPCVOID))aSyscall[42].pCurrent)
   32767 
   32768 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   32769   { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
   32770 #else
   32771   { "HeapCompact",             (SYSCALL)0,                       0 },
   32772 #endif
   32773 
   32774 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
   32775 
   32776 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32777   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
   32778 #else
   32779   { "LoadLibraryA",            (SYSCALL)0,                       0 },
   32780 #endif
   32781 
   32782 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
   32783 
   32784 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   32785         !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32786   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
   32787 #else
   32788   { "LoadLibraryW",            (SYSCALL)0,                       0 },
   32789 #endif
   32790 
   32791 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
   32792 
   32793 #if !SQLITE_OS_WINRT
   32794   { "LocalFree",               (SYSCALL)LocalFree,               0 },
   32795 #else
   32796   { "LocalFree",               (SYSCALL)0,                       0 },
   32797 #endif
   32798 
   32799 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
   32800 
   32801 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   32802   { "LockFile",                (SYSCALL)LockFile,                0 },
   32803 #else
   32804   { "LockFile",                (SYSCALL)0,                       0 },
   32805 #endif
   32806 
   32807 #ifndef osLockFile
   32808 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32809         DWORD))aSyscall[47].pCurrent)
   32810 #endif
   32811 
   32812 #if !SQLITE_OS_WINCE
   32813   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
   32814 #else
   32815   { "LockFileEx",              (SYSCALL)0,                       0 },
   32816 #endif
   32817 
   32818 #ifndef osLockFileEx
   32819 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
   32820         LPOVERLAPPED))aSyscall[48].pCurrent)
   32821 #endif
   32822 
   32823 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
   32824   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
   32825 #else
   32826   { "MapViewOfFile",           (SYSCALL)0,                       0 },
   32827 #endif
   32828 
   32829 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32830         SIZE_T))aSyscall[49].pCurrent)
   32831 
   32832   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
   32833 
   32834 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
   32835         int))aSyscall[50].pCurrent)
   32836 
   32837   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
   32838 
   32839 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
   32840         LARGE_INTEGER*))aSyscall[51].pCurrent)
   32841 
   32842   { "ReadFile",                (SYSCALL)ReadFile,                0 },
   32843 
   32844 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
   32845         LPOVERLAPPED))aSyscall[52].pCurrent)
   32846 
   32847   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
   32848 
   32849 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
   32850 
   32851 #if !SQLITE_OS_WINRT
   32852   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
   32853 #else
   32854   { "SetFilePointer",          (SYSCALL)0,                       0 },
   32855 #endif
   32856 
   32857 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
   32858         DWORD))aSyscall[54].pCurrent)
   32859 
   32860 #if !SQLITE_OS_WINRT
   32861   { "Sleep",                   (SYSCALL)Sleep,                   0 },
   32862 #else
   32863   { "Sleep",                   (SYSCALL)0,                       0 },
   32864 #endif
   32865 
   32866 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
   32867 
   32868   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
   32869 
   32870 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
   32871         LPFILETIME))aSyscall[56].pCurrent)
   32872 
   32873 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   32874   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
   32875 #else
   32876   { "UnlockFile",              (SYSCALL)0,                       0 },
   32877 #endif
   32878 
   32879 #ifndef osUnlockFile
   32880 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32881         DWORD))aSyscall[57].pCurrent)
   32882 #endif
   32883 
   32884 #if !SQLITE_OS_WINCE
   32885   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
   32886 #else
   32887   { "UnlockFileEx",            (SYSCALL)0,                       0 },
   32888 #endif
   32889 
   32890 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32891         LPOVERLAPPED))aSyscall[58].pCurrent)
   32892 
   32893 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
   32894   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
   32895 #else
   32896   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
   32897 #endif
   32898 
   32899 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
   32900 
   32901   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
   32902 
   32903 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
   32904         LPCSTR,LPBOOL))aSyscall[60].pCurrent)
   32905 
   32906   { "WriteFile",               (SYSCALL)WriteFile,               0 },
   32907 
   32908 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
   32909         LPOVERLAPPED))aSyscall[61].pCurrent)
   32910 
   32911 #if SQLITE_OS_WINRT
   32912   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
   32913 #else
   32914   { "CreateEventExW",          (SYSCALL)0,                       0 },
   32915 #endif
   32916 
   32917 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
   32918         DWORD,DWORD))aSyscall[62].pCurrent)
   32919 
   32920 #if !SQLITE_OS_WINRT
   32921   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
   32922 #else
   32923   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
   32924 #endif
   32925 
   32926 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
   32927         DWORD))aSyscall[63].pCurrent)
   32928 
   32929 #if SQLITE_OS_WINRT
   32930   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
   32931 #else
   32932   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
   32933 #endif
   32934 
   32935 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
   32936         BOOL))aSyscall[64].pCurrent)
   32937 
   32938 #if SQLITE_OS_WINRT
   32939   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
   32940 #else
   32941   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
   32942 #endif
   32943 
   32944 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
   32945         PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
   32946 
   32947 #if SQLITE_OS_WINRT
   32948   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
   32949 #else
   32950   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
   32951 #endif
   32952 
   32953 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
   32954         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
   32955 
   32956 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
   32957   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
   32958 #else
   32959   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
   32960 #endif
   32961 
   32962 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
   32963         SIZE_T))aSyscall[67].pCurrent)
   32964 
   32965 #if SQLITE_OS_WINRT
   32966   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
   32967 #else
   32968   { "CreateFile2",             (SYSCALL)0,                       0 },
   32969 #endif
   32970 
   32971 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
   32972         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
   32973 
   32974 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   32975   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
   32976 #else
   32977   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
   32978 #endif
   32979 
   32980 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
   32981         DWORD))aSyscall[69].pCurrent)
   32982 
   32983 #if SQLITE_OS_WINRT
   32984   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
   32985 #else
   32986   { "GetTickCount64",          (SYSCALL)0,                       0 },
   32987 #endif
   32988 
   32989 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
   32990 
   32991 #if SQLITE_OS_WINRT
   32992   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
   32993 #else
   32994   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
   32995 #endif
   32996 
   32997 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
   32998         LPSYSTEM_INFO))aSyscall[71].pCurrent)
   32999 
   33000 #if defined(SQLITE_WIN32_HAS_ANSI)
   33001   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
   33002 #else
   33003   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
   33004 #endif
   33005 
   33006 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
   33007 
   33008 #if defined(SQLITE_WIN32_HAS_WIDE)
   33009   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
   33010 #else
   33011   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
   33012 #endif
   33013 
   33014 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
   33015 
   33016   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
   33017 
   33018 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
   33019 
   33020 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
   33021   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
   33022 #else
   33023   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
   33024 #endif
   33025 
   33026 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
   33027         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
   33028 
   33029 /*
   33030 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
   33031 **       is really just a macro that uses a compiler intrinsic (e.g. x64).
   33032 **       So do not try to make this is into a redefinable interface.
   33033 */
   33034 #if defined(InterlockedCompareExchange)
   33035   { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
   33036 
   33037 #define osInterlockedCompareExchange InterlockedCompareExchange
   33038 #else
   33039   { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
   33040 
   33041 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG volatile*, \
   33042         LONG,LONG))aSyscall[76].pCurrent)
   33043 #endif /* defined(InterlockedCompareExchange) */
   33044 
   33045 }; /* End of the overrideable system calls */
   33046 
   33047 /*
   33048 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   33049 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
   33050 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   33051 ** system call named zName.
   33052 */
   33053 static int winSetSystemCall(
   33054   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   33055   const char *zName,            /* Name of system call to override */
   33056   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   33057 ){
   33058   unsigned int i;
   33059   int rc = SQLITE_NOTFOUND;
   33060 
   33061   UNUSED_PARAMETER(pNotUsed);
   33062   if( zName==0 ){
   33063     /* If no zName is given, restore all system calls to their default
   33064     ** settings and return NULL
   33065     */
   33066     rc = SQLITE_OK;
   33067     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   33068       if( aSyscall[i].pDefault ){
   33069         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   33070       }
   33071     }
   33072   }else{
   33073     /* If zName is specified, operate on only the one system call
   33074     ** specified.
   33075     */
   33076     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   33077       if( strcmp(zName, aSyscall[i].zName)==0 ){
   33078         if( aSyscall[i].pDefault==0 ){
   33079           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   33080         }
   33081         rc = SQLITE_OK;
   33082         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   33083         aSyscall[i].pCurrent = pNewFunc;
   33084         break;
   33085       }
   33086     }
   33087   }
   33088   return rc;
   33089 }
   33090 
   33091 /*
   33092 ** Return the value of a system call.  Return NULL if zName is not a
   33093 ** recognized system call name.  NULL is also returned if the system call
   33094 ** is currently undefined.
   33095 */
   33096 static sqlite3_syscall_ptr winGetSystemCall(
   33097   sqlite3_vfs *pNotUsed,
   33098   const char *zName
   33099 ){
   33100   unsigned int i;
   33101 
   33102   UNUSED_PARAMETER(pNotUsed);
   33103   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   33104     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   33105   }
   33106   return 0;
   33107 }
   33108 
   33109 /*
   33110 ** Return the name of the first system call after zName.  If zName==NULL
   33111 ** then return the name of the first system call.  Return NULL if zName
   33112 ** is the last system call or if zName is not the name of a valid
   33113 ** system call.
   33114 */
   33115 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
   33116   int i = -1;
   33117 
   33118   UNUSED_PARAMETER(p);
   33119   if( zName ){
   33120     for(i=0; i<ArraySize(aSyscall)-1; i++){
   33121       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   33122     }
   33123   }
   33124   for(i++; i<ArraySize(aSyscall); i++){
   33125     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   33126   }
   33127   return 0;
   33128 }
   33129 
   33130 #ifdef SQLITE_WIN32_MALLOC
   33131 /*
   33132 ** If a Win32 native heap has been configured, this function will attempt to
   33133 ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
   33134 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
   33135 ** "pnLargest" argument, if non-zero, will be used to return the size of the
   33136 ** largest committed free block in the heap, in bytes.
   33137 */
   33138 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
   33139   int rc = SQLITE_OK;
   33140   UINT nLargest = 0;
   33141   HANDLE hHeap;
   33142 
   33143   winMemAssertMagic();
   33144   hHeap = winMemGetHeap();
   33145   assert( hHeap!=0 );
   33146   assert( hHeap!=INVALID_HANDLE_VALUE );
   33147 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33148   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33149 #endif
   33150 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   33151   if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
   33152     DWORD lastErrno = osGetLastError();
   33153     if( lastErrno==NO_ERROR ){
   33154       sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
   33155                   (void*)hHeap);
   33156       rc = SQLITE_NOMEM;
   33157     }else{
   33158       sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
   33159                   osGetLastError(), (void*)hHeap);
   33160       rc = SQLITE_ERROR;
   33161     }
   33162   }
   33163 #else
   33164   sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
   33165               (void*)hHeap);
   33166   rc = SQLITE_NOTFOUND;
   33167 #endif
   33168   if( pnLargest ) *pnLargest = nLargest;
   33169   return rc;
   33170 }
   33171 
   33172 /*
   33173 ** If a Win32 native heap has been configured, this function will attempt to
   33174 ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
   33175 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
   33176 ** be returned and no changes will be made to the Win32 native heap.
   33177 */
   33178 SQLITE_API int sqlite3_win32_reset_heap(){
   33179   int rc;
   33180   MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
   33181   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
   33182   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   33183   MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
   33184   sqlite3_mutex_enter(pMaster);
   33185   sqlite3_mutex_enter(pMem);
   33186   winMemAssertMagic();
   33187   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
   33188     /*
   33189     ** At this point, there should be no outstanding memory allocations on
   33190     ** the heap.  Also, since both the master and memsys locks are currently
   33191     ** being held by us, no other function (i.e. from another thread) should
   33192     ** be able to even access the heap.  Attempt to destroy and recreate our
   33193     ** isolated Win32 native heap now.
   33194     */
   33195     assert( winMemGetHeap()!=NULL );
   33196     assert( winMemGetOwned() );
   33197     assert( sqlite3_memory_used()==0 );
   33198     winMemShutdown(winMemGetDataPtr());
   33199     assert( winMemGetHeap()==NULL );
   33200     assert( !winMemGetOwned() );
   33201     assert( sqlite3_memory_used()==0 );
   33202     rc = winMemInit(winMemGetDataPtr());
   33203     assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
   33204     assert( rc!=SQLITE_OK || winMemGetOwned() );
   33205     assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
   33206   }else{
   33207     /*
   33208     ** The Win32 native heap cannot be modified because it may be in use.
   33209     */
   33210     rc = SQLITE_BUSY;
   33211   }
   33212   sqlite3_mutex_leave(pMem);
   33213   sqlite3_mutex_leave(pMaster);
   33214   return rc;
   33215 }
   33216 #endif /* SQLITE_WIN32_MALLOC */
   33217 
   33218 /*
   33219 ** This function outputs the specified (ANSI) string to the Win32 debugger
   33220 ** (if available).
   33221 */
   33222 
   33223 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
   33224   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
   33225   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
   33226   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
   33227   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
   33228 #if defined(SQLITE_WIN32_HAS_ANSI)
   33229   if( nMin>0 ){
   33230     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   33231     memcpy(zDbgBuf, zBuf, nMin);
   33232     osOutputDebugStringA(zDbgBuf);
   33233   }else{
   33234     osOutputDebugStringA(zBuf);
   33235   }
   33236 #elif defined(SQLITE_WIN32_HAS_WIDE)
   33237   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   33238   if ( osMultiByteToWideChar(
   33239           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
   33240           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
   33241     return;
   33242   }
   33243   osOutputDebugStringW((LPCWSTR)zDbgBuf);
   33244 #else
   33245   if( nMin>0 ){
   33246     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   33247     memcpy(zDbgBuf, zBuf, nMin);
   33248     fprintf(stderr, "%s", zDbgBuf);
   33249   }else{
   33250     fprintf(stderr, "%s", zBuf);
   33251   }
   33252 #endif
   33253 }
   33254 
   33255 /*
   33256 ** The following routine suspends the current thread for at least ms
   33257 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
   33258 */
   33259 #if SQLITE_OS_WINRT
   33260 static HANDLE sleepObj = NULL;
   33261 #endif
   33262 
   33263 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
   33264 #if SQLITE_OS_WINRT
   33265   if ( sleepObj==NULL ){
   33266     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
   33267                                 SYNCHRONIZE);
   33268   }
   33269   assert( sleepObj!=NULL );
   33270   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
   33271 #else
   33272   osSleep(milliseconds);
   33273 #endif
   33274 }
   33275 
   33276 /*
   33277 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   33278 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   33279 **
   33280 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   33281 ** the LockFileEx() API.  But we can still statically link against that
   33282 ** API as long as we don't call it when running Win95/98/ME.  A call to
   33283 ** this routine is used to determine if the host is Win95/98/ME or
   33284 ** WinNT/2K/XP so that we will know whether or not we can safely call
   33285 ** the LockFileEx() API.
   33286 */
   33287 
   33288 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
   33289 # define osIsNT()  (1)
   33290 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
   33291 # define osIsNT()  (1)
   33292 #elif !defined(SQLITE_WIN32_HAS_WIDE)
   33293 # define osIsNT()  (0)
   33294 #else
   33295 # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
   33296 #endif
   33297 
   33298 /*
   33299 ** This function determines if the machine is running a version of Windows
   33300 ** based on the NT kernel.
   33301 */
   33302 SQLITE_API int sqlite3_win32_is_nt(void){
   33303 #if defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
   33304   if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
   33305 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   33306         defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
   33307     OSVERSIONINFOW sInfo;
   33308     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   33309     osGetVersionExW(&sInfo);
   33310     osInterlockedCompareExchange(&sqlite3_os_type,
   33311         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
   33312 #elif defined(SQLITE_WIN32_HAS_ANSI)
   33313     OSVERSIONINFOA sInfo;
   33314     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   33315     osGetVersionExA(&sInfo);
   33316     osInterlockedCompareExchange(&sqlite3_os_type,
   33317         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
   33318 #endif
   33319   }
   33320   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
   33321 #elif SQLITE_TEST
   33322   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
   33323 #else
   33324   return 1;
   33325 #endif
   33326 }
   33327 
   33328 #ifdef SQLITE_WIN32_MALLOC
   33329 /*
   33330 ** Allocate nBytes of memory.
   33331 */
   33332 static void *winMemMalloc(int nBytes){
   33333   HANDLE hHeap;
   33334   void *p;
   33335 
   33336   winMemAssertMagic();
   33337   hHeap = winMemGetHeap();
   33338   assert( hHeap!=0 );
   33339   assert( hHeap!=INVALID_HANDLE_VALUE );
   33340 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33341   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33342 #endif
   33343   assert( nBytes>=0 );
   33344   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   33345   if( !p ){
   33346     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
   33347                 nBytes, osGetLastError(), (void*)hHeap);
   33348   }
   33349   return p;
   33350 }
   33351 
   33352 /*
   33353 ** Free memory.
   33354 */
   33355 static void winMemFree(void *pPrior){
   33356   HANDLE hHeap;
   33357 
   33358   winMemAssertMagic();
   33359   hHeap = winMemGetHeap();
   33360   assert( hHeap!=0 );
   33361   assert( hHeap!=INVALID_HANDLE_VALUE );
   33362 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33363   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   33364 #endif
   33365   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
   33366   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
   33367     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
   33368                 pPrior, osGetLastError(), (void*)hHeap);
   33369   }
   33370 }
   33371 
   33372 /*
   33373 ** Change the size of an existing memory allocation
   33374 */
   33375 static void *winMemRealloc(void *pPrior, int nBytes){
   33376   HANDLE hHeap;
   33377   void *p;
   33378 
   33379   winMemAssertMagic();
   33380   hHeap = winMemGetHeap();
   33381   assert( hHeap!=0 );
   33382   assert( hHeap!=INVALID_HANDLE_VALUE );
   33383 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33384   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   33385 #endif
   33386   assert( nBytes>=0 );
   33387   if( !pPrior ){
   33388     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   33389   }else{
   33390     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
   33391   }
   33392   if( !p ){
   33393     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
   33394                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
   33395                 (void*)hHeap);
   33396   }
   33397   return p;
   33398 }
   33399 
   33400 /*
   33401 ** Return the size of an outstanding allocation, in bytes.
   33402 */
   33403 static int winMemSize(void *p){
   33404   HANDLE hHeap;
   33405   SIZE_T n;
   33406 
   33407   winMemAssertMagic();
   33408   hHeap = winMemGetHeap();
   33409   assert( hHeap!=0 );
   33410   assert( hHeap!=INVALID_HANDLE_VALUE );
   33411 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33412   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
   33413 #endif
   33414   if( !p ) return 0;
   33415   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
   33416   if( n==(SIZE_T)-1 ){
   33417     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
   33418                 p, osGetLastError(), (void*)hHeap);
   33419     return 0;
   33420   }
   33421   return (int)n;
   33422 }
   33423 
   33424 /*
   33425 ** Round up a request size to the next valid allocation size.
   33426 */
   33427 static int winMemRoundup(int n){
   33428   return n;
   33429 }
   33430 
   33431 /*
   33432 ** Initialize this module.
   33433 */
   33434 static int winMemInit(void *pAppData){
   33435   winMemData *pWinMemData = (winMemData *)pAppData;
   33436 
   33437   if( !pWinMemData ) return SQLITE_ERROR;
   33438   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
   33439   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
   33440 
   33441 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
   33442   if( !pWinMemData->hHeap ){
   33443     DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
   33444     DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
   33445     if( dwMaximumSize==0 ){
   33446       dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
   33447     }else if( dwInitialSize>dwMaximumSize ){
   33448       dwInitialSize = dwMaximumSize;
   33449     }
   33450     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
   33451                                       dwInitialSize, dwMaximumSize);
   33452     if( !pWinMemData->hHeap ){
   33453       sqlite3_log(SQLITE_NOMEM,
   33454           "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
   33455           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
   33456           dwMaximumSize);
   33457       return SQLITE_NOMEM;
   33458     }
   33459     pWinMemData->bOwned = TRUE;
   33460     assert( pWinMemData->bOwned );
   33461   }
   33462 #else
   33463   pWinMemData->hHeap = osGetProcessHeap();
   33464   if( !pWinMemData->hHeap ){
   33465     sqlite3_log(SQLITE_NOMEM,
   33466         "failed to GetProcessHeap (%lu)", osGetLastError());
   33467     return SQLITE_NOMEM;
   33468   }
   33469   pWinMemData->bOwned = FALSE;
   33470   assert( !pWinMemData->bOwned );
   33471 #endif
   33472   assert( pWinMemData->hHeap!=0 );
   33473   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   33474 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33475   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33476 #endif
   33477   return SQLITE_OK;
   33478 }
   33479 
   33480 /*
   33481 ** Deinitialize this module.
   33482 */
   33483 static void winMemShutdown(void *pAppData){
   33484   winMemData *pWinMemData = (winMemData *)pAppData;
   33485 
   33486   if( !pWinMemData ) return;
   33487   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
   33488   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
   33489 
   33490   if( pWinMemData->hHeap ){
   33491     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   33492 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   33493     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33494 #endif
   33495     if( pWinMemData->bOwned ){
   33496       if( !osHeapDestroy(pWinMemData->hHeap) ){
   33497         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
   33498                     osGetLastError(), (void*)pWinMemData->hHeap);
   33499       }
   33500       pWinMemData->bOwned = FALSE;
   33501     }
   33502     pWinMemData->hHeap = NULL;
   33503   }
   33504 }
   33505 
   33506 /*
   33507 ** Populate the low-level memory allocation function pointers in
   33508 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   33509 ** arguments specify the block of memory to manage.
   33510 **
   33511 ** This routine is only called by sqlite3_config(), and therefore
   33512 ** is not required to be threadsafe (it is not).
   33513 */
   33514 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
   33515   static const sqlite3_mem_methods winMemMethods = {
   33516     winMemMalloc,
   33517     winMemFree,
   33518     winMemRealloc,
   33519     winMemSize,
   33520     winMemRoundup,
   33521     winMemInit,
   33522     winMemShutdown,
   33523     &win_mem_data
   33524   };
   33525   return &winMemMethods;
   33526 }
   33527 
   33528 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   33529   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
   33530 }
   33531 #endif /* SQLITE_WIN32_MALLOC */
   33532 
   33533 /*
   33534 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
   33535 **
   33536 ** Space to hold the returned string is obtained from malloc.
   33537 */
   33538 static LPWSTR winUtf8ToUnicode(const char *zFilename){
   33539   int nChar;
   33540   LPWSTR zWideFilename;
   33541 
   33542   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
   33543   if( nChar==0 ){
   33544     return 0;
   33545   }
   33546   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
   33547   if( zWideFilename==0 ){
   33548     return 0;
   33549   }
   33550   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
   33551                                 nChar);
   33552   if( nChar==0 ){
   33553     sqlite3_free(zWideFilename);
   33554     zWideFilename = 0;
   33555   }
   33556   return zWideFilename;
   33557 }
   33558 
   33559 /*
   33560 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
   33561 ** obtained from sqlite3_malloc().
   33562 */
   33563 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
   33564   int nByte;
   33565   char *zFilename;
   33566 
   33567   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
   33568   if( nByte == 0 ){
   33569     return 0;
   33570   }
   33571   zFilename = sqlite3MallocZero( nByte );
   33572   if( zFilename==0 ){
   33573     return 0;
   33574   }
   33575   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
   33576                                 0, 0);
   33577   if( nByte == 0 ){
   33578     sqlite3_free(zFilename);
   33579     zFilename = 0;
   33580   }
   33581   return zFilename;
   33582 }
   33583 
   33584 /*
   33585 ** Convert an ANSI string to Microsoft Unicode, based on the
   33586 ** current codepage settings for file apis.
   33587 **
   33588 ** Space to hold the returned string is obtained
   33589 ** from sqlite3_malloc.
   33590 */
   33591 static LPWSTR winMbcsToUnicode(const char *zFilename){
   33592   int nByte;
   33593   LPWSTR zMbcsFilename;
   33594   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   33595 
   33596   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
   33597                                 0)*sizeof(WCHAR);
   33598   if( nByte==0 ){
   33599     return 0;
   33600   }
   33601   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
   33602   if( zMbcsFilename==0 ){
   33603     return 0;
   33604   }
   33605   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
   33606                                 nByte);
   33607   if( nByte==0 ){
   33608     sqlite3_free(zMbcsFilename);
   33609     zMbcsFilename = 0;
   33610   }
   33611   return zMbcsFilename;
   33612 }
   33613 
   33614 /*
   33615 ** Convert Microsoft Unicode to multi-byte character string, based on the
   33616 ** user's ANSI codepage.
   33617 **
   33618 ** Space to hold the returned string is obtained from
   33619 ** sqlite3_malloc().
   33620 */
   33621 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
   33622   int nByte;
   33623   char *zFilename;
   33624   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   33625 
   33626   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
   33627   if( nByte == 0 ){
   33628     return 0;
   33629   }
   33630   zFilename = sqlite3MallocZero( nByte );
   33631   if( zFilename==0 ){
   33632     return 0;
   33633   }
   33634   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
   33635                                 nByte, 0, 0);
   33636   if( nByte == 0 ){
   33637     sqlite3_free(zFilename);
   33638     zFilename = 0;
   33639   }
   33640   return zFilename;
   33641 }
   33642 
   33643 /*
   33644 ** Convert multibyte character string to UTF-8.  Space to hold the
   33645 ** returned string is obtained from sqlite3_malloc().
   33646 */
   33647 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
   33648   char *zFilenameUtf8;
   33649   LPWSTR zTmpWide;
   33650 
   33651   zTmpWide = winMbcsToUnicode(zFilename);
   33652   if( zTmpWide==0 ){
   33653     return 0;
   33654   }
   33655   zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
   33656   sqlite3_free(zTmpWide);
   33657   return zFilenameUtf8;
   33658 }
   33659 
   33660 /*
   33661 ** Convert UTF-8 to multibyte character string.  Space to hold the
   33662 ** returned string is obtained from sqlite3_malloc().
   33663 */
   33664 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
   33665   char *zFilenameMbcs;
   33666   LPWSTR zTmpWide;
   33667 
   33668   zTmpWide = winUtf8ToUnicode(zFilename);
   33669   if( zTmpWide==0 ){
   33670     return 0;
   33671   }
   33672   zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
   33673   sqlite3_free(zTmpWide);
   33674   return zFilenameMbcs;
   33675 }
   33676 
   33677 /*
   33678 ** This function sets the data directory or the temporary directory based on
   33679 ** the provided arguments.  The type argument must be 1 in order to set the
   33680 ** data directory or 2 in order to set the temporary directory.  The zValue
   33681 ** argument is the name of the directory to use.  The return value will be
   33682 ** SQLITE_OK if successful.
   33683 */
   33684 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
   33685   char **ppDirectory = 0;
   33686 #ifndef SQLITE_OMIT_AUTOINIT
   33687   int rc = sqlite3_initialize();
   33688   if( rc ) return rc;
   33689 #endif
   33690   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
   33691     ppDirectory = &sqlite3_data_directory;
   33692   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
   33693     ppDirectory = &sqlite3_temp_directory;
   33694   }
   33695   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
   33696           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
   33697   );
   33698   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
   33699   if( ppDirectory ){
   33700     char *zValueUtf8 = 0;
   33701     if( zValue && zValue[0] ){
   33702       zValueUtf8 = winUnicodeToUtf8(zValue);
   33703       if ( zValueUtf8==0 ){
   33704         return SQLITE_NOMEM;
   33705       }
   33706     }
   33707     sqlite3_free(*ppDirectory);
   33708     *ppDirectory = zValueUtf8;
   33709     return SQLITE_OK;
   33710   }
   33711   return SQLITE_ERROR;
   33712 }
   33713 
   33714 /*
   33715 ** The return value of winGetLastErrorMsg
   33716 ** is zero if the error message fits in the buffer, or non-zero
   33717 ** otherwise (if the message was truncated).
   33718 */
   33719 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
   33720   /* FormatMessage returns 0 on failure.  Otherwise it
   33721   ** returns the number of TCHARs written to the output
   33722   ** buffer, excluding the terminating null char.
   33723   */
   33724   DWORD dwLen = 0;
   33725   char *zOut = 0;
   33726 
   33727   if( osIsNT() ){
   33728 #if SQLITE_OS_WINRT
   33729     WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
   33730     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
   33731                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33732                              NULL,
   33733                              lastErrno,
   33734                              0,
   33735                              zTempWide,
   33736                              SQLITE_WIN32_MAX_ERRMSG_CHARS,
   33737                              0);
   33738 #else
   33739     LPWSTR zTempWide = NULL;
   33740     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   33741                              FORMAT_MESSAGE_FROM_SYSTEM |
   33742                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33743                              NULL,
   33744                              lastErrno,
   33745                              0,
   33746                              (LPWSTR) &zTempWide,
   33747                              0,
   33748                              0);
   33749 #endif
   33750     if( dwLen > 0 ){
   33751       /* allocate a buffer and convert to UTF8 */
   33752       sqlite3BeginBenignMalloc();
   33753       zOut = winUnicodeToUtf8(zTempWide);
   33754       sqlite3EndBenignMalloc();
   33755 #if !SQLITE_OS_WINRT
   33756       /* free the system buffer allocated by FormatMessage */
   33757       osLocalFree(zTempWide);
   33758 #endif
   33759     }
   33760   }
   33761 #ifdef SQLITE_WIN32_HAS_ANSI
   33762   else{
   33763     char *zTemp = NULL;
   33764     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   33765                              FORMAT_MESSAGE_FROM_SYSTEM |
   33766                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33767                              NULL,
   33768                              lastErrno,
   33769                              0,
   33770                              (LPSTR) &zTemp,
   33771                              0,
   33772                              0);
   33773     if( dwLen > 0 ){
   33774       /* allocate a buffer and convert to UTF8 */
   33775       sqlite3BeginBenignMalloc();
   33776       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   33777       sqlite3EndBenignMalloc();
   33778       /* free the system buffer allocated by FormatMessage */
   33779       osLocalFree(zTemp);
   33780     }
   33781   }
   33782 #endif
   33783   if( 0 == dwLen ){
   33784     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
   33785   }else{
   33786     /* copy a maximum of nBuf chars to output buffer */
   33787     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
   33788     /* free the UTF8 buffer */
   33789     sqlite3_free(zOut);
   33790   }
   33791   return 0;
   33792 }
   33793 
   33794 /*
   33795 **
   33796 ** This function - winLogErrorAtLine() - is only ever called via the macro
   33797 ** winLogError().
   33798 **
   33799 ** This routine is invoked after an error occurs in an OS function.
   33800 ** It logs a message using sqlite3_log() containing the current value of
   33801 ** error code and, if possible, the human-readable equivalent from
   33802 ** FormatMessage.
   33803 **
   33804 ** The first argument passed to the macro should be the error code that
   33805 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   33806 ** The two subsequent arguments should be the name of the OS function that
   33807 ** failed and the associated file-system path, if any.
   33808 */
   33809 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
   33810 static int winLogErrorAtLine(
   33811   int errcode,                    /* SQLite error code */
   33812   DWORD lastErrno,                /* Win32 last error */
   33813   const char *zFunc,              /* Name of OS function that failed */
   33814   const char *zPath,              /* File path associated with error */
   33815   int iLine                       /* Source line number where error occurred */
   33816 ){
   33817   char zMsg[500];                 /* Human readable error text */
   33818   int i;                          /* Loop counter */
   33819 
   33820   zMsg[0] = 0;
   33821   winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
   33822   assert( errcode!=SQLITE_OK );
   33823   if( zPath==0 ) zPath = "";
   33824   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
   33825   zMsg[i] = 0;
   33826   sqlite3_log(errcode,
   33827       "os_win.c:%d: (%lu) %s(%s) - %s",
   33828       iLine, lastErrno, zFunc, zPath, zMsg
   33829   );
   33830 
   33831   return errcode;
   33832 }
   33833 
   33834 /*
   33835 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
   33836 ** will be retried following a locking error - probably caused by
   33837 ** antivirus software.  Also the initial delay before the first retry.
   33838 ** The delay increases linearly with each retry.
   33839 */
   33840 #ifndef SQLITE_WIN32_IOERR_RETRY
   33841 # define SQLITE_WIN32_IOERR_RETRY 10
   33842 #endif
   33843 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
   33844 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
   33845 #endif
   33846 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
   33847 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
   33848 
   33849 /*
   33850 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
   33851 ** error code obtained via GetLastError() is eligible to be retried.  It
   33852 ** must accept the error code DWORD as its only argument and should return
   33853 ** non-zero if the error code is transient in nature and the operation
   33854 ** responsible for generating the original error might succeed upon being
   33855 ** retried.  The argument to this macro should be a variable.
   33856 **
   33857 ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
   33858 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
   33859 ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
   33860 ** may be used to include additional error codes in the set that should
   33861 ** result in the failing I/O operation being retried by the caller.  If
   33862 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
   33863 ** identical to those of the "winIoerrCanRetry1" macro.
   33864 */
   33865 #if !defined(winIoerrCanRetry1)
   33866 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
   33867                               ((a)==ERROR_SHARING_VIOLATION)    || \
   33868                               ((a)==ERROR_LOCK_VIOLATION)       || \
   33869                               ((a)==ERROR_DEV_NOT_EXIST)        || \
   33870                               ((a)==ERROR_NETNAME_DELETED)      || \
   33871                               ((a)==ERROR_SEM_TIMEOUT)          || \
   33872                               ((a)==ERROR_NETWORK_UNREACHABLE))
   33873 #endif
   33874 
   33875 /*
   33876 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
   33877 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
   33878 ** to give up with an error.
   33879 */
   33880 static int winRetryIoerr(int *pnRetry, DWORD *pError){
   33881   DWORD e = osGetLastError();
   33882   if( *pnRetry>=winIoerrRetry ){
   33883     if( pError ){
   33884       *pError = e;
   33885     }
   33886     return 0;
   33887   }
   33888   if( winIoerrCanRetry1(e) ){
   33889     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
   33890     ++*pnRetry;
   33891     return 1;
   33892   }
   33893 #if defined(winIoerrCanRetry2)
   33894   else if( winIoerrCanRetry2(e) ){
   33895     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
   33896     ++*pnRetry;
   33897     return 1;
   33898   }
   33899 #endif
   33900   if( pError ){
   33901     *pError = e;
   33902   }
   33903   return 0;
   33904 }
   33905 
   33906 /*
   33907 ** Log a I/O error retry episode.
   33908 */
   33909 static void winLogIoerr(int nRetry){
   33910   if( nRetry ){
   33911     sqlite3_log(SQLITE_IOERR,
   33912       "delayed %dms for lock/sharing conflict",
   33913       winIoerrRetryDelay*nRetry*(nRetry+1)/2
   33914     );
   33915   }
   33916 }
   33917 
   33918 #if SQLITE_OS_WINCE
   33919 /*************************************************************************
   33920 ** This section contains code for WinCE only.
   33921 */
   33922 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
   33923 /*
   33924 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
   33925 ** create a substitute.
   33926 */
   33927 /* #include <time.h> */
   33928 struct tm *__cdecl localtime(const time_t *t)
   33929 {
   33930   static struct tm y;
   33931   FILETIME uTm, lTm;
   33932   SYSTEMTIME pTm;
   33933   sqlite3_int64 t64;
   33934   t64 = *t;
   33935   t64 = (t64 + 11644473600)*10000000;
   33936   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
   33937   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
   33938   osFileTimeToLocalFileTime(&uTm,&lTm);
   33939   osFileTimeToSystemTime(&lTm,&pTm);
   33940   y.tm_year = pTm.wYear - 1900;
   33941   y.tm_mon = pTm.wMonth - 1;
   33942   y.tm_wday = pTm.wDayOfWeek;
   33943   y.tm_mday = pTm.wDay;
   33944   y.tm_hour = pTm.wHour;
   33945   y.tm_min = pTm.wMinute;
   33946   y.tm_sec = pTm.wSecond;
   33947   return &y;
   33948 }
   33949 #endif
   33950 
   33951 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
   33952 
   33953 /*
   33954 ** Acquire a lock on the handle h
   33955 */
   33956 static void winceMutexAcquire(HANDLE h){
   33957    DWORD dwErr;
   33958    do {
   33959      dwErr = osWaitForSingleObject(h, INFINITE);
   33960    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
   33961 }
   33962 /*
   33963 ** Release a lock acquired by winceMutexAcquire()
   33964 */
   33965 #define winceMutexRelease(h) ReleaseMutex(h)
   33966 
   33967 /*
   33968 ** Create the mutex and shared memory used for locking in the file
   33969 ** descriptor pFile
   33970 */
   33971 static int winceCreateLock(const char *zFilename, winFile *pFile){
   33972   LPWSTR zTok;
   33973   LPWSTR zName;
   33974   DWORD lastErrno;
   33975   BOOL bLogged = FALSE;
   33976   BOOL bInit = TRUE;
   33977 
   33978   zName = winUtf8ToUnicode(zFilename);
   33979   if( zName==0 ){
   33980     /* out of memory */
   33981     return SQLITE_IOERR_NOMEM;
   33982   }
   33983 
   33984   /* Initialize the local lockdata */
   33985   memset(&pFile->local, 0, sizeof(pFile->local));
   33986 
   33987   /* Replace the backslashes from the filename and lowercase it
   33988   ** to derive a mutex name. */
   33989   zTok = osCharLowerW(zName);
   33990   for (;*zTok;zTok++){
   33991     if (*zTok == '\\') *zTok = '_';
   33992   }
   33993 
   33994   /* Create/open the named mutex */
   33995   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
   33996   if (!pFile->hMutex){
   33997     pFile->lastErrno = osGetLastError();
   33998     sqlite3_free(zName);
   33999     return winLogError(SQLITE_IOERR, pFile->lastErrno,
   34000                        "winceCreateLock1", zFilename);
   34001   }
   34002 
   34003   /* Acquire the mutex before continuing */
   34004   winceMutexAcquire(pFile->hMutex);
   34005 
   34006   /* Since the names of named mutexes, semaphores, file mappings etc are
   34007   ** case-sensitive, take advantage of that by uppercasing the mutex name
   34008   ** and using that as the shared filemapping name.
   34009   */
   34010   osCharUpperW(zName);
   34011   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
   34012                                         PAGE_READWRITE, 0, sizeof(winceLock),
   34013                                         zName);
   34014 
   34015   /* Set a flag that indicates we're the first to create the memory so it
   34016   ** must be zero-initialized */
   34017   lastErrno = osGetLastError();
   34018   if (lastErrno == ERROR_ALREADY_EXISTS){
   34019     bInit = FALSE;
   34020   }
   34021 
   34022   sqlite3_free(zName);
   34023 
   34024   /* If we succeeded in making the shared memory handle, map it. */
   34025   if( pFile->hShared ){
   34026     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
   34027              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
   34028     /* If mapping failed, close the shared memory handle and erase it */
   34029     if( !pFile->shared ){
   34030       pFile->lastErrno = osGetLastError();
   34031       winLogError(SQLITE_IOERR, pFile->lastErrno,
   34032                   "winceCreateLock2", zFilename);
   34033       bLogged = TRUE;
   34034       osCloseHandle(pFile->hShared);
   34035       pFile->hShared = NULL;
   34036     }
   34037   }
   34038 
   34039   /* If shared memory could not be created, then close the mutex and fail */
   34040   if( pFile->hShared==NULL ){
   34041     if( !bLogged ){
   34042       pFile->lastErrno = lastErrno;
   34043       winLogError(SQLITE_IOERR, pFile->lastErrno,
   34044                   "winceCreateLock3", zFilename);
   34045       bLogged = TRUE;
   34046     }
   34047     winceMutexRelease(pFile->hMutex);
   34048     osCloseHandle(pFile->hMutex);
   34049     pFile->hMutex = NULL;
   34050     return SQLITE_IOERR;
   34051   }
   34052 
   34053   /* Initialize the shared memory if we're supposed to */
   34054   if( bInit ){
   34055     memset(pFile->shared, 0, sizeof(winceLock));
   34056   }
   34057 
   34058   winceMutexRelease(pFile->hMutex);
   34059   return SQLITE_OK;
   34060 }
   34061 
   34062 /*
   34063 ** Destroy the part of winFile that deals with wince locks
   34064 */
   34065 static void winceDestroyLock(winFile *pFile){
   34066   if (pFile->hMutex){
   34067     /* Acquire the mutex */
   34068     winceMutexAcquire(pFile->hMutex);
   34069 
   34070     /* The following blocks should probably assert in debug mode, but they
   34071        are to cleanup in case any locks remained open */
   34072     if (pFile->local.nReaders){
   34073       pFile->shared->nReaders --;
   34074     }
   34075     if (pFile->local.bReserved){
   34076       pFile->shared->bReserved = FALSE;
   34077     }
   34078     if (pFile->local.bPending){
   34079       pFile->shared->bPending = FALSE;
   34080     }
   34081     if (pFile->local.bExclusive){
   34082       pFile->shared->bExclusive = FALSE;
   34083     }
   34084 
   34085     /* De-reference and close our copy of the shared memory handle */
   34086     osUnmapViewOfFile(pFile->shared);
   34087     osCloseHandle(pFile->hShared);
   34088 
   34089     /* Done with the mutex */
   34090     winceMutexRelease(pFile->hMutex);
   34091     osCloseHandle(pFile->hMutex);
   34092     pFile->hMutex = NULL;
   34093   }
   34094 }
   34095 
   34096 /*
   34097 ** An implementation of the LockFile() API of Windows for CE
   34098 */
   34099 static BOOL winceLockFile(
   34100   LPHANDLE phFile,
   34101   DWORD dwFileOffsetLow,
   34102   DWORD dwFileOffsetHigh,
   34103   DWORD nNumberOfBytesToLockLow,
   34104   DWORD nNumberOfBytesToLockHigh
   34105 ){
   34106   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   34107   BOOL bReturn = FALSE;
   34108 
   34109   UNUSED_PARAMETER(dwFileOffsetHigh);
   34110   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   34111 
   34112   if (!pFile->hMutex) return TRUE;
   34113   winceMutexAcquire(pFile->hMutex);
   34114 
   34115   /* Wanting an exclusive lock? */
   34116   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
   34117        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   34118     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
   34119        pFile->shared->bExclusive = TRUE;
   34120        pFile->local.bExclusive = TRUE;
   34121        bReturn = TRUE;
   34122     }
   34123   }
   34124 
   34125   /* Want a read-only lock? */
   34126   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
   34127            nNumberOfBytesToLockLow == 1){
   34128     if (pFile->shared->bExclusive == 0){
   34129       pFile->local.nReaders ++;
   34130       if (pFile->local.nReaders == 1){
   34131         pFile->shared->nReaders ++;
   34132       }
   34133       bReturn = TRUE;
   34134     }
   34135   }
   34136 
   34137   /* Want a pending lock? */
   34138   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
   34139            && nNumberOfBytesToLockLow == 1){
   34140     /* If no pending lock has been acquired, then acquire it */
   34141     if (pFile->shared->bPending == 0) {
   34142       pFile->shared->bPending = TRUE;
   34143       pFile->local.bPending = TRUE;
   34144       bReturn = TRUE;
   34145     }
   34146   }
   34147 
   34148   /* Want a reserved lock? */
   34149   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
   34150            && nNumberOfBytesToLockLow == 1){
   34151     if (pFile->shared->bReserved == 0) {
   34152       pFile->shared->bReserved = TRUE;
   34153       pFile->local.bReserved = TRUE;
   34154       bReturn = TRUE;
   34155     }
   34156   }
   34157 
   34158   winceMutexRelease(pFile->hMutex);
   34159   return bReturn;
   34160 }
   34161 
   34162 /*
   34163 ** An implementation of the UnlockFile API of Windows for CE
   34164 */
   34165 static BOOL winceUnlockFile(
   34166   LPHANDLE phFile,
   34167   DWORD dwFileOffsetLow,
   34168   DWORD dwFileOffsetHigh,
   34169   DWORD nNumberOfBytesToUnlockLow,
   34170   DWORD nNumberOfBytesToUnlockHigh
   34171 ){
   34172   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   34173   BOOL bReturn = FALSE;
   34174 
   34175   UNUSED_PARAMETER(dwFileOffsetHigh);
   34176   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
   34177 
   34178   if (!pFile->hMutex) return TRUE;
   34179   winceMutexAcquire(pFile->hMutex);
   34180 
   34181   /* Releasing a reader lock or an exclusive lock */
   34182   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
   34183     /* Did we have an exclusive lock? */
   34184     if (pFile->local.bExclusive){
   34185       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
   34186       pFile->local.bExclusive = FALSE;
   34187       pFile->shared->bExclusive = FALSE;
   34188       bReturn = TRUE;
   34189     }
   34190 
   34191     /* Did we just have a reader lock? */
   34192     else if (pFile->local.nReaders){
   34193       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
   34194              || nNumberOfBytesToUnlockLow == 1);
   34195       pFile->local.nReaders --;
   34196       if (pFile->local.nReaders == 0)
   34197       {
   34198         pFile->shared->nReaders --;
   34199       }
   34200       bReturn = TRUE;
   34201     }
   34202   }
   34203 
   34204   /* Releasing a pending lock */
   34205   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
   34206            && nNumberOfBytesToUnlockLow == 1){
   34207     if (pFile->local.bPending){
   34208       pFile->local.bPending = FALSE;
   34209       pFile->shared->bPending = FALSE;
   34210       bReturn = TRUE;
   34211     }
   34212   }
   34213   /* Releasing a reserved lock */
   34214   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
   34215            && nNumberOfBytesToUnlockLow == 1){
   34216     if (pFile->local.bReserved) {
   34217       pFile->local.bReserved = FALSE;
   34218       pFile->shared->bReserved = FALSE;
   34219       bReturn = TRUE;
   34220     }
   34221   }
   34222 
   34223   winceMutexRelease(pFile->hMutex);
   34224   return bReturn;
   34225 }
   34226 /*
   34227 ** End of the special code for wince
   34228 *****************************************************************************/
   34229 #endif /* SQLITE_OS_WINCE */
   34230 
   34231 /*
   34232 ** Lock a file region.
   34233 */
   34234 static BOOL winLockFile(
   34235   LPHANDLE phFile,
   34236   DWORD flags,
   34237   DWORD offsetLow,
   34238   DWORD offsetHigh,
   34239   DWORD numBytesLow,
   34240   DWORD numBytesHigh
   34241 ){
   34242 #if SQLITE_OS_WINCE
   34243   /*
   34244   ** NOTE: Windows CE is handled differently here due its lack of the Win32
   34245   **       API LockFile.
   34246   */
   34247   return winceLockFile(phFile, offsetLow, offsetHigh,
   34248                        numBytesLow, numBytesHigh);
   34249 #else
   34250   if( osIsNT() ){
   34251     OVERLAPPED ovlp;
   34252     memset(&ovlp, 0, sizeof(OVERLAPPED));
   34253     ovlp.Offset = offsetLow;
   34254     ovlp.OffsetHigh = offsetHigh;
   34255     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
   34256   }else{
   34257     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
   34258                       numBytesHigh);
   34259   }
   34260 #endif
   34261 }
   34262 
   34263 /*
   34264 ** Unlock a file region.
   34265  */
   34266 static BOOL winUnlockFile(
   34267   LPHANDLE phFile,
   34268   DWORD offsetLow,
   34269   DWORD offsetHigh,
   34270   DWORD numBytesLow,
   34271   DWORD numBytesHigh
   34272 ){
   34273 #if SQLITE_OS_WINCE
   34274   /*
   34275   ** NOTE: Windows CE is handled differently here due its lack of the Win32
   34276   **       API UnlockFile.
   34277   */
   34278   return winceUnlockFile(phFile, offsetLow, offsetHigh,
   34279                          numBytesLow, numBytesHigh);
   34280 #else
   34281   if( osIsNT() ){
   34282     OVERLAPPED ovlp;
   34283     memset(&ovlp, 0, sizeof(OVERLAPPED));
   34284     ovlp.Offset = offsetLow;
   34285     ovlp.OffsetHigh = offsetHigh;
   34286     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
   34287   }else{
   34288     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
   34289                         numBytesHigh);
   34290   }
   34291 #endif
   34292 }
   34293 
   34294 /*****************************************************************************
   34295 ** The next group of routines implement the I/O methods specified
   34296 ** by the sqlite3_io_methods object.
   34297 ******************************************************************************/
   34298 
   34299 /*
   34300 ** Some Microsoft compilers lack this definition.
   34301 */
   34302 #ifndef INVALID_SET_FILE_POINTER
   34303 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
   34304 #endif
   34305 
   34306 /*
   34307 ** Move the current position of the file handle passed as the first
   34308 ** argument to offset iOffset within the file. If successful, return 0.
   34309 ** Otherwise, set pFile->lastErrno and return non-zero.
   34310 */
   34311 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
   34312 #if !SQLITE_OS_WINRT
   34313   LONG upperBits;                 /* Most sig. 32 bits of new offset */
   34314   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
   34315   DWORD dwRet;                    /* Value returned by SetFilePointer() */
   34316   DWORD lastErrno;                /* Value returned by GetLastError() */
   34317 
   34318   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
   34319 
   34320   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
   34321   lowerBits = (LONG)(iOffset & 0xffffffff);
   34322 
   34323   /* API oddity: If successful, SetFilePointer() returns a dword
   34324   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
   34325   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
   34326   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
   34327   ** whether an error has actually occurred, it is also necessary to call
   34328   ** GetLastError().
   34329   */
   34330   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   34331 
   34332   if( (dwRet==INVALID_SET_FILE_POINTER
   34333       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
   34334     pFile->lastErrno = lastErrno;
   34335     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
   34336                 "winSeekFile", pFile->zPath);
   34337     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
   34338     return 1;
   34339   }
   34340 
   34341   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
   34342   return 0;
   34343 #else
   34344   /*
   34345   ** Same as above, except that this implementation works for WinRT.
   34346   */
   34347 
   34348   LARGE_INTEGER x;                /* The new offset */
   34349   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
   34350 
   34351   x.QuadPart = iOffset;
   34352   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
   34353 
   34354   if(!bRet){
   34355     pFile->lastErrno = osGetLastError();
   34356     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
   34357                 "winSeekFile", pFile->zPath);
   34358     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
   34359     return 1;
   34360   }
   34361 
   34362   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
   34363   return 0;
   34364 #endif
   34365 }
   34366 
   34367 #if SQLITE_MAX_MMAP_SIZE>0
   34368 /* Forward references to VFS helper methods used for memory mapped files */
   34369 static int winMapfile(winFile*, sqlite3_int64);
   34370 static int winUnmapfile(winFile*);
   34371 #endif
   34372 
   34373 /*
   34374 ** Close a file.
   34375 **
   34376 ** It is reported that an attempt to close a handle might sometimes
   34377 ** fail.  This is a very unreasonable result, but Windows is notorious
   34378 ** for being unreasonable so I do not doubt that it might happen.  If
   34379 ** the close fails, we pause for 100 milliseconds and try again.  As
   34380 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
   34381 ** giving up and returning an error.
   34382 */
   34383 #define MX_CLOSE_ATTEMPT 3
   34384 static int winClose(sqlite3_file *id){
   34385   int rc, cnt = 0;
   34386   winFile *pFile = (winFile*)id;
   34387 
   34388   assert( id!=0 );
   34389 #ifndef SQLITE_OMIT_WAL
   34390   assert( pFile->pShm==0 );
   34391 #endif
   34392   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
   34393   OSTRACE(("CLOSE file=%p\n", pFile->h));
   34394 
   34395 #if SQLITE_MAX_MMAP_SIZE>0
   34396   winUnmapfile(pFile);
   34397 #endif
   34398 
   34399   do{
   34400     rc = osCloseHandle(pFile->h);
   34401     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
   34402   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
   34403 #if SQLITE_OS_WINCE
   34404 #define WINCE_DELETION_ATTEMPTS 3
   34405   winceDestroyLock(pFile);
   34406   if( pFile->zDeleteOnClose ){
   34407     int cnt = 0;
   34408     while(
   34409            osDeleteFileW(pFile->zDeleteOnClose)==0
   34410         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
   34411         && cnt++ < WINCE_DELETION_ATTEMPTS
   34412     ){
   34413        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
   34414     }
   34415     sqlite3_free(pFile->zDeleteOnClose);
   34416   }
   34417 #endif
   34418   if( rc ){
   34419     pFile->h = NULL;
   34420   }
   34421   OpenCounter(-1);
   34422   OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
   34423   return rc ? SQLITE_OK
   34424             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
   34425                           "winClose", pFile->zPath);
   34426 }
   34427 
   34428 /*
   34429 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   34430 ** bytes were read successfully and SQLITE_IOERR if anything goes
   34431 ** wrong.
   34432 */
   34433 static int winRead(
   34434   sqlite3_file *id,          /* File to read from */
   34435   void *pBuf,                /* Write content into this buffer */
   34436   int amt,                   /* Number of bytes to read */
   34437   sqlite3_int64 offset       /* Begin reading at this offset */
   34438 ){
   34439 #if !SQLITE_OS_WINCE
   34440   OVERLAPPED overlapped;          /* The offset for ReadFile. */
   34441 #endif
   34442   winFile *pFile = (winFile*)id;  /* file handle */
   34443   DWORD nRead;                    /* Number of bytes actually read from file */
   34444   int nRetry = 0;                 /* Number of retrys */
   34445 
   34446   assert( id!=0 );
   34447   assert( amt>0 );
   34448   assert( offset>=0 );
   34449   SimulateIOError(return SQLITE_IOERR_READ);
   34450   OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
   34451            pFile->h, pBuf, amt, offset, pFile->locktype));
   34452 
   34453 #if SQLITE_MAX_MMAP_SIZE>0
   34454   /* Deal with as much of this read request as possible by transfering
   34455   ** data from the memory mapping using memcpy().  */
   34456   if( offset<pFile->mmapSize ){
   34457     if( offset+amt <= pFile->mmapSize ){
   34458       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
   34459       OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
   34460       return SQLITE_OK;
   34461     }else{
   34462       int nCopy = (int)(pFile->mmapSize - offset);
   34463       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
   34464       pBuf = &((u8 *)pBuf)[nCopy];
   34465       amt -= nCopy;
   34466       offset += nCopy;
   34467     }
   34468   }
   34469 #endif
   34470 
   34471 #if SQLITE_OS_WINCE
   34472   if( winSeekFile(pFile, offset) ){
   34473     OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
   34474     return SQLITE_FULL;
   34475   }
   34476   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
   34477 #else
   34478   memset(&overlapped, 0, sizeof(OVERLAPPED));
   34479   overlapped.Offset = (LONG)(offset & 0xffffffff);
   34480   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   34481   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
   34482          osGetLastError()!=ERROR_HANDLE_EOF ){
   34483 #endif
   34484     DWORD lastErrno;
   34485     if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
   34486     pFile->lastErrno = lastErrno;
   34487     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
   34488     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
   34489                        "winRead", pFile->zPath);
   34490   }
   34491   winLogIoerr(nRetry);
   34492   if( nRead<(DWORD)amt ){
   34493     /* Unread parts of the buffer must be zero-filled */
   34494     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
   34495     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
   34496     return SQLITE_IOERR_SHORT_READ;
   34497   }
   34498 
   34499   OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
   34500   return SQLITE_OK;
   34501 }
   34502 
   34503 /*
   34504 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   34505 ** or some other error code on failure.
   34506 */
   34507 static int winWrite(
   34508   sqlite3_file *id,               /* File to write into */
   34509   const void *pBuf,               /* The bytes to be written */
   34510   int amt,                        /* Number of bytes to write */
   34511   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   34512 ){
   34513   int rc = 0;                     /* True if error has occurred, else false */
   34514   winFile *pFile = (winFile*)id;  /* File handle */
   34515   int nRetry = 0;                 /* Number of retries */
   34516 
   34517   assert( amt>0 );
   34518   assert( pFile );
   34519   SimulateIOError(return SQLITE_IOERR_WRITE);
   34520   SimulateDiskfullError(return SQLITE_FULL);
   34521 
   34522   OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
   34523            pFile->h, pBuf, amt, offset, pFile->locktype));
   34524 
   34525 #if SQLITE_MAX_MMAP_SIZE>0
   34526   /* Deal with as much of this write request as possible by transfering
   34527   ** data from the memory mapping using memcpy().  */
   34528   if( offset<pFile->mmapSize ){
   34529     if( offset+amt <= pFile->mmapSize ){
   34530       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
   34531       OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
   34532       return SQLITE_OK;
   34533     }else{
   34534       int nCopy = (int)(pFile->mmapSize - offset);
   34535       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
   34536       pBuf = &((u8 *)pBuf)[nCopy];
   34537       amt -= nCopy;
   34538       offset += nCopy;
   34539     }
   34540   }
   34541 #endif
   34542 
   34543 #if SQLITE_OS_WINCE
   34544   rc = winSeekFile(pFile, offset);
   34545   if( rc==0 ){
   34546 #else
   34547   {
   34548 #endif
   34549 #if !SQLITE_OS_WINCE
   34550     OVERLAPPED overlapped;        /* The offset for WriteFile. */
   34551 #endif
   34552     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
   34553     int nRem = amt;               /* Number of bytes yet to be written */
   34554     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
   34555     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
   34556 
   34557 #if !SQLITE_OS_WINCE
   34558     memset(&overlapped, 0, sizeof(OVERLAPPED));
   34559     overlapped.Offset = (LONG)(offset & 0xffffffff);
   34560     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   34561 #endif
   34562 
   34563     while( nRem>0 ){
   34564 #if SQLITE_OS_WINCE
   34565       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
   34566 #else
   34567       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
   34568 #endif
   34569         if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
   34570         break;
   34571       }
   34572       assert( nWrite==0 || nWrite<=(DWORD)nRem );
   34573       if( nWrite==0 || nWrite>(DWORD)nRem ){
   34574         lastErrno = osGetLastError();
   34575         break;
   34576       }
   34577 #if !SQLITE_OS_WINCE
   34578       offset += nWrite;
   34579       overlapped.Offset = (LONG)(offset & 0xffffffff);
   34580       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   34581 #endif
   34582       aRem += nWrite;
   34583       nRem -= nWrite;
   34584     }
   34585     if( nRem>0 ){
   34586       pFile->lastErrno = lastErrno;
   34587       rc = 1;
   34588     }
   34589   }
   34590 
   34591   if( rc ){
   34592     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
   34593        || ( pFile->lastErrno==ERROR_DISK_FULL )){
   34594       OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
   34595       return winLogError(SQLITE_FULL, pFile->lastErrno,
   34596                          "winWrite1", pFile->zPath);
   34597     }
   34598     OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
   34599     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
   34600                        "winWrite2", pFile->zPath);
   34601   }else{
   34602     winLogIoerr(nRetry);
   34603   }
   34604   OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
   34605   return SQLITE_OK;
   34606 }
   34607 
   34608 /*
   34609 ** Truncate an open file to a specified size
   34610 */
   34611 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
   34612   winFile *pFile = (winFile*)id;  /* File handle object */
   34613   int rc = SQLITE_OK;             /* Return code for this function */
   34614   DWORD lastErrno;
   34615 
   34616   assert( pFile );
   34617   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
   34618   OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
   34619            pFile->h, nByte, pFile->locktype));
   34620 
   34621   /* If the user has configured a chunk-size for this file, truncate the
   34622   ** file so that it consists of an integer number of chunks (i.e. the
   34623   ** actual file size after the operation may be larger than the requested
   34624   ** size).
   34625   */
   34626   if( pFile->szChunk>0 ){
   34627     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   34628   }
   34629 
   34630   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
   34631   if( winSeekFile(pFile, nByte) ){
   34632     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   34633                      "winTruncate1", pFile->zPath);
   34634   }else if( 0==osSetEndOfFile(pFile->h) &&
   34635             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
   34636     pFile->lastErrno = lastErrno;
   34637     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   34638                      "winTruncate2", pFile->zPath);
   34639   }
   34640 
   34641 #if SQLITE_MAX_MMAP_SIZE>0
   34642   /* If the file was truncated to a size smaller than the currently
   34643   ** mapped region, reduce the effective mapping size as well. SQLite will
   34644   ** use read() and write() to access data beyond this point from now on.
   34645   */
   34646   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
   34647     pFile->mmapSize = nByte;
   34648   }
   34649 #endif
   34650 
   34651   OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   34652   return rc;
   34653 }
   34654 
   34655 #ifdef SQLITE_TEST
   34656 /*
   34657 ** Count the number of fullsyncs and normal syncs.  This is used to test
   34658 ** that syncs and fullsyncs are occuring at the right times.
   34659 */
   34660 SQLITE_API int sqlite3_sync_count = 0;
   34661 SQLITE_API int sqlite3_fullsync_count = 0;
   34662 #endif
   34663 
   34664 /*
   34665 ** Make sure all writes to a particular file are committed to disk.
   34666 */
   34667 static int winSync(sqlite3_file *id, int flags){
   34668 #ifndef SQLITE_NO_SYNC
   34669   /*
   34670   ** Used only when SQLITE_NO_SYNC is not defined.
   34671    */
   34672   BOOL rc;
   34673 #endif
   34674 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
   34675     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
   34676   /*
   34677   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
   34678   ** OSTRACE() macros.
   34679    */
   34680   winFile *pFile = (winFile*)id;
   34681 #else
   34682   UNUSED_PARAMETER(id);
   34683 #endif
   34684 
   34685   assert( pFile );
   34686   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   34687   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   34688       || (flags&0x0F)==SQLITE_SYNC_FULL
   34689   );
   34690 
   34691   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   34692   ** line is to test that doing so does not cause any problems.
   34693   */
   34694   SimulateDiskfullError( return SQLITE_FULL );
   34695 
   34696   OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
   34697            pFile->h, flags, pFile->locktype));
   34698 
   34699 #ifndef SQLITE_TEST
   34700   UNUSED_PARAMETER(flags);
   34701 #else
   34702   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
   34703     sqlite3_fullsync_count++;
   34704   }
   34705   sqlite3_sync_count++;
   34706 #endif
   34707 
   34708   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   34709   ** no-op
   34710   */
   34711 #ifdef SQLITE_NO_SYNC
   34712   OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
   34713   return SQLITE_OK;
   34714 #else
   34715   rc = osFlushFileBuffers(pFile->h);
   34716   SimulateIOError( rc=FALSE );
   34717   if( rc ){
   34718     OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
   34719     return SQLITE_OK;
   34720   }else{
   34721     pFile->lastErrno = osGetLastError();
   34722     OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
   34723     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
   34724                        "winSync", pFile->zPath);
   34725   }
   34726 #endif
   34727 }
   34728 
   34729 /*
   34730 ** Determine the current size of a file in bytes
   34731 */
   34732 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
   34733   winFile *pFile = (winFile*)id;
   34734   int rc = SQLITE_OK;
   34735 
   34736   assert( id!=0 );
   34737   assert( pSize!=0 );
   34738   SimulateIOError(return SQLITE_IOERR_FSTAT);
   34739   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
   34740 
   34741 #if SQLITE_OS_WINRT
   34742   {
   34743     FILE_STANDARD_INFO info;
   34744     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
   34745                                      &info, sizeof(info)) ){
   34746       *pSize = info.EndOfFile.QuadPart;
   34747     }else{
   34748       pFile->lastErrno = osGetLastError();
   34749       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
   34750                        "winFileSize", pFile->zPath);
   34751     }
   34752   }
   34753 #else
   34754   {
   34755     DWORD upperBits;
   34756     DWORD lowerBits;
   34757     DWORD lastErrno;
   34758 
   34759     lowerBits = osGetFileSize(pFile->h, &upperBits);
   34760     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
   34761     if(   (lowerBits == INVALID_FILE_SIZE)
   34762        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
   34763       pFile->lastErrno = lastErrno;
   34764       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
   34765                        "winFileSize", pFile->zPath);
   34766     }
   34767   }
   34768 #endif
   34769   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
   34770            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
   34771   return rc;
   34772 }
   34773 
   34774 /*
   34775 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
   34776 */
   34777 #ifndef LOCKFILE_FAIL_IMMEDIATELY
   34778 # define LOCKFILE_FAIL_IMMEDIATELY 1
   34779 #endif
   34780 
   34781 #ifndef LOCKFILE_EXCLUSIVE_LOCK
   34782 # define LOCKFILE_EXCLUSIVE_LOCK 2
   34783 #endif
   34784 
   34785 /*
   34786 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
   34787 ** When the LockFile function was used, it was always expected to fail
   34788 ** immediately if the lock could not be obtained.  Also, it always expected to
   34789 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
   34790 ** and reflect those expectations; therefore, they should not be changed.
   34791 */
   34792 #ifndef SQLITE_LOCKFILE_FLAGS
   34793 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
   34794                                   LOCKFILE_EXCLUSIVE_LOCK)
   34795 #endif
   34796 
   34797 /*
   34798 ** Currently, SQLite never calls the LockFileEx function without wanting the
   34799 ** call to fail immediately if the lock cannot be obtained.
   34800 */
   34801 #ifndef SQLITE_LOCKFILEEX_FLAGS
   34802 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
   34803 #endif
   34804 
   34805 /*
   34806 ** Acquire a reader lock.
   34807 ** Different API routines are called depending on whether or not this
   34808 ** is Win9x or WinNT.
   34809 */
   34810 static int winGetReadLock(winFile *pFile){
   34811   int res;
   34812   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
   34813   if( osIsNT() ){
   34814 #if SQLITE_OS_WINCE
   34815     /*
   34816     ** NOTE: Windows CE is handled differently here due its lack of the Win32
   34817     **       API LockFileEx.
   34818     */
   34819     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
   34820 #else
   34821     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
   34822                       SHARED_SIZE, 0);
   34823 #endif
   34824   }
   34825 #ifdef SQLITE_WIN32_HAS_ANSI
   34826   else{
   34827     int lk;
   34828     sqlite3_randomness(sizeof(lk), &lk);
   34829     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
   34830     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
   34831                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   34832   }
   34833 #endif
   34834   if( res == 0 ){
   34835     pFile->lastErrno = osGetLastError();
   34836     /* No need to log a failure to lock */
   34837   }
   34838   OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
   34839   return res;
   34840 }
   34841 
   34842 /*
   34843 ** Undo a readlock
   34844 */
   34845 static int winUnlockReadLock(winFile *pFile){
   34846   int res;
   34847   DWORD lastErrno;
   34848   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
   34849   if( osIsNT() ){
   34850     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   34851   }
   34852 #ifdef SQLITE_WIN32_HAS_ANSI
   34853   else{
   34854     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   34855   }
   34856 #endif
   34857   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
   34858     pFile->lastErrno = lastErrno;
   34859     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
   34860                 "winUnlockReadLock", pFile->zPath);
   34861   }
   34862   OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
   34863   return res;
   34864 }
   34865 
   34866 /*
   34867 ** Lock the file with the lock specified by parameter locktype - one
   34868 ** of the following:
   34869 **
   34870 **     (1) SHARED_LOCK
   34871 **     (2) RESERVED_LOCK
   34872 **     (3) PENDING_LOCK
   34873 **     (4) EXCLUSIVE_LOCK
   34874 **
   34875 ** Sometimes when requesting one lock state, additional lock states
   34876 ** are inserted in between.  The locking might fail on one of the later
   34877 ** transitions leaving the lock state different from what it started but
   34878 ** still short of its goal.  The following chart shows the allowed
   34879 ** transitions and the inserted intermediate states:
   34880 **
   34881 **    UNLOCKED -> SHARED
   34882 **    SHARED -> RESERVED
   34883 **    SHARED -> (PENDING) -> EXCLUSIVE
   34884 **    RESERVED -> (PENDING) -> EXCLUSIVE
   34885 **    PENDING -> EXCLUSIVE
   34886 **
   34887 ** This routine will only increase a lock.  The winUnlock() routine
   34888 ** erases all locks at once and returns us immediately to locking level 0.
   34889 ** It is not possible to lower the locking level one step at a time.  You
   34890 ** must go straight to locking level 0.
   34891 */
   34892 static int winLock(sqlite3_file *id, int locktype){
   34893   int rc = SQLITE_OK;    /* Return code from subroutines */
   34894   int res = 1;           /* Result of a Windows lock call */
   34895   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   34896   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   34897   winFile *pFile = (winFile*)id;
   34898   DWORD lastErrno = NO_ERROR;
   34899 
   34900   assert( id!=0 );
   34901   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
   34902            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
   34903 
   34904   /* If there is already a lock of this type or more restrictive on the
   34905   ** OsFile, do nothing. Don't use the end_lock: exit path, as
   34906   ** sqlite3OsEnterMutex() hasn't been called yet.
   34907   */
   34908   if( pFile->locktype>=locktype ){
   34909     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
   34910     return SQLITE_OK;
   34911   }
   34912 
   34913   /* Make sure the locking sequence is correct
   34914   */
   34915   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   34916   assert( locktype!=PENDING_LOCK );
   34917   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   34918 
   34919   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   34920   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   34921   ** the PENDING_LOCK byte is temporary.
   34922   */
   34923   newLocktype = pFile->locktype;
   34924   if(   (pFile->locktype==NO_LOCK)
   34925      || (   (locktype==EXCLUSIVE_LOCK)
   34926          && (pFile->locktype==RESERVED_LOCK))
   34927   ){
   34928     int cnt = 3;
   34929     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
   34930                                          PENDING_BYTE, 0, 1, 0))==0 ){
   34931       /* Try 3 times to get the pending lock.  This is needed to work
   34932       ** around problems caused by indexing and/or anti-virus software on
   34933       ** Windows systems.
   34934       ** If you are using this code as a model for alternative VFSes, do not
   34935       ** copy this retry logic.  It is a hack intended for Windows only.
   34936       */
   34937       lastErrno = osGetLastError();
   34938       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
   34939                pFile->h, cnt, res));
   34940       if( lastErrno==ERROR_INVALID_HANDLE ){
   34941         pFile->lastErrno = lastErrno;
   34942         rc = SQLITE_IOERR_LOCK;
   34943         OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
   34944                  pFile->h, cnt, sqlite3ErrName(rc)));
   34945         return rc;
   34946       }
   34947       if( cnt ) sqlite3_win32_sleep(1);
   34948     }
   34949     gotPendingLock = res;
   34950     if( !res ){
   34951       lastErrno = osGetLastError();
   34952     }
   34953   }
   34954 
   34955   /* Acquire a shared lock
   34956   */
   34957   if( locktype==SHARED_LOCK && res ){
   34958     assert( pFile->locktype==NO_LOCK );
   34959     res = winGetReadLock(pFile);
   34960     if( res ){
   34961       newLocktype = SHARED_LOCK;
   34962     }else{
   34963       lastErrno = osGetLastError();
   34964     }
   34965   }
   34966 
   34967   /* Acquire a RESERVED lock
   34968   */
   34969   if( locktype==RESERVED_LOCK && res ){
   34970     assert( pFile->locktype==SHARED_LOCK );
   34971     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
   34972     if( res ){
   34973       newLocktype = RESERVED_LOCK;
   34974     }else{
   34975       lastErrno = osGetLastError();
   34976     }
   34977   }
   34978 
   34979   /* Acquire a PENDING lock
   34980   */
   34981   if( locktype==EXCLUSIVE_LOCK && res ){
   34982     newLocktype = PENDING_LOCK;
   34983     gotPendingLock = 0;
   34984   }
   34985 
   34986   /* Acquire an EXCLUSIVE lock
   34987   */
   34988   if( locktype==EXCLUSIVE_LOCK && res ){
   34989     assert( pFile->locktype>=SHARED_LOCK );
   34990     res = winUnlockReadLock(pFile);
   34991     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
   34992                       SHARED_SIZE, 0);
   34993     if( res ){
   34994       newLocktype = EXCLUSIVE_LOCK;
   34995     }else{
   34996       lastErrno = osGetLastError();
   34997       winGetReadLock(pFile);
   34998     }
   34999   }
   35000 
   35001   /* If we are holding a PENDING lock that ought to be released, then
   35002   ** release it now.
   35003   */
   35004   if( gotPendingLock && locktype==SHARED_LOCK ){
   35005     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
   35006   }
   35007 
   35008   /* Update the state of the lock has held in the file descriptor then
   35009   ** return the appropriate result code.
   35010   */
   35011   if( res ){
   35012     rc = SQLITE_OK;
   35013   }else{
   35014     pFile->lastErrno = lastErrno;
   35015     rc = SQLITE_BUSY;
   35016     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
   35017              pFile->h, locktype, newLocktype));
   35018   }
   35019   pFile->locktype = (u8)newLocktype;
   35020   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
   35021            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
   35022   return rc;
   35023 }
   35024 
   35025 /*
   35026 ** This routine checks if there is a RESERVED lock held on the specified
   35027 ** file by this or any other process. If such a lock is held, return
   35028 ** non-zero, otherwise zero.
   35029 */
   35030 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
   35031   int res;
   35032   winFile *pFile = (winFile*)id;
   35033 
   35034   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   35035   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
   35036 
   35037   assert( id!=0 );
   35038   if( pFile->locktype>=RESERVED_LOCK ){
   35039     res = 1;
   35040     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
   35041   }else{
   35042     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
   35043     if( res ){
   35044       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
   35045     }
   35046     res = !res;
   35047     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
   35048   }
   35049   *pResOut = res;
   35050   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
   35051            pFile->h, pResOut, *pResOut));
   35052   return SQLITE_OK;
   35053 }
   35054 
   35055 /*
   35056 ** Lower the locking level on file descriptor id to locktype.  locktype
   35057 ** must be either NO_LOCK or SHARED_LOCK.
   35058 **
   35059 ** If the locking level of the file descriptor is already at or below
   35060 ** the requested locking level, this routine is a no-op.
   35061 **
   35062 ** It is not possible for this routine to fail if the second argument
   35063 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   35064 ** might return SQLITE_IOERR;
   35065 */
   35066 static int winUnlock(sqlite3_file *id, int locktype){
   35067   int type;
   35068   winFile *pFile = (winFile*)id;
   35069   int rc = SQLITE_OK;
   35070   assert( pFile!=0 );
   35071   assert( locktype<=SHARED_LOCK );
   35072   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
   35073            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
   35074   type = pFile->locktype;
   35075   if( type>=EXCLUSIVE_LOCK ){
   35076     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   35077     if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
   35078       /* This should never happen.  We should always be able to
   35079       ** reacquire the read lock */
   35080       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
   35081                        "winUnlock", pFile->zPath);
   35082     }
   35083   }
   35084   if( type>=RESERVED_LOCK ){
   35085     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
   35086   }
   35087   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   35088     winUnlockReadLock(pFile);
   35089   }
   35090   if( type>=PENDING_LOCK ){
   35091     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
   35092   }
   35093   pFile->locktype = (u8)locktype;
   35094   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
   35095            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
   35096   return rc;
   35097 }
   35098 
   35099 /*
   35100 ** If *pArg is inititially negative then this is a query.  Set *pArg to
   35101 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   35102 **
   35103 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   35104 */
   35105 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
   35106   if( *pArg<0 ){
   35107     *pArg = (pFile->ctrlFlags & mask)!=0;
   35108   }else if( (*pArg)==0 ){
   35109     pFile->ctrlFlags &= ~mask;
   35110   }else{
   35111     pFile->ctrlFlags |= mask;
   35112   }
   35113 }
   35114 
   35115 /* Forward references to VFS helper methods used for temporary files */
   35116 static int winGetTempname(sqlite3_vfs *, char **);
   35117 static int winIsDir(const void *);
   35118 static BOOL winIsDriveLetterAndColon(const char *);
   35119 
   35120 /*
   35121 ** Control and query of the open file handle.
   35122 */
   35123 static int winFileControl(sqlite3_file *id, int op, void *pArg){
   35124   winFile *pFile = (winFile*)id;
   35125   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
   35126   switch( op ){
   35127     case SQLITE_FCNTL_LOCKSTATE: {
   35128       *(int*)pArg = pFile->locktype;
   35129       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35130       return SQLITE_OK;
   35131     }
   35132     case SQLITE_LAST_ERRNO: {
   35133       *(int*)pArg = (int)pFile->lastErrno;
   35134       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35135       return SQLITE_OK;
   35136     }
   35137     case SQLITE_FCNTL_CHUNK_SIZE: {
   35138       pFile->szChunk = *(int *)pArg;
   35139       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35140       return SQLITE_OK;
   35141     }
   35142     case SQLITE_FCNTL_SIZE_HINT: {
   35143       if( pFile->szChunk>0 ){
   35144         sqlite3_int64 oldSz;
   35145         int rc = winFileSize(id, &oldSz);
   35146         if( rc==SQLITE_OK ){
   35147           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
   35148           if( newSz>oldSz ){
   35149             SimulateIOErrorBenign(1);
   35150             rc = winTruncate(id, newSz);
   35151             SimulateIOErrorBenign(0);
   35152           }
   35153         }
   35154         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   35155         return rc;
   35156       }
   35157       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35158       return SQLITE_OK;
   35159     }
   35160     case SQLITE_FCNTL_PERSIST_WAL: {
   35161       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
   35162       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35163       return SQLITE_OK;
   35164     }
   35165     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   35166       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
   35167       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35168       return SQLITE_OK;
   35169     }
   35170     case SQLITE_FCNTL_VFSNAME: {
   35171       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
   35172       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35173       return SQLITE_OK;
   35174     }
   35175     case SQLITE_FCNTL_WIN32_AV_RETRY: {
   35176       int *a = (int*)pArg;
   35177       if( a[0]>0 ){
   35178         winIoerrRetry = a[0];
   35179       }else{
   35180         a[0] = winIoerrRetry;
   35181       }
   35182       if( a[1]>0 ){
   35183         winIoerrRetryDelay = a[1];
   35184       }else{
   35185         a[1] = winIoerrRetryDelay;
   35186       }
   35187       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   35188       return SQLITE_OK;
   35189     }
   35190 #ifdef SQLITE_TEST
   35191     case SQLITE_FCNTL_WIN32_SET_HANDLE: {
   35192       LPHANDLE phFile = (LPHANDLE)pArg;
   35193       HANDLE hOldFile = pFile->h;
   35194       pFile->h = *phFile;
   35195       *phFile = hOldFile;
   35196       OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
   35197                hOldFile, pFile->h));
   35198       return SQLITE_OK;
   35199     }
   35200 #endif
   35201     case SQLITE_FCNTL_TEMPFILENAME: {
   35202       char *zTFile = 0;
   35203       int rc = winGetTempname(pFile->pVfs, &zTFile);
   35204       if( rc==SQLITE_OK ){
   35205         *(char**)pArg = zTFile;
   35206       }
   35207       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   35208       return rc;
   35209     }
   35210 #if SQLITE_MAX_MMAP_SIZE>0
   35211     case SQLITE_FCNTL_MMAP_SIZE: {
   35212       i64 newLimit = *(i64*)pArg;
   35213       int rc = SQLITE_OK;
   35214       if( newLimit>sqlite3GlobalConfig.mxMmap ){
   35215         newLimit = sqlite3GlobalConfig.mxMmap;
   35216       }
   35217       *(i64*)pArg = pFile->mmapSizeMax;
   35218       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
   35219         pFile->mmapSizeMax = newLimit;
   35220         if( pFile->mmapSize>0 ){
   35221           winUnmapfile(pFile);
   35222           rc = winMapfile(pFile, -1);
   35223         }
   35224       }
   35225       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   35226       return rc;
   35227     }
   35228 #endif
   35229   }
   35230   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
   35231   return SQLITE_NOTFOUND;
   35232 }
   35233 
   35234 /*
   35235 ** Return the sector size in bytes of the underlying block device for
   35236 ** the specified file. This is almost always 512 bytes, but may be
   35237 ** larger for some devices.
   35238 **
   35239 ** SQLite code assumes this function cannot fail. It also assumes that
   35240 ** if two files are created in the same file-system directory (i.e.
   35241 ** a database and its journal file) that the sector size will be the
   35242 ** same for both.
   35243 */
   35244 static int winSectorSize(sqlite3_file *id){
   35245   (void)id;
   35246   return SQLITE_DEFAULT_SECTOR_SIZE;
   35247 }
   35248 
   35249 /*
   35250 ** Return a vector of device characteristics.
   35251 */
   35252 static int winDeviceCharacteristics(sqlite3_file *id){
   35253   winFile *p = (winFile*)id;
   35254   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
   35255          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
   35256 }
   35257 
   35258 /*
   35259 ** Windows will only let you create file view mappings
   35260 ** on allocation size granularity boundaries.
   35261 ** During sqlite3_os_init() we do a GetSystemInfo()
   35262 ** to get the granularity size.
   35263 */
   35264 static SYSTEM_INFO winSysInfo;
   35265 
   35266 #ifndef SQLITE_OMIT_WAL
   35267 
   35268 /*
   35269 ** Helper functions to obtain and relinquish the global mutex. The
   35270 ** global mutex is used to protect the winLockInfo objects used by
   35271 ** this file, all of which may be shared by multiple threads.
   35272 **
   35273 ** Function winShmMutexHeld() is used to assert() that the global mutex
   35274 ** is held when required. This function is only used as part of assert()
   35275 ** statements. e.g.
   35276 **
   35277 **   winShmEnterMutex()
   35278 **     assert( winShmMutexHeld() );
   35279 **   winShmLeaveMutex()
   35280 */
   35281 static void winShmEnterMutex(void){
   35282   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   35283 }
   35284 static void winShmLeaveMutex(void){
   35285   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   35286 }
   35287 #ifndef NDEBUG
   35288 static int winShmMutexHeld(void) {
   35289   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   35290 }
   35291 #endif
   35292 
   35293 /*
   35294 ** Object used to represent a single file opened and mmapped to provide
   35295 ** shared memory.  When multiple threads all reference the same
   35296 ** log-summary, each thread has its own winFile object, but they all
   35297 ** point to a single instance of this object.  In other words, each
   35298 ** log-summary is opened only once per process.
   35299 **
   35300 ** winShmMutexHeld() must be true when creating or destroying
   35301 ** this object or while reading or writing the following fields:
   35302 **
   35303 **      nRef
   35304 **      pNext
   35305 **
   35306 ** The following fields are read-only after the object is created:
   35307 **
   35308 **      fid
   35309 **      zFilename
   35310 **
   35311 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
   35312 ** winShmMutexHeld() is true when reading or writing any other field
   35313 ** in this structure.
   35314 **
   35315 */
   35316 struct winShmNode {
   35317   sqlite3_mutex *mutex;      /* Mutex to access this object */
   35318   char *zFilename;           /* Name of the file */
   35319   winFile hFile;             /* File handle from winOpen */
   35320 
   35321   int szRegion;              /* Size of shared-memory regions */
   35322   int nRegion;               /* Size of array apRegion */
   35323   struct ShmRegion {
   35324     HANDLE hMap;             /* File handle from CreateFileMapping */
   35325     void *pMap;
   35326   } *aRegion;
   35327   DWORD lastErrno;           /* The Windows errno from the last I/O error */
   35328 
   35329   int nRef;                  /* Number of winShm objects pointing to this */
   35330   winShm *pFirst;            /* All winShm objects pointing to this */
   35331   winShmNode *pNext;         /* Next in list of all winShmNode objects */
   35332 #ifdef SQLITE_DEBUG
   35333   u8 nextShmId;              /* Next available winShm.id value */
   35334 #endif
   35335 };
   35336 
   35337 /*
   35338 ** A global array of all winShmNode objects.
   35339 **
   35340 ** The winShmMutexHeld() must be true while reading or writing this list.
   35341 */
   35342 static winShmNode *winShmNodeList = 0;
   35343 
   35344 /*
   35345 ** Structure used internally by this VFS to record the state of an
   35346 ** open shared memory connection.
   35347 **
   35348 ** The following fields are initialized when this object is created and
   35349 ** are read-only thereafter:
   35350 **
   35351 **    winShm.pShmNode
   35352 **    winShm.id
   35353 **
   35354 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
   35355 ** while accessing any read/write fields.
   35356 */
   35357 struct winShm {
   35358   winShmNode *pShmNode;      /* The underlying winShmNode object */
   35359   winShm *pNext;             /* Next winShm with the same winShmNode */
   35360   u8 hasMutex;               /* True if holding the winShmNode mutex */
   35361   u16 sharedMask;            /* Mask of shared locks held */
   35362   u16 exclMask;              /* Mask of exclusive locks held */
   35363 #ifdef SQLITE_DEBUG
   35364   u8 id;                     /* Id of this connection with its winShmNode */
   35365 #endif
   35366 };
   35367 
   35368 /*
   35369 ** Constants used for locking
   35370 */
   35371 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
   35372 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   35373 
   35374 /*
   35375 ** Apply advisory locks for all n bytes beginning at ofst.
   35376 */
   35377 #define _SHM_UNLCK  1
   35378 #define _SHM_RDLCK  2
   35379 #define _SHM_WRLCK  3
   35380 static int winShmSystemLock(
   35381   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
   35382   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
   35383   int ofst,             /* Offset to first byte to be locked/unlocked */
   35384   int nByte             /* Number of bytes to lock or unlock */
   35385 ){
   35386   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
   35387 
   35388   /* Access to the winShmNode object is serialized by the caller */
   35389   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
   35390 
   35391   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
   35392            pFile->hFile.h, lockType, ofst, nByte));
   35393 
   35394   /* Release/Acquire the system-level lock */
   35395   if( lockType==_SHM_UNLCK ){
   35396     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
   35397   }else{
   35398     /* Initialize the locking parameters */
   35399     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
   35400     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
   35401     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
   35402   }
   35403 
   35404   if( rc!= 0 ){
   35405     rc = SQLITE_OK;
   35406   }else{
   35407     pFile->lastErrno =  osGetLastError();
   35408     rc = SQLITE_BUSY;
   35409   }
   35410 
   35411   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
   35412            pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
   35413            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
   35414 
   35415   return rc;
   35416 }
   35417 
   35418 /* Forward references to VFS methods */
   35419 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
   35420 static int winDelete(sqlite3_vfs *,const char*,int);
   35421 
   35422 /*
   35423 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
   35424 **
   35425 ** This is not a VFS shared-memory method; it is a utility function called
   35426 ** by VFS shared-memory methods.
   35427 */
   35428 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
   35429   winShmNode **pp;
   35430   winShmNode *p;
   35431   assert( winShmMutexHeld() );
   35432   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
   35433            osGetCurrentProcessId(), deleteFlag));
   35434   pp = &winShmNodeList;
   35435   while( (p = *pp)!=0 ){
   35436     if( p->nRef==0 ){
   35437       int i;
   35438       if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
   35439       for(i=0; i<p->nRegion; i++){
   35440         BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
   35441         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
   35442                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
   35443         UNUSED_VARIABLE_VALUE(bRc);
   35444         bRc = osCloseHandle(p->aRegion[i].hMap);
   35445         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
   35446                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
   35447         UNUSED_VARIABLE_VALUE(bRc);
   35448       }
   35449       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
   35450         SimulateIOErrorBenign(1);
   35451         winClose((sqlite3_file *)&p->hFile);
   35452         SimulateIOErrorBenign(0);
   35453       }
   35454       if( deleteFlag ){
   35455         SimulateIOErrorBenign(1);
   35456         sqlite3BeginBenignMalloc();
   35457         winDelete(pVfs, p->zFilename, 0);
   35458         sqlite3EndBenignMalloc();
   35459         SimulateIOErrorBenign(0);
   35460       }
   35461       *pp = p->pNext;
   35462       sqlite3_free(p->aRegion);
   35463       sqlite3_free(p);
   35464     }else{
   35465       pp = &p->pNext;
   35466     }
   35467   }
   35468 }
   35469 
   35470 /*
   35471 ** Open the shared-memory area associated with database file pDbFd.
   35472 **
   35473 ** When opening a new shared-memory file, if no other instances of that
   35474 ** file are currently open, in this process or in other processes, then
   35475 ** the file must be truncated to zero length or have its header cleared.
   35476 */
   35477 static int winOpenSharedMemory(winFile *pDbFd){
   35478   struct winShm *p;                  /* The connection to be opened */
   35479   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
   35480   int rc;                            /* Result code */
   35481   struct winShmNode *pNew;           /* Newly allocated winShmNode */
   35482   int nName;                         /* Size of zName in bytes */
   35483 
   35484   assert( pDbFd->pShm==0 );    /* Not previously opened */
   35485 
   35486   /* Allocate space for the new sqlite3_shm object.  Also speculatively
   35487   ** allocate space for a new winShmNode and filename.
   35488   */
   35489   p = sqlite3MallocZero( sizeof(*p) );
   35490   if( p==0 ) return SQLITE_IOERR_NOMEM;
   35491   nName = sqlite3Strlen30(pDbFd->zPath);
   35492   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
   35493   if( pNew==0 ){
   35494     sqlite3_free(p);
   35495     return SQLITE_IOERR_NOMEM;
   35496   }
   35497   pNew->zFilename = (char*)&pNew[1];
   35498   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
   35499   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
   35500 
   35501   /* Look to see if there is an existing winShmNode that can be used.
   35502   ** If no matching winShmNode currently exists, create a new one.
   35503   */
   35504   winShmEnterMutex();
   35505   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
   35506     /* TBD need to come up with better match here.  Perhaps
   35507     ** use FILE_ID_BOTH_DIR_INFO Structure.
   35508     */
   35509     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
   35510   }
   35511   if( pShmNode ){
   35512     sqlite3_free(pNew);
   35513   }else{
   35514     pShmNode = pNew;
   35515     pNew = 0;
   35516     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
   35517     pShmNode->pNext = winShmNodeList;
   35518     winShmNodeList = pShmNode;
   35519 
   35520     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   35521     if( pShmNode->mutex==0 ){
   35522       rc = SQLITE_IOERR_NOMEM;
   35523       goto shm_open_err;
   35524     }
   35525 
   35526     rc = winOpen(pDbFd->pVfs,
   35527                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
   35528                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
   35529                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
   35530                  0);
   35531     if( SQLITE_OK!=rc ){
   35532       goto shm_open_err;
   35533     }
   35534 
   35535     /* Check to see if another process is holding the dead-man switch.
   35536     ** If not, truncate the file to zero length.
   35537     */
   35538     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
   35539       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
   35540       if( rc!=SQLITE_OK ){
   35541         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
   35542                          "winOpenShm", pDbFd->zPath);
   35543       }
   35544     }
   35545     if( rc==SQLITE_OK ){
   35546       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   35547       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
   35548     }
   35549     if( rc ) goto shm_open_err;
   35550   }
   35551 
   35552   /* Make the new connection a child of the winShmNode */
   35553   p->pShmNode = pShmNode;
   35554 #ifdef SQLITE_DEBUG
   35555   p->id = pShmNode->nextShmId++;
   35556 #endif
   35557   pShmNode->nRef++;
   35558   pDbFd->pShm = p;
   35559   winShmLeaveMutex();
   35560 
   35561   /* The reference count on pShmNode has already been incremented under
   35562   ** the cover of the winShmEnterMutex() mutex and the pointer from the
   35563   ** new (struct winShm) object to the pShmNode has been set. All that is
   35564   ** left to do is to link the new object into the linked list starting
   35565   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   35566   ** mutex.
   35567   */
   35568   sqlite3_mutex_enter(pShmNode->mutex);
   35569   p->pNext = pShmNode->pFirst;
   35570   pShmNode->pFirst = p;
   35571   sqlite3_mutex_leave(pShmNode->mutex);
   35572   return SQLITE_OK;
   35573 
   35574   /* Jump here on any error */
   35575 shm_open_err:
   35576   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   35577   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
   35578   sqlite3_free(p);
   35579   sqlite3_free(pNew);
   35580   winShmLeaveMutex();
   35581   return rc;
   35582 }
   35583 
   35584 /*
   35585 ** Close a connection to shared-memory.  Delete the underlying
   35586 ** storage if deleteFlag is true.
   35587 */
   35588 static int winShmUnmap(
   35589   sqlite3_file *fd,          /* Database holding shared memory */
   35590   int deleteFlag             /* Delete after closing if true */
   35591 ){
   35592   winFile *pDbFd;       /* Database holding shared-memory */
   35593   winShm *p;            /* The connection to be closed */
   35594   winShmNode *pShmNode; /* The underlying shared-memory file */
   35595   winShm **pp;          /* For looping over sibling connections */
   35596 
   35597   pDbFd = (winFile*)fd;
   35598   p = pDbFd->pShm;
   35599   if( p==0 ) return SQLITE_OK;
   35600   pShmNode = p->pShmNode;
   35601 
   35602   /* Remove connection p from the set of connections associated
   35603   ** with pShmNode */
   35604   sqlite3_mutex_enter(pShmNode->mutex);
   35605   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   35606   *pp = p->pNext;
   35607 
   35608   /* Free the connection p */
   35609   sqlite3_free(p);
   35610   pDbFd->pShm = 0;
   35611   sqlite3_mutex_leave(pShmNode->mutex);
   35612 
   35613   /* If pShmNode->nRef has reached 0, then close the underlying
   35614   ** shared-memory file, too */
   35615   winShmEnterMutex();
   35616   assert( pShmNode->nRef>0 );
   35617   pShmNode->nRef--;
   35618   if( pShmNode->nRef==0 ){
   35619     winShmPurge(pDbFd->pVfs, deleteFlag);
   35620   }
   35621   winShmLeaveMutex();
   35622 
   35623   return SQLITE_OK;
   35624 }
   35625 
   35626 /*
   35627 ** Change the lock state for a shared-memory segment.
   35628 */
   35629 static int winShmLock(
   35630   sqlite3_file *fd,          /* Database file holding the shared memory */
   35631   int ofst,                  /* First lock to acquire or release */
   35632   int n,                     /* Number of locks to acquire or release */
   35633   int flags                  /* What to do with the lock */
   35634 ){
   35635   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
   35636   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
   35637   winShm *pX;                           /* For looping over all siblings */
   35638   winShmNode *pShmNode = p->pShmNode;
   35639   int rc = SQLITE_OK;                   /* Result code */
   35640   u16 mask;                             /* Mask of locks to take or release */
   35641 
   35642   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   35643   assert( n>=1 );
   35644   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   35645        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   35646        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   35647        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   35648   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   35649 
   35650   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
   35651   assert( n>1 || mask==(1<<ofst) );
   35652   sqlite3_mutex_enter(pShmNode->mutex);
   35653   if( flags & SQLITE_SHM_UNLOCK ){
   35654     u16 allMask = 0; /* Mask of locks held by siblings */
   35655 
   35656     /* See if any siblings hold this same lock */
   35657     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35658       if( pX==p ) continue;
   35659       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   35660       allMask |= pX->sharedMask;
   35661     }
   35662 
   35663     /* Unlock the system-level locks */
   35664     if( (mask & allMask)==0 ){
   35665       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
   35666     }else{
   35667       rc = SQLITE_OK;
   35668     }
   35669 
   35670     /* Undo the local locks */
   35671     if( rc==SQLITE_OK ){
   35672       p->exclMask &= ~mask;
   35673       p->sharedMask &= ~mask;
   35674     }
   35675   }else if( flags & SQLITE_SHM_SHARED ){
   35676     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   35677 
   35678     /* Find out which shared locks are already held by sibling connections.
   35679     ** If any sibling already holds an exclusive lock, go ahead and return
   35680     ** SQLITE_BUSY.
   35681     */
   35682     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35683       if( (pX->exclMask & mask)!=0 ){
   35684         rc = SQLITE_BUSY;
   35685         break;
   35686       }
   35687       allShared |= pX->sharedMask;
   35688     }
   35689 
   35690     /* Get shared locks at the system level, if necessary */
   35691     if( rc==SQLITE_OK ){
   35692       if( (allShared & mask)==0 ){
   35693         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
   35694       }else{
   35695         rc = SQLITE_OK;
   35696       }
   35697     }
   35698 
   35699     /* Get the local shared locks */
   35700     if( rc==SQLITE_OK ){
   35701       p->sharedMask |= mask;
   35702     }
   35703   }else{
   35704     /* Make sure no sibling connections hold locks that will block this
   35705     ** lock.  If any do, return SQLITE_BUSY right away.
   35706     */
   35707     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35708       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   35709         rc = SQLITE_BUSY;
   35710         break;
   35711       }
   35712     }
   35713 
   35714     /* Get the exclusive locks at the system level.  Then if successful
   35715     ** also mark the local connection as being locked.
   35716     */
   35717     if( rc==SQLITE_OK ){
   35718       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
   35719       if( rc==SQLITE_OK ){
   35720         assert( (p->sharedMask & mask)==0 );
   35721         p->exclMask |= mask;
   35722       }
   35723     }
   35724   }
   35725   sqlite3_mutex_leave(pShmNode->mutex);
   35726   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
   35727            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
   35728            sqlite3ErrName(rc)));
   35729   return rc;
   35730 }
   35731 
   35732 /*
   35733 ** Implement a memory barrier or memory fence on shared memory.
   35734 **
   35735 ** All loads and stores begun before the barrier must complete before
   35736 ** any load or store begun after the barrier.
   35737 */
   35738 static void winShmBarrier(
   35739   sqlite3_file *fd          /* Database holding the shared memory */
   35740 ){
   35741   UNUSED_PARAMETER(fd);
   35742   /* MemoryBarrier(); // does not work -- do not know why not */
   35743   winShmEnterMutex();
   35744   winShmLeaveMutex();
   35745 }
   35746 
   35747 /*
   35748 ** This function is called to obtain a pointer to region iRegion of the
   35749 ** shared-memory associated with the database file fd. Shared-memory regions
   35750 ** are numbered starting from zero. Each shared-memory region is szRegion
   35751 ** bytes in size.
   35752 **
   35753 ** If an error occurs, an error code is returned and *pp is set to NULL.
   35754 **
   35755 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
   35756 ** region has not been allocated (by any client, including one running in a
   35757 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   35758 ** isWrite is non-zero and the requested shared-memory region has not yet
   35759 ** been allocated, it is allocated by this function.
   35760 **
   35761 ** If the shared-memory region has already been allocated or is allocated by
   35762 ** this call as described above, then it is mapped into this processes
   35763 ** address space (if it is not already), *pp is set to point to the mapped
   35764 ** memory and SQLITE_OK returned.
   35765 */
   35766 static int winShmMap(
   35767   sqlite3_file *fd,               /* Handle open on database file */
   35768   int iRegion,                    /* Region to retrieve */
   35769   int szRegion,                   /* Size of regions */
   35770   int isWrite,                    /* True to extend file if necessary */
   35771   void volatile **pp              /* OUT: Mapped memory */
   35772 ){
   35773   winFile *pDbFd = (winFile*)fd;
   35774   winShm *p = pDbFd->pShm;
   35775   winShmNode *pShmNode;
   35776   int rc = SQLITE_OK;
   35777 
   35778   if( !p ){
   35779     rc = winOpenSharedMemory(pDbFd);
   35780     if( rc!=SQLITE_OK ) return rc;
   35781     p = pDbFd->pShm;
   35782   }
   35783   pShmNode = p->pShmNode;
   35784 
   35785   sqlite3_mutex_enter(pShmNode->mutex);
   35786   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   35787 
   35788   if( pShmNode->nRegion<=iRegion ){
   35789     struct ShmRegion *apNew;           /* New aRegion[] array */
   35790     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   35791     sqlite3_int64 sz;                  /* Current size of wal-index file */
   35792 
   35793     pShmNode->szRegion = szRegion;
   35794 
   35795     /* The requested region is not mapped into this processes address space.
   35796     ** Check to see if it has been allocated (i.e. if the wal-index file is
   35797     ** large enough to contain the requested region).
   35798     */
   35799     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
   35800     if( rc!=SQLITE_OK ){
   35801       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   35802                        "winShmMap1", pDbFd->zPath);
   35803       goto shmpage_out;
   35804     }
   35805 
   35806     if( sz<nByte ){
   35807       /* The requested memory region does not exist. If isWrite is set to
   35808       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
   35809       **
   35810       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
   35811       ** the requested memory region.
   35812       */
   35813       if( !isWrite ) goto shmpage_out;
   35814       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
   35815       if( rc!=SQLITE_OK ){
   35816         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   35817                          "winShmMap2", pDbFd->zPath);
   35818         goto shmpage_out;
   35819       }
   35820     }
   35821 
   35822     /* Map the requested memory region into this processes address space. */
   35823     apNew = (struct ShmRegion *)sqlite3_realloc(
   35824         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
   35825     );
   35826     if( !apNew ){
   35827       rc = SQLITE_IOERR_NOMEM;
   35828       goto shmpage_out;
   35829     }
   35830     pShmNode->aRegion = apNew;
   35831 
   35832     while( pShmNode->nRegion<=iRegion ){
   35833       HANDLE hMap = NULL;         /* file-mapping handle */
   35834       void *pMap = 0;             /* Mapped memory region */
   35835 
   35836 #if SQLITE_OS_WINRT
   35837       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
   35838           NULL, PAGE_READWRITE, nByte, NULL
   35839       );
   35840 #elif defined(SQLITE_WIN32_HAS_WIDE)
   35841       hMap = osCreateFileMappingW(pShmNode->hFile.h,
   35842           NULL, PAGE_READWRITE, 0, nByte, NULL
   35843       );
   35844 #elif defined(SQLITE_WIN32_HAS_ANSI)
   35845       hMap = osCreateFileMappingA(pShmNode->hFile.h,
   35846           NULL, PAGE_READWRITE, 0, nByte, NULL
   35847       );
   35848 #endif
   35849       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
   35850                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
   35851                hMap ? "ok" : "failed"));
   35852       if( hMap ){
   35853         int iOffset = pShmNode->nRegion*szRegion;
   35854         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   35855 #if SQLITE_OS_WINRT
   35856         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
   35857             iOffset - iOffsetShift, szRegion + iOffsetShift
   35858         );
   35859 #else
   35860         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
   35861             0, iOffset - iOffsetShift, szRegion + iOffsetShift
   35862         );
   35863 #endif
   35864         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
   35865                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
   35866                  szRegion, pMap ? "ok" : "failed"));
   35867       }
   35868       if( !pMap ){
   35869         pShmNode->lastErrno = osGetLastError();
   35870         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
   35871                          "winShmMap3", pDbFd->zPath);
   35872         if( hMap ) osCloseHandle(hMap);
   35873         goto shmpage_out;
   35874       }
   35875 
   35876       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
   35877       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
   35878       pShmNode->nRegion++;
   35879     }
   35880   }
   35881 
   35882 shmpage_out:
   35883   if( pShmNode->nRegion>iRegion ){
   35884     int iOffset = iRegion*szRegion;
   35885     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   35886     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
   35887     *pp = (void *)&p[iOffsetShift];
   35888   }else{
   35889     *pp = 0;
   35890   }
   35891   sqlite3_mutex_leave(pShmNode->mutex);
   35892   return rc;
   35893 }
   35894 
   35895 #else
   35896 # define winShmMap     0
   35897 # define winShmLock    0
   35898 # define winShmBarrier 0
   35899 # define winShmUnmap   0
   35900 #endif /* #ifndef SQLITE_OMIT_WAL */
   35901 
   35902 /*
   35903 ** Cleans up the mapped region of the specified file, if any.
   35904 */
   35905 #if SQLITE_MAX_MMAP_SIZE>0
   35906 static int winUnmapfile(winFile *pFile){
   35907   assert( pFile!=0 );
   35908   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
   35909            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
   35910            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
   35911            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
   35912   if( pFile->pMapRegion ){
   35913     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
   35914       pFile->lastErrno = osGetLastError();
   35915       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
   35916                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
   35917                pFile->pMapRegion));
   35918       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
   35919                          "winUnmapfile1", pFile->zPath);
   35920     }
   35921     pFile->pMapRegion = 0;
   35922     pFile->mmapSize = 0;
   35923     pFile->mmapSizeActual = 0;
   35924   }
   35925   if( pFile->hMap!=NULL ){
   35926     if( !osCloseHandle(pFile->hMap) ){
   35927       pFile->lastErrno = osGetLastError();
   35928       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
   35929                osGetCurrentProcessId(), pFile, pFile->hMap));
   35930       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
   35931                          "winUnmapfile2", pFile->zPath);
   35932     }
   35933     pFile->hMap = NULL;
   35934   }
   35935   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   35936            osGetCurrentProcessId(), pFile));
   35937   return SQLITE_OK;
   35938 }
   35939 
   35940 /*
   35941 ** Memory map or remap the file opened by file-descriptor pFd (if the file
   35942 ** is already mapped, the existing mapping is replaced by the new). Or, if
   35943 ** there already exists a mapping for this file, and there are still
   35944 ** outstanding xFetch() references to it, this function is a no-op.
   35945 **
   35946 ** If parameter nByte is non-negative, then it is the requested size of
   35947 ** the mapping to create. Otherwise, if nByte is less than zero, then the
   35948 ** requested size is the size of the file on disk. The actual size of the
   35949 ** created mapping is either the requested size or the value configured
   35950 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
   35951 **
   35952 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
   35953 ** recreated as a result of outstanding references) or an SQLite error
   35954 ** code otherwise.
   35955 */
   35956 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
   35957   sqlite3_int64 nMap = nByte;
   35958   int rc;
   35959 
   35960   assert( nMap>=0 || pFd->nFetchOut==0 );
   35961   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
   35962            osGetCurrentProcessId(), pFd, nByte));
   35963 
   35964   if( pFd->nFetchOut>0 ) return SQLITE_OK;
   35965 
   35966   if( nMap<0 ){
   35967     rc = winFileSize((sqlite3_file*)pFd, &nMap);
   35968     if( rc ){
   35969       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
   35970                osGetCurrentProcessId(), pFd));
   35971       return SQLITE_IOERR_FSTAT;
   35972     }
   35973   }
   35974   if( nMap>pFd->mmapSizeMax ){
   35975     nMap = pFd->mmapSizeMax;
   35976   }
   35977   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
   35978 
   35979   if( nMap==0 && pFd->mmapSize>0 ){
   35980     winUnmapfile(pFd);
   35981   }
   35982   if( nMap!=pFd->mmapSize ){
   35983     void *pNew = 0;
   35984     DWORD protect = PAGE_READONLY;
   35985     DWORD flags = FILE_MAP_READ;
   35986 
   35987     winUnmapfile(pFd);
   35988     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
   35989       protect = PAGE_READWRITE;
   35990       flags |= FILE_MAP_WRITE;
   35991     }
   35992 #if SQLITE_OS_WINRT
   35993     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
   35994 #elif defined(SQLITE_WIN32_HAS_WIDE)
   35995     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
   35996                                 (DWORD)((nMap>>32) & 0xffffffff),
   35997                                 (DWORD)(nMap & 0xffffffff), NULL);
   35998 #elif defined(SQLITE_WIN32_HAS_ANSI)
   35999     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
   36000                                 (DWORD)((nMap>>32) & 0xffffffff),
   36001                                 (DWORD)(nMap & 0xffffffff), NULL);
   36002 #endif
   36003     if( pFd->hMap==NULL ){
   36004       pFd->lastErrno = osGetLastError();
   36005       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
   36006                        "winMapfile1", pFd->zPath);
   36007       /* Log the error, but continue normal operation using xRead/xWrite */
   36008       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
   36009                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   36010       return SQLITE_OK;
   36011     }
   36012     assert( (nMap % winSysInfo.dwPageSize)==0 );
   36013     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
   36014 #if SQLITE_OS_WINRT
   36015     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
   36016 #else
   36017     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
   36018 #endif
   36019     if( pNew==NULL ){
   36020       osCloseHandle(pFd->hMap);
   36021       pFd->hMap = NULL;
   36022       pFd->lastErrno = osGetLastError();
   36023       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
   36024                        "winMapfile2", pFd->zPath);
   36025       /* Log the error, but continue normal operation using xRead/xWrite */
   36026       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
   36027                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   36028       return SQLITE_OK;
   36029     }
   36030     pFd->pMapRegion = pNew;
   36031     pFd->mmapSize = nMap;
   36032     pFd->mmapSizeActual = nMap;
   36033   }
   36034 
   36035   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   36036            osGetCurrentProcessId(), pFd));
   36037   return SQLITE_OK;
   36038 }
   36039 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   36040 
   36041 /*
   36042 ** If possible, return a pointer to a mapping of file fd starting at offset
   36043 ** iOff. The mapping must be valid for at least nAmt bytes.
   36044 **
   36045 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
   36046 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
   36047 ** Finally, if an error does occur, return an SQLite error code. The final
   36048 ** value of *pp is undefined in this case.
   36049 **
   36050 ** If this function does return a pointer, the caller must eventually
   36051 ** release the reference by calling winUnfetch().
   36052 */
   36053 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
   36054 #if SQLITE_MAX_MMAP_SIZE>0
   36055   winFile *pFd = (winFile*)fd;   /* The underlying database file */
   36056 #endif
   36057   *pp = 0;
   36058 
   36059   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
   36060            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
   36061 
   36062 #if SQLITE_MAX_MMAP_SIZE>0
   36063   if( pFd->mmapSizeMax>0 ){
   36064     if( pFd->pMapRegion==0 ){
   36065       int rc = winMapfile(pFd, -1);
   36066       if( rc!=SQLITE_OK ){
   36067         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
   36068                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   36069         return rc;
   36070       }
   36071     }
   36072     if( pFd->mmapSize >= iOff+nAmt ){
   36073       *pp = &((u8 *)pFd->pMapRegion)[iOff];
   36074       pFd->nFetchOut++;
   36075     }
   36076   }
   36077 #endif
   36078 
   36079   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
   36080            osGetCurrentProcessId(), fd, pp, *pp));
   36081   return SQLITE_OK;
   36082 }
   36083 
   36084 /*
   36085 ** If the third argument is non-NULL, then this function releases a
   36086 ** reference obtained by an earlier call to winFetch(). The second
   36087 ** argument passed to this function must be the same as the corresponding
   36088 ** argument that was passed to the winFetch() invocation.
   36089 **
   36090 ** Or, if the third argument is NULL, then this function is being called
   36091 ** to inform the VFS layer that, according to POSIX, any existing mapping
   36092 ** may now be invalid and should be unmapped.
   36093 */
   36094 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
   36095 #if SQLITE_MAX_MMAP_SIZE>0
   36096   winFile *pFd = (winFile*)fd;   /* The underlying database file */
   36097 
   36098   /* If p==0 (unmap the entire file) then there must be no outstanding
   36099   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
   36100   ** then there must be at least one outstanding.  */
   36101   assert( (p==0)==(pFd->nFetchOut==0) );
   36102 
   36103   /* If p!=0, it must match the iOff value. */
   36104   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
   36105 
   36106   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
   36107            osGetCurrentProcessId(), pFd, iOff, p));
   36108 
   36109   if( p ){
   36110     pFd->nFetchOut--;
   36111   }else{
   36112     /* FIXME:  If Windows truly always prevents truncating or deleting a
   36113     ** file while a mapping is held, then the following winUnmapfile() call
   36114     ** is unnecessary can can be omitted - potentially improving
   36115     ** performance.  */
   36116     winUnmapfile(pFd);
   36117   }
   36118 
   36119   assert( pFd->nFetchOut>=0 );
   36120 #endif
   36121 
   36122   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   36123            osGetCurrentProcessId(), fd));
   36124   return SQLITE_OK;
   36125 }
   36126 
   36127 /*
   36128 ** Here ends the implementation of all sqlite3_file methods.
   36129 **
   36130 ********************** End sqlite3_file Methods *******************************
   36131 ******************************************************************************/
   36132 
   36133 /*
   36134 ** This vector defines all the methods that can operate on an
   36135 ** sqlite3_file for win32.
   36136 */
   36137 static const sqlite3_io_methods winIoMethod = {
   36138   3,                              /* iVersion */
   36139   winClose,                       /* xClose */
   36140   winRead,                        /* xRead */
   36141   winWrite,                       /* xWrite */
   36142   winTruncate,                    /* xTruncate */
   36143   winSync,                        /* xSync */
   36144   winFileSize,                    /* xFileSize */
   36145   winLock,                        /* xLock */
   36146   winUnlock,                      /* xUnlock */
   36147   winCheckReservedLock,           /* xCheckReservedLock */
   36148   winFileControl,                 /* xFileControl */
   36149   winSectorSize,                  /* xSectorSize */
   36150   winDeviceCharacteristics,       /* xDeviceCharacteristics */
   36151   winShmMap,                      /* xShmMap */
   36152   winShmLock,                     /* xShmLock */
   36153   winShmBarrier,                  /* xShmBarrier */
   36154   winShmUnmap,                    /* xShmUnmap */
   36155   winFetch,                       /* xFetch */
   36156   winUnfetch                      /* xUnfetch */
   36157 };
   36158 
   36159 /****************************************************************************
   36160 **************************** sqlite3_vfs methods ****************************
   36161 **
   36162 ** This division contains the implementation of methods on the
   36163 ** sqlite3_vfs object.
   36164 */
   36165 
   36166 #if defined(__CYGWIN__)
   36167 /*
   36168 ** Convert a filename from whatever the underlying operating system
   36169 ** supports for filenames into UTF-8.  Space to hold the result is
   36170 ** obtained from malloc and must be freed by the calling function.
   36171 */
   36172 static char *winConvertToUtf8Filename(const void *zFilename){
   36173   char *zConverted = 0;
   36174   if( osIsNT() ){
   36175     zConverted = winUnicodeToUtf8(zFilename);
   36176   }
   36177 #ifdef SQLITE_WIN32_HAS_ANSI
   36178   else{
   36179     zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
   36180   }
   36181 #endif
   36182   /* caller will handle out of memory */
   36183   return zConverted;
   36184 }
   36185 #endif
   36186 
   36187 /*
   36188 ** Convert a UTF-8 filename into whatever form the underlying
   36189 ** operating system wants filenames in.  Space to hold the result
   36190 ** is obtained from malloc and must be freed by the calling
   36191 ** function.
   36192 */
   36193 static void *winConvertFromUtf8Filename(const char *zFilename){
   36194   void *zConverted = 0;
   36195   if( osIsNT() ){
   36196     zConverted = winUtf8ToUnicode(zFilename);
   36197   }
   36198 #ifdef SQLITE_WIN32_HAS_ANSI
   36199   else{
   36200     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
   36201   }
   36202 #endif
   36203   /* caller will handle out of memory */
   36204   return zConverted;
   36205 }
   36206 
   36207 /*
   36208 ** This function returns non-zero if the specified UTF-8 string buffer
   36209 ** ends with a directory separator character or one was successfully
   36210 ** added to it.
   36211 */
   36212 static int winMakeEndInDirSep(int nBuf, char *zBuf){
   36213   if( zBuf ){
   36214     int nLen = sqlite3Strlen30(zBuf);
   36215     if( nLen>0 ){
   36216       if( winIsDirSep(zBuf[nLen-1]) ){
   36217         return 1;
   36218       }else if( nLen+1<nBuf ){
   36219         zBuf[nLen] = winGetDirSep();
   36220         zBuf[nLen+1] = '\0';
   36221         return 1;
   36222       }
   36223     }
   36224   }
   36225   return 0;
   36226 }
   36227 
   36228 /*
   36229 ** Create a temporary file name and store the resulting pointer into pzBuf.
   36230 ** The pointer returned in pzBuf must be freed via sqlite3_free().
   36231 */
   36232 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
   36233   static char zChars[] =
   36234     "abcdefghijklmnopqrstuvwxyz"
   36235     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   36236     "0123456789";
   36237   size_t i, j;
   36238   int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
   36239   int nMax, nBuf, nDir, nLen;
   36240   char *zBuf;
   36241 
   36242   /* It's odd to simulate an io-error here, but really this is just
   36243   ** using the io-error infrastructure to test that SQLite handles this
   36244   ** function failing.
   36245   */
   36246   SimulateIOError( return SQLITE_IOERR );
   36247 
   36248   /* Allocate a temporary buffer to store the fully qualified file
   36249   ** name for the temporary file.  If this fails, we cannot continue.
   36250   */
   36251   nMax = pVfs->mxPathname; nBuf = nMax + 2;
   36252   zBuf = sqlite3MallocZero( nBuf );
   36253   if( !zBuf ){
   36254     OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36255     return SQLITE_IOERR_NOMEM;
   36256   }
   36257 
   36258   /* Figure out the effective temporary directory.  First, check if one
   36259   ** has been explicitly set by the application; otherwise, use the one
   36260   ** configured by the operating system.
   36261   */
   36262   nDir = nMax - (nPre + 15);
   36263   assert( nDir>0 );
   36264   if( sqlite3_temp_directory ){
   36265     int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
   36266     if( nDirLen>0 ){
   36267       if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
   36268         nDirLen++;
   36269       }
   36270       if( nDirLen>nDir ){
   36271         sqlite3_free(zBuf);
   36272         OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   36273         return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
   36274       }
   36275       sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
   36276     }
   36277   }
   36278 #if defined(__CYGWIN__)
   36279   else{
   36280     static const char *azDirs[] = {
   36281        0, /* getenv("SQLITE_TMPDIR") */
   36282        0, /* getenv("TMPDIR") */
   36283        0, /* getenv("TMP") */
   36284        0, /* getenv("TEMP") */
   36285        0, /* getenv("USERPROFILE") */
   36286        "/var/tmp",
   36287        "/usr/tmp",
   36288        "/tmp",
   36289        ".",
   36290        0        /* List terminator */
   36291     };
   36292     unsigned int i;
   36293     const char *zDir = 0;
   36294 
   36295     if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
   36296     if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   36297     if( !azDirs[2] ) azDirs[2] = getenv("TMP");
   36298     if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
   36299     if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
   36300     for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   36301       void *zConverted;
   36302       if( zDir==0 ) continue;
   36303       /* If the path starts with a drive letter followed by the colon
   36304       ** character, assume it is already a native Win32 path; otherwise,
   36305       ** it must be converted to a native Win32 path via the Cygwin API
   36306       ** prior to using it.
   36307       */
   36308       if( winIsDriveLetterAndColon(zDir) ){
   36309         zConverted = winConvertFromUtf8Filename(zDir);
   36310         if( !zConverted ){
   36311           sqlite3_free(zBuf);
   36312           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36313           return SQLITE_IOERR_NOMEM;
   36314         }
   36315         if( winIsDir(zConverted) ){
   36316           sqlite3_snprintf(nMax, zBuf, "%s", zDir);
   36317           sqlite3_free(zConverted);
   36318           break;
   36319         }
   36320         sqlite3_free(zConverted);
   36321       }else{
   36322         zConverted = sqlite3MallocZero( nMax+1 );
   36323         if( !zConverted ){
   36324           sqlite3_free(zBuf);
   36325           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36326           return SQLITE_IOERR_NOMEM;
   36327         }
   36328         if( cygwin_conv_path(
   36329                 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
   36330                 zConverted, nMax+1)<0 ){
   36331           sqlite3_free(zConverted);
   36332           sqlite3_free(zBuf);
   36333           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
   36334           return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
   36335                              "winGetTempname2", zDir);
   36336         }
   36337         if( winIsDir(zConverted) ){
   36338           /* At this point, we know the candidate directory exists and should
   36339           ** be used.  However, we may need to convert the string containing
   36340           ** its name into UTF-8 (i.e. if it is UTF-16 right now).
   36341           */
   36342           char *zUtf8 = winConvertToUtf8Filename(zConverted);
   36343           if( !zUtf8 ){
   36344             sqlite3_free(zConverted);
   36345             sqlite3_free(zBuf);
   36346             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36347             return SQLITE_IOERR_NOMEM;
   36348           }
   36349           sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
   36350           sqlite3_free(zUtf8);
   36351           sqlite3_free(zConverted);
   36352           break;
   36353         }
   36354         sqlite3_free(zConverted);
   36355       }
   36356     }
   36357   }
   36358 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
   36359   else if( osIsNT() ){
   36360     char *zMulti;
   36361     LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
   36362     if( !zWidePath ){
   36363       sqlite3_free(zBuf);
   36364       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36365       return SQLITE_IOERR_NOMEM;
   36366     }
   36367     if( osGetTempPathW(nMax, zWidePath)==0 ){
   36368       sqlite3_free(zWidePath);
   36369       sqlite3_free(zBuf);
   36370       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
   36371       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
   36372                          "winGetTempname2", 0);
   36373     }
   36374     zMulti = winUnicodeToUtf8(zWidePath);
   36375     if( zMulti ){
   36376       sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
   36377       sqlite3_free(zMulti);
   36378       sqlite3_free(zWidePath);
   36379     }else{
   36380       sqlite3_free(zWidePath);
   36381       sqlite3_free(zBuf);
   36382       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36383       return SQLITE_IOERR_NOMEM;
   36384     }
   36385   }
   36386 #ifdef SQLITE_WIN32_HAS_ANSI
   36387   else{
   36388     char *zUtf8;
   36389     char *zMbcsPath = sqlite3MallocZero( nMax );
   36390     if( !zMbcsPath ){
   36391       sqlite3_free(zBuf);
   36392       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36393       return SQLITE_IOERR_NOMEM;
   36394     }
   36395     if( osGetTempPathA(nMax, zMbcsPath)==0 ){
   36396       sqlite3_free(zBuf);
   36397       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
   36398       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
   36399                          "winGetTempname3", 0);
   36400     }
   36401     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
   36402     if( zUtf8 ){
   36403       sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
   36404       sqlite3_free(zUtf8);
   36405     }else{
   36406       sqlite3_free(zBuf);
   36407       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   36408       return SQLITE_IOERR_NOMEM;
   36409     }
   36410   }
   36411 #endif /* SQLITE_WIN32_HAS_ANSI */
   36412 #endif /* !SQLITE_OS_WINRT */
   36413 
   36414   /*
   36415   ** Check to make sure the temporary directory ends with an appropriate
   36416   ** separator.  If it does not and there is not enough space left to add
   36417   ** one, fail.
   36418   */
   36419   if( !winMakeEndInDirSep(nDir+1, zBuf) ){
   36420     sqlite3_free(zBuf);
   36421     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   36422     return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
   36423   }
   36424 
   36425   /*
   36426   ** Check that the output buffer is large enough for the temporary file
   36427   ** name in the following format:
   36428   **
   36429   **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
   36430   **
   36431   ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
   36432   ** account for the space used by the 15 character random suffix and the
   36433   ** two trailing NUL characters.  The final directory separator character
   36434   ** has already added if it was not already present.
   36435   */
   36436   nLen = sqlite3Strlen30(zBuf);
   36437   if( (nLen + nPre + 17) > nBuf ){
   36438     sqlite3_free(zBuf);
   36439     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   36440     return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
   36441   }
   36442 
   36443   sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
   36444 
   36445   j = sqlite3Strlen30(zBuf);
   36446   sqlite3_randomness(15, &zBuf[j]);
   36447   for(i=0; i<15; i++, j++){
   36448     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   36449   }
   36450   zBuf[j] = 0;
   36451   zBuf[j+1] = 0;
   36452   *pzBuf = zBuf;
   36453 
   36454   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
   36455   return SQLITE_OK;
   36456 }
   36457 
   36458 /*
   36459 ** Return TRUE if the named file is really a directory.  Return false if
   36460 ** it is something other than a directory, or if there is any kind of memory
   36461 ** allocation failure.
   36462 */
   36463 static int winIsDir(const void *zConverted){
   36464   DWORD attr;
   36465   int rc = 0;
   36466   DWORD lastErrno;
   36467 
   36468   if( osIsNT() ){
   36469     int cnt = 0;
   36470     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   36471     memset(&sAttrData, 0, sizeof(sAttrData));
   36472     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
   36473                              GetFileExInfoStandard,
   36474                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
   36475     if( !rc ){
   36476       return 0; /* Invalid name? */
   36477     }
   36478     attr = sAttrData.dwFileAttributes;
   36479 #if SQLITE_OS_WINCE==0
   36480   }else{
   36481     attr = osGetFileAttributesA((char*)zConverted);
   36482 #endif
   36483   }
   36484   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
   36485 }
   36486 
   36487 /*
   36488 ** Open a file.
   36489 */
   36490 static int winOpen(
   36491   sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
   36492   const char *zName,        /* Name of the file (UTF-8) */
   36493   sqlite3_file *id,         /* Write the SQLite file handle here */
   36494   int flags,                /* Open mode flags */
   36495   int *pOutFlags            /* Status return flags */
   36496 ){
   36497   HANDLE h;
   36498   DWORD lastErrno = 0;
   36499   DWORD dwDesiredAccess;
   36500   DWORD dwShareMode;
   36501   DWORD dwCreationDisposition;
   36502   DWORD dwFlagsAndAttributes = 0;
   36503 #if SQLITE_OS_WINCE
   36504   int isTemp = 0;
   36505 #endif
   36506   winFile *pFile = (winFile*)id;
   36507   void *zConverted;              /* Filename in OS encoding */
   36508   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
   36509   int cnt = 0;
   36510 
   36511   /* If argument zPath is a NULL pointer, this function is required to open
   36512   ** a temporary file. Use this buffer to store the file name in.
   36513   */
   36514   char *zTmpname = 0; /* For temporary filename, if necessary. */
   36515 
   36516   int rc = SQLITE_OK;            /* Function Return Code */
   36517 #if !defined(NDEBUG) || SQLITE_OS_WINCE
   36518   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   36519 #endif
   36520 
   36521   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   36522   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   36523   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   36524   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   36525   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   36526 
   36527 #ifndef NDEBUG
   36528   int isOpenJournal = (isCreate && (
   36529         eType==SQLITE_OPEN_MASTER_JOURNAL
   36530      || eType==SQLITE_OPEN_MAIN_JOURNAL
   36531      || eType==SQLITE_OPEN_WAL
   36532   ));
   36533 #endif
   36534 
   36535   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
   36536            zUtf8Name, id, flags, pOutFlags));
   36537 
   36538   /* Check the following statements are true:
   36539   **
   36540   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   36541   **   (b) if CREATE is set, then READWRITE must also be set, and
   36542   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   36543   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   36544   */
   36545   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   36546   assert(isCreate==0 || isReadWrite);
   36547   assert(isExclusive==0 || isCreate);
   36548   assert(isDelete==0 || isCreate);
   36549 
   36550   /* The main DB, main journal, WAL file and master journal are never
   36551   ** automatically deleted. Nor are they ever temporary files.  */
   36552   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   36553   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   36554   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   36555   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   36556 
   36557   /* Assert that the upper layer has set one of the "file-type" flags. */
   36558   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   36559        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   36560        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   36561        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   36562   );
   36563 
   36564   assert( pFile!=0 );
   36565   memset(pFile, 0, sizeof(winFile));
   36566   pFile->h = INVALID_HANDLE_VALUE;
   36567 
   36568 #if SQLITE_OS_WINRT
   36569   if( !zUtf8Name && !sqlite3_temp_directory ){
   36570     sqlite3_log(SQLITE_ERROR,
   36571         "sqlite3_temp_directory variable should be set for WinRT");
   36572   }
   36573 #endif
   36574 
   36575   /* If the second argument to this function is NULL, generate a
   36576   ** temporary file name to use
   36577   */
   36578   if( !zUtf8Name ){
   36579     assert( isDelete && !isOpenJournal );
   36580     rc = winGetTempname(pVfs, &zTmpname);
   36581     if( rc!=SQLITE_OK ){
   36582       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
   36583       return rc;
   36584     }
   36585     zUtf8Name = zTmpname;
   36586   }
   36587 
   36588   /* Database filenames are double-zero terminated if they are not
   36589   ** URIs with parameters.  Hence, they can always be passed into
   36590   ** sqlite3_uri_parameter().
   36591   */
   36592   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
   36593        zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
   36594 
   36595   /* Convert the filename to the system encoding. */
   36596   zConverted = winConvertFromUtf8Filename(zUtf8Name);
   36597   if( zConverted==0 ){
   36598     sqlite3_free(zTmpname);
   36599     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
   36600     return SQLITE_IOERR_NOMEM;
   36601   }
   36602 
   36603   if( winIsDir(zConverted) ){
   36604     sqlite3_free(zConverted);
   36605     sqlite3_free(zTmpname);
   36606     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
   36607     return SQLITE_CANTOPEN_ISDIR;
   36608   }
   36609 
   36610   if( isReadWrite ){
   36611     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
   36612   }else{
   36613     dwDesiredAccess = GENERIC_READ;
   36614   }
   36615 
   36616   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
   36617   ** created. SQLite doesn't use it to indicate "exclusive access"
   36618   ** as it is usually understood.
   36619   */
   36620   if( isExclusive ){
   36621     /* Creates a new file, only if it does not already exist. */
   36622     /* If the file exists, it fails. */
   36623     dwCreationDisposition = CREATE_NEW;
   36624   }else if( isCreate ){
   36625     /* Open existing file, or create if it doesn't exist */
   36626     dwCreationDisposition = OPEN_ALWAYS;
   36627   }else{
   36628     /* Opens a file, only if it exists. */
   36629     dwCreationDisposition = OPEN_EXISTING;
   36630   }
   36631 
   36632   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
   36633 
   36634   if( isDelete ){
   36635 #if SQLITE_OS_WINCE
   36636     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
   36637     isTemp = 1;
   36638 #else
   36639     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
   36640                                | FILE_ATTRIBUTE_HIDDEN
   36641                                | FILE_FLAG_DELETE_ON_CLOSE;
   36642 #endif
   36643   }else{
   36644     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
   36645   }
   36646   /* Reports from the internet are that performance is always
   36647   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
   36648 #if SQLITE_OS_WINCE
   36649   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
   36650 #endif
   36651 
   36652   if( osIsNT() ){
   36653 #if SQLITE_OS_WINRT
   36654     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
   36655     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
   36656     extendedParameters.dwFileAttributes =
   36657             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
   36658     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
   36659     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
   36660     extendedParameters.lpSecurityAttributes = NULL;
   36661     extendedParameters.hTemplateFile = NULL;
   36662     while( (h = osCreateFile2((LPCWSTR)zConverted,
   36663                               dwDesiredAccess,
   36664                               dwShareMode,
   36665                               dwCreationDisposition,
   36666                               &extendedParameters))==INVALID_HANDLE_VALUE &&
   36667                               winRetryIoerr(&cnt, &lastErrno) ){
   36668                /* Noop */
   36669     }
   36670 #else
   36671     while( (h = osCreateFileW((LPCWSTR)zConverted,
   36672                               dwDesiredAccess,
   36673                               dwShareMode, NULL,
   36674                               dwCreationDisposition,
   36675                               dwFlagsAndAttributes,
   36676                               NULL))==INVALID_HANDLE_VALUE &&
   36677                               winRetryIoerr(&cnt, &lastErrno) ){
   36678                /* Noop */
   36679     }
   36680 #endif
   36681   }
   36682 #ifdef SQLITE_WIN32_HAS_ANSI
   36683   else{
   36684     while( (h = osCreateFileA((LPCSTR)zConverted,
   36685                               dwDesiredAccess,
   36686                               dwShareMode, NULL,
   36687                               dwCreationDisposition,
   36688                               dwFlagsAndAttributes,
   36689                               NULL))==INVALID_HANDLE_VALUE &&
   36690                               winRetryIoerr(&cnt, &lastErrno) ){
   36691                /* Noop */
   36692     }
   36693   }
   36694 #endif
   36695   winLogIoerr(cnt);
   36696 
   36697   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
   36698            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
   36699 
   36700   if( h==INVALID_HANDLE_VALUE ){
   36701     pFile->lastErrno = lastErrno;
   36702     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
   36703     sqlite3_free(zConverted);
   36704     sqlite3_free(zTmpname);
   36705     if( isReadWrite && !isExclusive ){
   36706       return winOpen(pVfs, zName, id,
   36707          ((flags|SQLITE_OPEN_READONLY) &
   36708                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
   36709          pOutFlags);
   36710     }else{
   36711       return SQLITE_CANTOPEN_BKPT;
   36712     }
   36713   }
   36714 
   36715   if( pOutFlags ){
   36716     if( isReadWrite ){
   36717       *pOutFlags = SQLITE_OPEN_READWRITE;
   36718     }else{
   36719       *pOutFlags = SQLITE_OPEN_READONLY;
   36720     }
   36721   }
   36722 
   36723   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
   36724            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
   36725            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
   36726 
   36727 #if SQLITE_OS_WINCE
   36728   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
   36729        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
   36730   ){
   36731     osCloseHandle(h);
   36732     sqlite3_free(zConverted);
   36733     sqlite3_free(zTmpname);
   36734     OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
   36735     return rc;
   36736   }
   36737   if( isTemp ){
   36738     pFile->zDeleteOnClose = zConverted;
   36739   }else
   36740 #endif
   36741   {
   36742     sqlite3_free(zConverted);
   36743   }
   36744 
   36745   sqlite3_free(zTmpname);
   36746   pFile->pMethod = &winIoMethod;
   36747   pFile->pVfs = pVfs;
   36748   pFile->h = h;
   36749   if( isReadonly ){
   36750     pFile->ctrlFlags |= WINFILE_RDONLY;
   36751   }
   36752   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   36753     pFile->ctrlFlags |= WINFILE_PSOW;
   36754   }
   36755   pFile->lastErrno = NO_ERROR;
   36756   pFile->zPath = zName;
   36757 #if SQLITE_MAX_MMAP_SIZE>0
   36758   pFile->hMap = NULL;
   36759   pFile->pMapRegion = 0;
   36760   pFile->mmapSize = 0;
   36761   pFile->mmapSizeActual = 0;
   36762   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
   36763 #endif
   36764 
   36765   OpenCounter(+1);
   36766   return rc;
   36767 }
   36768 
   36769 /*
   36770 ** Delete the named file.
   36771 **
   36772 ** Note that Windows does not allow a file to be deleted if some other
   36773 ** process has it open.  Sometimes a virus scanner or indexing program
   36774 ** will open a journal file shortly after it is created in order to do
   36775 ** whatever it does.  While this other process is holding the
   36776 ** file open, we will be unable to delete it.  To work around this
   36777 ** problem, we delay 100 milliseconds and try to delete again.  Up
   36778 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
   36779 ** up and returning an error.
   36780 */
   36781 static int winDelete(
   36782   sqlite3_vfs *pVfs,          /* Not used on win32 */
   36783   const char *zFilename,      /* Name of file to delete */
   36784   int syncDir                 /* Not used on win32 */
   36785 ){
   36786   int cnt = 0;
   36787   int rc;
   36788   DWORD attr;
   36789   DWORD lastErrno = 0;
   36790   void *zConverted;
   36791   UNUSED_PARAMETER(pVfs);
   36792   UNUSED_PARAMETER(syncDir);
   36793 
   36794   SimulateIOError(return SQLITE_IOERR_DELETE);
   36795   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
   36796 
   36797   zConverted = winConvertFromUtf8Filename(zFilename);
   36798   if( zConverted==0 ){
   36799     OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
   36800     return SQLITE_IOERR_NOMEM;
   36801   }
   36802   if( osIsNT() ){
   36803     do {
   36804 #if SQLITE_OS_WINRT
   36805       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   36806       memset(&sAttrData, 0, sizeof(sAttrData));
   36807       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
   36808                                   &sAttrData) ){
   36809         attr = sAttrData.dwFileAttributes;
   36810       }else{
   36811         lastErrno = osGetLastError();
   36812         if( lastErrno==ERROR_FILE_NOT_FOUND
   36813          || lastErrno==ERROR_PATH_NOT_FOUND ){
   36814           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   36815         }else{
   36816           rc = SQLITE_ERROR;
   36817         }
   36818         break;
   36819       }
   36820 #else
   36821       attr = osGetFileAttributesW(zConverted);
   36822 #endif
   36823       if ( attr==INVALID_FILE_ATTRIBUTES ){
   36824         lastErrno = osGetLastError();
   36825         if( lastErrno==ERROR_FILE_NOT_FOUND
   36826          || lastErrno==ERROR_PATH_NOT_FOUND ){
   36827           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   36828         }else{
   36829           rc = SQLITE_ERROR;
   36830         }
   36831         break;
   36832       }
   36833       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
   36834         rc = SQLITE_ERROR; /* Files only. */
   36835         break;
   36836       }
   36837       if ( osDeleteFileW(zConverted) ){
   36838         rc = SQLITE_OK; /* Deleted OK. */
   36839         break;
   36840       }
   36841       if ( !winRetryIoerr(&cnt, &lastErrno) ){
   36842         rc = SQLITE_ERROR; /* No more retries. */
   36843         break;
   36844       }
   36845     } while(1);
   36846   }
   36847 #ifdef SQLITE_WIN32_HAS_ANSI
   36848   else{
   36849     do {
   36850       attr = osGetFileAttributesA(zConverted);
   36851       if ( attr==INVALID_FILE_ATTRIBUTES ){
   36852         lastErrno = osGetLastError();
   36853         if( lastErrno==ERROR_FILE_NOT_FOUND
   36854          || lastErrno==ERROR_PATH_NOT_FOUND ){
   36855           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   36856         }else{
   36857           rc = SQLITE_ERROR;
   36858         }
   36859         break;
   36860       }
   36861       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
   36862         rc = SQLITE_ERROR; /* Files only. */
   36863         break;
   36864       }
   36865       if ( osDeleteFileA(zConverted) ){
   36866         rc = SQLITE_OK; /* Deleted OK. */
   36867         break;
   36868       }
   36869       if ( !winRetryIoerr(&cnt, &lastErrno) ){
   36870         rc = SQLITE_ERROR; /* No more retries. */
   36871         break;
   36872       }
   36873     } while(1);
   36874   }
   36875 #endif
   36876   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
   36877     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
   36878   }else{
   36879     winLogIoerr(cnt);
   36880   }
   36881   sqlite3_free(zConverted);
   36882   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
   36883   return rc;
   36884 }
   36885 
   36886 /*
   36887 ** Check the existence and status of a file.
   36888 */
   36889 static int winAccess(
   36890   sqlite3_vfs *pVfs,         /* Not used on win32 */
   36891   const char *zFilename,     /* Name of file to check */
   36892   int flags,                 /* Type of test to make on this file */
   36893   int *pResOut               /* OUT: Result */
   36894 ){
   36895   DWORD attr;
   36896   int rc = 0;
   36897   DWORD lastErrno = 0;
   36898   void *zConverted;
   36899   UNUSED_PARAMETER(pVfs);
   36900 
   36901   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   36902   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
   36903            zFilename, flags, pResOut));
   36904 
   36905   zConverted = winConvertFromUtf8Filename(zFilename);
   36906   if( zConverted==0 ){
   36907     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
   36908     return SQLITE_IOERR_NOMEM;
   36909   }
   36910   if( osIsNT() ){
   36911     int cnt = 0;
   36912     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   36913     memset(&sAttrData, 0, sizeof(sAttrData));
   36914     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
   36915                              GetFileExInfoStandard,
   36916                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
   36917     if( rc ){
   36918       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
   36919       ** as if it does not exist.
   36920       */
   36921       if(    flags==SQLITE_ACCESS_EXISTS
   36922           && sAttrData.nFileSizeHigh==0
   36923           && sAttrData.nFileSizeLow==0 ){
   36924         attr = INVALID_FILE_ATTRIBUTES;
   36925       }else{
   36926         attr = sAttrData.dwFileAttributes;
   36927       }
   36928     }else{
   36929       winLogIoerr(cnt);
   36930       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
   36931         sqlite3_free(zConverted);
   36932         return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
   36933                            zFilename);
   36934       }else{
   36935         attr = INVALID_FILE_ATTRIBUTES;
   36936       }
   36937     }
   36938   }
   36939 #ifdef SQLITE_WIN32_HAS_ANSI
   36940   else{
   36941     attr = osGetFileAttributesA((char*)zConverted);
   36942   }
   36943 #endif
   36944   sqlite3_free(zConverted);
   36945   switch( flags ){
   36946     case SQLITE_ACCESS_READ:
   36947     case SQLITE_ACCESS_EXISTS:
   36948       rc = attr!=INVALID_FILE_ATTRIBUTES;
   36949       break;
   36950     case SQLITE_ACCESS_READWRITE:
   36951       rc = attr!=INVALID_FILE_ATTRIBUTES &&
   36952              (attr & FILE_ATTRIBUTE_READONLY)==0;
   36953       break;
   36954     default:
   36955       assert(!"Invalid flags argument");
   36956   }
   36957   *pResOut = rc;
   36958   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
   36959            zFilename, pResOut, *pResOut));
   36960   return SQLITE_OK;
   36961 }
   36962 
   36963 /*
   36964 ** Returns non-zero if the specified path name starts with a drive letter
   36965 ** followed by a colon character.
   36966 */
   36967 static BOOL winIsDriveLetterAndColon(
   36968   const char *zPathname
   36969 ){
   36970   return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
   36971 }
   36972 
   36973 /*
   36974 ** Returns non-zero if the specified path name should be used verbatim.  If
   36975 ** non-zero is returned from this function, the calling function must simply
   36976 ** use the provided path name verbatim -OR- resolve it into a full path name
   36977 ** using the GetFullPathName Win32 API function (if available).
   36978 */
   36979 static BOOL winIsVerbatimPathname(
   36980   const char *zPathname
   36981 ){
   36982   /*
   36983   ** If the path name starts with a forward slash or a backslash, it is either
   36984   ** a legal UNC name, a volume relative path, or an absolute path name in the
   36985   ** "Unix" format on Windows.  There is no easy way to differentiate between
   36986   ** the final two cases; therefore, we return the safer return value of TRUE
   36987   ** so that callers of this function will simply use it verbatim.
   36988   */
   36989   if ( winIsDirSep(zPathname[0]) ){
   36990     return TRUE;
   36991   }
   36992 
   36993   /*
   36994   ** If the path name starts with a letter and a colon it is either a volume
   36995   ** relative path or an absolute path.  Callers of this function must not
   36996   ** attempt to treat it as a relative path name (i.e. they should simply use
   36997   ** it verbatim).
   36998   */
   36999   if ( winIsDriveLetterAndColon(zPathname) ){
   37000     return TRUE;
   37001   }
   37002 
   37003   /*
   37004   ** If we get to this point, the path name should almost certainly be a purely
   37005   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
   37006   */
   37007   return FALSE;
   37008 }
   37009 
   37010 /*
   37011 ** Turn a relative pathname into a full pathname.  Write the full
   37012 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
   37013 ** bytes in size.
   37014 */
   37015 static int winFullPathname(
   37016   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   37017   const char *zRelative,        /* Possibly relative input path */
   37018   int nFull,                    /* Size of output buffer in bytes */
   37019   char *zFull                   /* Output buffer */
   37020 ){
   37021 
   37022 #if defined(__CYGWIN__)
   37023   SimulateIOError( return SQLITE_ERROR );
   37024   UNUSED_PARAMETER(nFull);
   37025   assert( nFull>=pVfs->mxPathname );
   37026   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   37027     /*
   37028     ** NOTE: We are dealing with a relative path name and the data
   37029     **       directory has been set.  Therefore, use it as the basis
   37030     **       for converting the relative path name to an absolute
   37031     **       one by prepending the data directory and a slash.
   37032     */
   37033     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
   37034     if( !zOut ){
   37035       return SQLITE_IOERR_NOMEM;
   37036     }
   37037     if( cygwin_conv_path(
   37038             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
   37039             CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
   37040       sqlite3_free(zOut);
   37041       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
   37042                          "winFullPathname1", zRelative);
   37043     }else{
   37044       char *zUtf8 = winConvertToUtf8Filename(zOut);
   37045       if( !zUtf8 ){
   37046         sqlite3_free(zOut);
   37047         return SQLITE_IOERR_NOMEM;
   37048       }
   37049       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   37050                        sqlite3_data_directory, winGetDirSep(), zUtf8);
   37051       sqlite3_free(zUtf8);
   37052       sqlite3_free(zOut);
   37053     }
   37054   }else{
   37055     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
   37056     if( !zOut ){
   37057       return SQLITE_IOERR_NOMEM;
   37058     }
   37059     if( cygwin_conv_path(
   37060             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
   37061             zRelative, zOut, pVfs->mxPathname+1)<0 ){
   37062       sqlite3_free(zOut);
   37063       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
   37064                          "winFullPathname2", zRelative);
   37065     }else{
   37066       char *zUtf8 = winConvertToUtf8Filename(zOut);
   37067       if( !zUtf8 ){
   37068         sqlite3_free(zOut);
   37069         return SQLITE_IOERR_NOMEM;
   37070       }
   37071       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
   37072       sqlite3_free(zUtf8);
   37073       sqlite3_free(zOut);
   37074     }
   37075   }
   37076   return SQLITE_OK;
   37077 #endif
   37078 
   37079 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
   37080   SimulateIOError( return SQLITE_ERROR );
   37081   /* WinCE has no concept of a relative pathname, or so I am told. */
   37082   /* WinRT has no way to convert a relative path to an absolute one. */
   37083   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   37084     /*
   37085     ** NOTE: We are dealing with a relative path name and the data
   37086     **       directory has been set.  Therefore, use it as the basis
   37087     **       for converting the relative path name to an absolute
   37088     **       one by prepending the data directory and a backslash.
   37089     */
   37090     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   37091                      sqlite3_data_directory, winGetDirSep(), zRelative);
   37092   }else{
   37093     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
   37094   }
   37095   return SQLITE_OK;
   37096 #endif
   37097 
   37098 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
   37099   DWORD nByte;
   37100   void *zConverted;
   37101   char *zOut;
   37102 
   37103   /* If this path name begins with "/X:", where "X" is any alphabetic
   37104   ** character, discard the initial "/" from the pathname.
   37105   */
   37106   if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
   37107     zRelative++;
   37108   }
   37109 
   37110   /* It's odd to simulate an io-error here, but really this is just
   37111   ** using the io-error infrastructure to test that SQLite handles this
   37112   ** function failing. This function could fail if, for example, the
   37113   ** current working directory has been unlinked.
   37114   */
   37115   SimulateIOError( return SQLITE_ERROR );
   37116   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   37117     /*
   37118     ** NOTE: We are dealing with a relative path name and the data
   37119     **       directory has been set.  Therefore, use it as the basis
   37120     **       for converting the relative path name to an absolute
   37121     **       one by prepending the data directory and a backslash.
   37122     */
   37123     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   37124                      sqlite3_data_directory, winGetDirSep(), zRelative);
   37125     return SQLITE_OK;
   37126   }
   37127   zConverted = winConvertFromUtf8Filename(zRelative);
   37128   if( zConverted==0 ){
   37129     return SQLITE_IOERR_NOMEM;
   37130   }
   37131   if( osIsNT() ){
   37132     LPWSTR zTemp;
   37133     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
   37134     if( nByte==0 ){
   37135       sqlite3_free(zConverted);
   37136       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   37137                          "winFullPathname1", zRelative);
   37138     }
   37139     nByte += 3;
   37140     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
   37141     if( zTemp==0 ){
   37142       sqlite3_free(zConverted);
   37143       return SQLITE_IOERR_NOMEM;
   37144     }
   37145     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
   37146     if( nByte==0 ){
   37147       sqlite3_free(zConverted);
   37148       sqlite3_free(zTemp);
   37149       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   37150                          "winFullPathname2", zRelative);
   37151     }
   37152     sqlite3_free(zConverted);
   37153     zOut = winUnicodeToUtf8(zTemp);
   37154     sqlite3_free(zTemp);
   37155   }
   37156 #ifdef SQLITE_WIN32_HAS_ANSI
   37157   else{
   37158     char *zTemp;
   37159     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
   37160     if( nByte==0 ){
   37161       sqlite3_free(zConverted);
   37162       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   37163                          "winFullPathname3", zRelative);
   37164     }
   37165     nByte += 3;
   37166     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
   37167     if( zTemp==0 ){
   37168       sqlite3_free(zConverted);
   37169       return SQLITE_IOERR_NOMEM;
   37170     }
   37171     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
   37172     if( nByte==0 ){
   37173       sqlite3_free(zConverted);
   37174       sqlite3_free(zTemp);
   37175       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   37176                          "winFullPathname4", zRelative);
   37177     }
   37178     sqlite3_free(zConverted);
   37179     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   37180     sqlite3_free(zTemp);
   37181   }
   37182 #endif
   37183   if( zOut ){
   37184     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
   37185     sqlite3_free(zOut);
   37186     return SQLITE_OK;
   37187   }else{
   37188     return SQLITE_IOERR_NOMEM;
   37189   }
   37190 #endif
   37191 }
   37192 
   37193 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   37194 /*
   37195 ** Interfaces for opening a shared library, finding entry points
   37196 ** within the shared library, and closing the shared library.
   37197 */
   37198 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   37199   HANDLE h;
   37200 #if defined(__CYGWIN__)
   37201   int nFull = pVfs->mxPathname+1;
   37202   char *zFull = sqlite3MallocZero( nFull );
   37203   void *zConverted = 0;
   37204   if( zFull==0 ){
   37205     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   37206     return 0;
   37207   }
   37208   if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
   37209     sqlite3_free(zFull);
   37210     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   37211     return 0;
   37212   }
   37213   zConverted = winConvertFromUtf8Filename(zFull);
   37214   sqlite3_free(zFull);
   37215 #else
   37216   void *zConverted = winConvertFromUtf8Filename(zFilename);
   37217   UNUSED_PARAMETER(pVfs);
   37218 #endif
   37219   if( zConverted==0 ){
   37220     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   37221     return 0;
   37222   }
   37223   if( osIsNT() ){
   37224 #if SQLITE_OS_WINRT
   37225     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
   37226 #else
   37227     h = osLoadLibraryW((LPCWSTR)zConverted);
   37228 #endif
   37229   }
   37230 #ifdef SQLITE_WIN32_HAS_ANSI
   37231   else{
   37232     h = osLoadLibraryA((char*)zConverted);
   37233   }
   37234 #endif
   37235   OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
   37236   sqlite3_free(zConverted);
   37237   return (void*)h;
   37238 }
   37239 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   37240   UNUSED_PARAMETER(pVfs);
   37241   winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
   37242 }
   37243 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
   37244   FARPROC proc;
   37245   UNUSED_PARAMETER(pVfs);
   37246   proc = osGetProcAddressA((HANDLE)pH, zSym);
   37247   OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
   37248            (void*)pH, zSym, (void*)proc));
   37249   return (void(*)(void))proc;
   37250 }
   37251 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
   37252   UNUSED_PARAMETER(pVfs);
   37253   osFreeLibrary((HANDLE)pHandle);
   37254   OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
   37255 }
   37256 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   37257   #define winDlOpen  0
   37258   #define winDlError 0
   37259   #define winDlSym   0
   37260   #define winDlClose 0
   37261 #endif
   37262 
   37263 
   37264 /*
   37265 ** Write up to nBuf bytes of randomness into zBuf.
   37266 */
   37267 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   37268   int n = 0;
   37269   UNUSED_PARAMETER(pVfs);
   37270 #if defined(SQLITE_TEST)
   37271   n = nBuf;
   37272   memset(zBuf, 0, nBuf);
   37273 #else
   37274   if( sizeof(SYSTEMTIME)<=nBuf-n ){
   37275     SYSTEMTIME x;
   37276     osGetSystemTime(&x);
   37277     memcpy(&zBuf[n], &x, sizeof(x));
   37278     n += sizeof(x);
   37279   }
   37280   if( sizeof(DWORD)<=nBuf-n ){
   37281     DWORD pid = osGetCurrentProcessId();
   37282     memcpy(&zBuf[n], &pid, sizeof(pid));
   37283     n += sizeof(pid);
   37284   }
   37285 #if SQLITE_OS_WINRT
   37286   if( sizeof(ULONGLONG)<=nBuf-n ){
   37287     ULONGLONG cnt = osGetTickCount64();
   37288     memcpy(&zBuf[n], &cnt, sizeof(cnt));
   37289     n += sizeof(cnt);
   37290   }
   37291 #else
   37292   if( sizeof(DWORD)<=nBuf-n ){
   37293     DWORD cnt = osGetTickCount();
   37294     memcpy(&zBuf[n], &cnt, sizeof(cnt));
   37295     n += sizeof(cnt);
   37296   }
   37297 #endif
   37298   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
   37299     LARGE_INTEGER i;
   37300     osQueryPerformanceCounter(&i);
   37301     memcpy(&zBuf[n], &i, sizeof(i));
   37302     n += sizeof(i);
   37303   }
   37304 #endif
   37305   return n;
   37306 }
   37307 
   37308 
   37309 /*
   37310 ** Sleep for a little while.  Return the amount of time slept.
   37311 */
   37312 static int winSleep(sqlite3_vfs *pVfs, int microsec){
   37313   sqlite3_win32_sleep((microsec+999)/1000);
   37314   UNUSED_PARAMETER(pVfs);
   37315   return ((microsec+999)/1000)*1000;
   37316 }
   37317 
   37318 /*
   37319 ** The following variable, if set to a non-zero value, is interpreted as
   37320 ** the number of seconds since 1970 and is used to set the result of
   37321 ** sqlite3OsCurrentTime() during testing.
   37322 */
   37323 #ifdef SQLITE_TEST
   37324 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   37325 #endif
   37326 
   37327 /*
   37328 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   37329 ** the current time and date as a Julian Day number times 86_400_000.  In
   37330 ** other words, write into *piNow the number of milliseconds since the Julian
   37331 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   37332 ** proleptic Gregorian calendar.
   37333 **
   37334 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   37335 ** cannot be found.
   37336 */
   37337 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
   37338   /* FILETIME structure is a 64-bit value representing the number of
   37339      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
   37340   */
   37341   FILETIME ft;
   37342   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
   37343 #ifdef SQLITE_TEST
   37344   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   37345 #endif
   37346   /* 2^32 - to avoid use of LL and warnings in gcc */
   37347   static const sqlite3_int64 max32BitValue =
   37348       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
   37349       (sqlite3_int64)294967296;
   37350 
   37351 #if SQLITE_OS_WINCE
   37352   SYSTEMTIME time;
   37353   osGetSystemTime(&time);
   37354   /* if SystemTimeToFileTime() fails, it returns zero. */
   37355   if (!osSystemTimeToFileTime(&time,&ft)){
   37356     return SQLITE_ERROR;
   37357   }
   37358 #else
   37359   osGetSystemTimeAsFileTime( &ft );
   37360 #endif
   37361 
   37362   *piNow = winFiletimeEpoch +
   37363             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
   37364                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
   37365 
   37366 #ifdef SQLITE_TEST
   37367   if( sqlite3_current_time ){
   37368     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   37369   }
   37370 #endif
   37371   UNUSED_PARAMETER(pVfs);
   37372   return SQLITE_OK;
   37373 }
   37374 
   37375 /*
   37376 ** Find the current time (in Universal Coordinated Time).  Write the
   37377 ** current time and date as a Julian Day number into *prNow and
   37378 ** return 0.  Return 1 if the time and date cannot be found.
   37379 */
   37380 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
   37381   int rc;
   37382   sqlite3_int64 i;
   37383   rc = winCurrentTimeInt64(pVfs, &i);
   37384   if( !rc ){
   37385     *prNow = i/86400000.0;
   37386   }
   37387   return rc;
   37388 }
   37389 
   37390 /*
   37391 ** The idea is that this function works like a combination of
   37392 ** GetLastError() and FormatMessage() on Windows (or errno and
   37393 ** strerror_r() on Unix). After an error is returned by an OS
   37394 ** function, SQLite calls this function with zBuf pointing to
   37395 ** a buffer of nBuf bytes. The OS layer should populate the
   37396 ** buffer with a nul-terminated UTF-8 encoded error message
   37397 ** describing the last IO error to have occurred within the calling
   37398 ** thread.
   37399 **
   37400 ** If the error message is too large for the supplied buffer,
   37401 ** it should be truncated. The return value of xGetLastError
   37402 ** is zero if the error message fits in the buffer, or non-zero
   37403 ** otherwise (if the message was truncated). If non-zero is returned,
   37404 ** then it is not necessary to include the nul-terminator character
   37405 ** in the output buffer.
   37406 **
   37407 ** Not supplying an error message will have no adverse effect
   37408 ** on SQLite. It is fine to have an implementation that never
   37409 ** returns an error message:
   37410 **
   37411 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   37412 **     assert(zBuf[0]=='\0');
   37413 **     return 0;
   37414 **   }
   37415 **
   37416 ** However if an error message is supplied, it will be incorporated
   37417 ** by sqlite into the error message available to the user using
   37418 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
   37419 */
   37420 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   37421   UNUSED_PARAMETER(pVfs);
   37422   return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
   37423 }
   37424 
   37425 /*
   37426 ** Initialize and deinitialize the operating system interface.
   37427 */
   37428 SQLITE_API int sqlite3_os_init(void){
   37429   static sqlite3_vfs winVfs = {
   37430     3,                   /* iVersion */
   37431     sizeof(winFile),     /* szOsFile */
   37432     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
   37433     0,                   /* pNext */
   37434     "win32",             /* zName */
   37435     0,                   /* pAppData */
   37436     winOpen,             /* xOpen */
   37437     winDelete,           /* xDelete */
   37438     winAccess,           /* xAccess */
   37439     winFullPathname,     /* xFullPathname */
   37440     winDlOpen,           /* xDlOpen */
   37441     winDlError,          /* xDlError */
   37442     winDlSym,            /* xDlSym */
   37443     winDlClose,          /* xDlClose */
   37444     winRandomness,       /* xRandomness */
   37445     winSleep,            /* xSleep */
   37446     winCurrentTime,      /* xCurrentTime */
   37447     winGetLastError,     /* xGetLastError */
   37448     winCurrentTimeInt64, /* xCurrentTimeInt64 */
   37449     winSetSystemCall,    /* xSetSystemCall */
   37450     winGetSystemCall,    /* xGetSystemCall */
   37451     winNextSystemCall,   /* xNextSystemCall */
   37452   };
   37453 #if defined(SQLITE_WIN32_HAS_WIDE)
   37454   static sqlite3_vfs winLongPathVfs = {
   37455     3,                   /* iVersion */
   37456     sizeof(winFile),     /* szOsFile */
   37457     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
   37458     0,                   /* pNext */
   37459     "win32-longpath",    /* zName */
   37460     0,                   /* pAppData */
   37461     winOpen,             /* xOpen */
   37462     winDelete,           /* xDelete */
   37463     winAccess,           /* xAccess */
   37464     winFullPathname,     /* xFullPathname */
   37465     winDlOpen,           /* xDlOpen */
   37466     winDlError,          /* xDlError */
   37467     winDlSym,            /* xDlSym */
   37468     winDlClose,          /* xDlClose */
   37469     winRandomness,       /* xRandomness */
   37470     winSleep,            /* xSleep */
   37471     winCurrentTime,      /* xCurrentTime */
   37472     winGetLastError,     /* xGetLastError */
   37473     winCurrentTimeInt64, /* xCurrentTimeInt64 */
   37474     winSetSystemCall,    /* xSetSystemCall */
   37475     winGetSystemCall,    /* xGetSystemCall */
   37476     winNextSystemCall,   /* xNextSystemCall */
   37477   };
   37478 #endif
   37479 
   37480   /* Double-check that the aSyscall[] array has been constructed
   37481   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   37482   assert( ArraySize(aSyscall)==77 );
   37483 
   37484   /* get memory map allocation granularity */
   37485   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
   37486 #if SQLITE_OS_WINRT
   37487   osGetNativeSystemInfo(&winSysInfo);
   37488 #else
   37489   osGetSystemInfo(&winSysInfo);
   37490 #endif
   37491   assert( winSysInfo.dwAllocationGranularity>0 );
   37492   assert( winSysInfo.dwPageSize>0 );
   37493 
   37494   sqlite3_vfs_register(&winVfs, 1);
   37495 
   37496 #if defined(SQLITE_WIN32_HAS_WIDE)
   37497   sqlite3_vfs_register(&winLongPathVfs, 0);
   37498 #endif
   37499 
   37500   return SQLITE_OK;
   37501 }
   37502 
   37503 SQLITE_API int sqlite3_os_end(void){
   37504 #if SQLITE_OS_WINRT
   37505   if( sleepObj!=NULL ){
   37506     osCloseHandle(sleepObj);
   37507     sleepObj = NULL;
   37508   }
   37509 #endif
   37510   return SQLITE_OK;
   37511 }
   37512 
   37513 #endif /* SQLITE_OS_WIN */
   37514 
   37515 /************** End of os_win.c **********************************************/
   37516 /************** Begin file bitvec.c ******************************************/
   37517 /*
   37518 ** 2008 February 16
   37519 **
   37520 ** The author disclaims copyright to this source code.  In place of
   37521 ** a legal notice, here is a blessing:
   37522 **
   37523 **    May you do good and not evil.
   37524 **    May you find forgiveness for yourself and forgive others.
   37525 **    May you share freely, never taking more than you give.
   37526 **
   37527 *************************************************************************
   37528 ** This file implements an object that represents a fixed-length
   37529 ** bitmap.  Bits are numbered starting with 1.
   37530 **
   37531 ** A bitmap is used to record which pages of a database file have been
   37532 ** journalled during a transaction, or which pages have the "dont-write"
   37533 ** property.  Usually only a few pages are meet either condition.
   37534 ** So the bitmap is usually sparse and has low cardinality.
   37535 ** But sometimes (for example when during a DROP of a large table) most
   37536 ** or all of the pages in a database can get journalled.  In those cases,
   37537 ** the bitmap becomes dense with high cardinality.  The algorithm needs
   37538 ** to handle both cases well.
   37539 **
   37540 ** The size of the bitmap is fixed when the object is created.
   37541 **
   37542 ** All bits are clear when the bitmap is created.  Individual bits
   37543 ** may be set or cleared one at a time.
   37544 **
   37545 ** Test operations are about 100 times more common that set operations.
   37546 ** Clear operations are exceedingly rare.  There are usually between
   37547 ** 5 and 500 set operations per Bitvec object, though the number of sets can
   37548 ** sometimes grow into tens of thousands or larger.  The size of the
   37549 ** Bitvec object is the number of pages in the database file at the
   37550 ** start of a transaction, and is thus usually less than a few thousand,
   37551 ** but can be as large as 2 billion for a really big database.
   37552 */
   37553 
   37554 /* Size of the Bitvec structure in bytes. */
   37555 #define BITVEC_SZ        512
   37556 
   37557 /* Round the union size down to the nearest pointer boundary, since that's how
   37558 ** it will be aligned within the Bitvec struct. */
   37559 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
   37560 
   37561 /* Type of the array "element" for the bitmap representation.
   37562 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
   37563 ** Setting this to the "natural word" size of your CPU may improve
   37564 ** performance. */
   37565 #define BITVEC_TELEM     u8
   37566 /* Size, in bits, of the bitmap element. */
   37567 #define BITVEC_SZELEM    8
   37568 /* Number of elements in a bitmap array. */
   37569 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
   37570 /* Number of bits in the bitmap array. */
   37571 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
   37572 
   37573 /* Number of u32 values in hash table. */
   37574 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
   37575 /* Maximum number of entries in hash table before
   37576 ** sub-dividing and re-hashing. */
   37577 #define BITVEC_MXHASH    (BITVEC_NINT/2)
   37578 /* Hashing function for the aHash representation.
   37579 ** Empirical testing showed that the *37 multiplier
   37580 ** (an arbitrary prime)in the hash function provided
   37581 ** no fewer collisions than the no-op *1. */
   37582 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
   37583 
   37584 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
   37585 
   37586 
   37587 /*
   37588 ** A bitmap is an instance of the following structure.
   37589 **
   37590 ** This bitmap records the existence of zero or more bits
   37591 ** with values between 1 and iSize, inclusive.
   37592 **
   37593 ** There are three possible representations of the bitmap.
   37594 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
   37595 ** bitmap.  The least significant bit is bit 1.
   37596 **
   37597 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
   37598 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
   37599 **
   37600 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
   37601 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
   37602 ** handles up to iDivisor separate values of i.  apSub[0] holds
   37603 ** values between 1 and iDivisor.  apSub[1] holds values between
   37604 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
   37605 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
   37606 ** to hold deal with values between 1 and iDivisor.
   37607 */
   37608 struct Bitvec {
   37609   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
   37610   u32 nSet;       /* Number of bits that are set - only valid for aHash
   37611                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
   37612                   ** this would be 125. */
   37613   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
   37614                   /* Should >=0 for apSub element. */
   37615                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
   37616                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
   37617   union {
   37618     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
   37619     u32 aHash[BITVEC_NINT];      /* Hash table representation */
   37620     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
   37621   } u;
   37622 };
   37623 
   37624 /*
   37625 ** Create a new bitmap object able to handle bits between 0 and iSize,
   37626 ** inclusive.  Return a pointer to the new object.  Return NULL if
   37627 ** malloc fails.
   37628 */
   37629 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
   37630   Bitvec *p;
   37631   assert( sizeof(*p)==BITVEC_SZ );
   37632   p = sqlite3MallocZero( sizeof(*p) );
   37633   if( p ){
   37634     p->iSize = iSize;
   37635   }
   37636   return p;
   37637 }
   37638 
   37639 /*
   37640 ** Check to see if the i-th bit is set.  Return true or false.
   37641 ** If p is NULL (if the bitmap has not been created) or if
   37642 ** i is out of range, then return false.
   37643 */
   37644 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
   37645   if( p==0 ) return 0;
   37646   if( i>p->iSize || i==0 ) return 0;
   37647   i--;
   37648   while( p->iDivisor ){
   37649     u32 bin = i/p->iDivisor;
   37650     i = i%p->iDivisor;
   37651     p = p->u.apSub[bin];
   37652     if (!p) {
   37653       return 0;
   37654     }
   37655   }
   37656   if( p->iSize<=BITVEC_NBIT ){
   37657     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
   37658   } else{
   37659     u32 h = BITVEC_HASH(i++);
   37660     while( p->u.aHash[h] ){
   37661       if( p->u.aHash[h]==i ) return 1;
   37662       h = (h+1) % BITVEC_NINT;
   37663     }
   37664     return 0;
   37665   }
   37666 }
   37667 
   37668 /*
   37669 ** Set the i-th bit.  Return 0 on success and an error code if
   37670 ** anything goes wrong.
   37671 **
   37672 ** This routine might cause sub-bitmaps to be allocated.  Failing
   37673 ** to get the memory needed to hold the sub-bitmap is the only
   37674 ** that can go wrong with an insert, assuming p and i are valid.
   37675 **
   37676 ** The calling function must ensure that p is a valid Bitvec object
   37677 ** and that the value for "i" is within range of the Bitvec object.
   37678 ** Otherwise the behavior is undefined.
   37679 */
   37680 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
   37681   u32 h;
   37682   if( p==0 ) return SQLITE_OK;
   37683   assert( i>0 );
   37684   assert( i<=p->iSize );
   37685   i--;
   37686   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
   37687     u32 bin = i/p->iDivisor;
   37688     i = i%p->iDivisor;
   37689     if( p->u.apSub[bin]==0 ){
   37690       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
   37691       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
   37692     }
   37693     p = p->u.apSub[bin];
   37694   }
   37695   if( p->iSize<=BITVEC_NBIT ){
   37696     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
   37697     return SQLITE_OK;
   37698   }
   37699   h = BITVEC_HASH(i++);
   37700   /* if there wasn't a hash collision, and this doesn't */
   37701   /* completely fill the hash, then just add it without */
   37702   /* worring about sub-dividing and re-hashing. */
   37703   if( !p->u.aHash[h] ){
   37704     if (p->nSet<(BITVEC_NINT-1)) {
   37705       goto bitvec_set_end;
   37706     } else {
   37707       goto bitvec_set_rehash;
   37708     }
   37709   }
   37710   /* there was a collision, check to see if it's already */
   37711   /* in hash, if not, try to find a spot for it */
   37712   do {
   37713     if( p->u.aHash[h]==i ) return SQLITE_OK;
   37714     h++;
   37715     if( h>=BITVEC_NINT ) h = 0;
   37716   } while( p->u.aHash[h] );
   37717   /* we didn't find it in the hash.  h points to the first */
   37718   /* available free spot. check to see if this is going to */
   37719   /* make our hash too "full".  */
   37720 bitvec_set_rehash:
   37721   if( p->nSet>=BITVEC_MXHASH ){
   37722     unsigned int j;
   37723     int rc;
   37724     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
   37725     if( aiValues==0 ){
   37726       return SQLITE_NOMEM;
   37727     }else{
   37728       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   37729       memset(p->u.apSub, 0, sizeof(p->u.apSub));
   37730       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
   37731       rc = sqlite3BitvecSet(p, i);
   37732       for(j=0; j<BITVEC_NINT; j++){
   37733         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
   37734       }
   37735       sqlite3StackFree(0, aiValues);
   37736       return rc;
   37737     }
   37738   }
   37739 bitvec_set_end:
   37740   p->nSet++;
   37741   p->u.aHash[h] = i;
   37742   return SQLITE_OK;
   37743 }
   37744 
   37745 /*
   37746 ** Clear the i-th bit.
   37747 **
   37748 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
   37749 ** that BitvecClear can use to rebuilt its hash table.
   37750 */
   37751 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
   37752   if( p==0 ) return;
   37753   assert( i>0 );
   37754   i--;
   37755   while( p->iDivisor ){
   37756     u32 bin = i/p->iDivisor;
   37757     i = i%p->iDivisor;
   37758     p = p->u.apSub[bin];
   37759     if (!p) {
   37760       return;
   37761     }
   37762   }
   37763   if( p->iSize<=BITVEC_NBIT ){
   37764     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
   37765   }else{
   37766     unsigned int j;
   37767     u32 *aiValues = pBuf;
   37768     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   37769     memset(p->u.aHash, 0, sizeof(p->u.aHash));
   37770     p->nSet = 0;
   37771     for(j=0; j<BITVEC_NINT; j++){
   37772       if( aiValues[j] && aiValues[j]!=(i+1) ){
   37773         u32 h = BITVEC_HASH(aiValues[j]-1);
   37774         p->nSet++;
   37775         while( p->u.aHash[h] ){
   37776           h++;
   37777           if( h>=BITVEC_NINT ) h = 0;
   37778         }
   37779         p->u.aHash[h] = aiValues[j];
   37780       }
   37781     }
   37782   }
   37783 }
   37784 
   37785 /*
   37786 ** Destroy a bitmap object.  Reclaim all memory used.
   37787 */
   37788 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
   37789   if( p==0 ) return;
   37790   if( p->iDivisor ){
   37791     unsigned int i;
   37792     for(i=0; i<BITVEC_NPTR; i++){
   37793       sqlite3BitvecDestroy(p->u.apSub[i]);
   37794     }
   37795   }
   37796   sqlite3_free(p);
   37797 }
   37798 
   37799 /*
   37800 ** Return the value of the iSize parameter specified when Bitvec *p
   37801 ** was created.
   37802 */
   37803 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
   37804   return p->iSize;
   37805 }
   37806 
   37807 #ifndef SQLITE_OMIT_BUILTIN_TEST
   37808 /*
   37809 ** Let V[] be an array of unsigned characters sufficient to hold
   37810 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
   37811 ** Then the following macros can be used to set, clear, or test
   37812 ** individual bits within V.
   37813 */
   37814 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
   37815 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
   37816 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
   37817 
   37818 /*
   37819 ** This routine runs an extensive test of the Bitvec code.
   37820 **
   37821 ** The input is an array of integers that acts as a program
   37822 ** to test the Bitvec.  The integers are opcodes followed
   37823 ** by 0, 1, or 3 operands, depending on the opcode.  Another
   37824 ** opcode follows immediately after the last operand.
   37825 **
   37826 ** There are 6 opcodes numbered from 0 through 5.  0 is the
   37827 ** "halt" opcode and causes the test to end.
   37828 **
   37829 **    0          Halt and return the number of errors
   37830 **    1 N S X    Set N bits beginning with S and incrementing by X
   37831 **    2 N S X    Clear N bits beginning with S and incrementing by X
   37832 **    3 N        Set N randomly chosen bits
   37833 **    4 N        Clear N randomly chosen bits
   37834 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
   37835 **
   37836 ** The opcodes 1 through 4 perform set and clear operations are performed
   37837 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
   37838 ** Opcode 5 works on the linear array only, not on the Bitvec.
   37839 ** Opcode 5 is used to deliberately induce a fault in order to
   37840 ** confirm that error detection works.
   37841 **
   37842 ** At the conclusion of the test the linear array is compared
   37843 ** against the Bitvec object.  If there are any differences,
   37844 ** an error is returned.  If they are the same, zero is returned.
   37845 **
   37846 ** If a memory allocation error occurs, return -1.
   37847 */
   37848 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
   37849   Bitvec *pBitvec = 0;
   37850   unsigned char *pV = 0;
   37851   int rc = -1;
   37852   int i, nx, pc, op;
   37853   void *pTmpSpace;
   37854 
   37855   /* Allocate the Bitvec to be tested and a linear array of
   37856   ** bits to act as the reference */
   37857   pBitvec = sqlite3BitvecCreate( sz );
   37858   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
   37859   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
   37860   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
   37861 
   37862   /* NULL pBitvec tests */
   37863   sqlite3BitvecSet(0, 1);
   37864   sqlite3BitvecClear(0, 1, pTmpSpace);
   37865 
   37866   /* Run the program */
   37867   pc = 0;
   37868   while( (op = aOp[pc])!=0 ){
   37869     switch( op ){
   37870       case 1:
   37871       case 2:
   37872       case 5: {
   37873         nx = 4;
   37874         i = aOp[pc+2] - 1;
   37875         aOp[pc+2] += aOp[pc+3];
   37876         break;
   37877       }
   37878       case 3:
   37879       case 4:
   37880       default: {
   37881         nx = 2;
   37882         sqlite3_randomness(sizeof(i), &i);
   37883         break;
   37884       }
   37885     }
   37886     if( (--aOp[pc+1]) > 0 ) nx = 0;
   37887     pc += nx;
   37888     i = (i & 0x7fffffff)%sz;
   37889     if( (op & 1)!=0 ){
   37890       SETBIT(pV, (i+1));
   37891       if( op!=5 ){
   37892         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
   37893       }
   37894     }else{
   37895       CLEARBIT(pV, (i+1));
   37896       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
   37897     }
   37898   }
   37899 
   37900   /* Test to make sure the linear array exactly matches the
   37901   ** Bitvec object.  Start with the assumption that they do
   37902   ** match (rc==0).  Change rc to non-zero if a discrepancy
   37903   ** is found.
   37904   */
   37905   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
   37906           + sqlite3BitvecTest(pBitvec, 0)
   37907           + (sqlite3BitvecSize(pBitvec) - sz);
   37908   for(i=1; i<=sz; i++){
   37909     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
   37910       rc = i;
   37911       break;
   37912     }
   37913   }
   37914 
   37915   /* Free allocated structure */
   37916 bitvec_end:
   37917   sqlite3_free(pTmpSpace);
   37918   sqlite3_free(pV);
   37919   sqlite3BitvecDestroy(pBitvec);
   37920   return rc;
   37921 }
   37922 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   37923 
   37924 /************** End of bitvec.c **********************************************/
   37925 /************** Begin file pcache.c ******************************************/
   37926 /*
   37927 ** 2008 August 05
   37928 **
   37929 ** The author disclaims copyright to this source code.  In place of
   37930 ** a legal notice, here is a blessing:
   37931 **
   37932 **    May you do good and not evil.
   37933 **    May you find forgiveness for yourself and forgive others.
   37934 **    May you share freely, never taking more than you give.
   37935 **
   37936 *************************************************************************
   37937 ** This file implements that page cache.
   37938 */
   37939 
   37940 /*
   37941 ** A complete page cache is an instance of this structure.
   37942 */
   37943 struct PCache {
   37944   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
   37945   PgHdr *pSynced;                     /* Last synced page in dirty page list */
   37946   int nRef;                           /* Number of referenced pages */
   37947   int szCache;                        /* Configured cache size */
   37948   int szPage;                         /* Size of every page in this cache */
   37949   int szExtra;                        /* Size of extra space for each page */
   37950   u8 bPurgeable;                      /* True if pages are on backing store */
   37951   u8 eCreate;                         /* eCreate value for for xFetch() */
   37952   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
   37953   void *pStress;                      /* Argument to xStress */
   37954   sqlite3_pcache *pCache;             /* Pluggable cache module */
   37955   PgHdr *pPage1;                      /* Reference to page 1 */
   37956 };
   37957 
   37958 /*
   37959 ** Some of the assert() macros in this code are too expensive to run
   37960 ** even during normal debugging.  Use them only rarely on long-running
   37961 ** tests.  Enable the expensive asserts using the
   37962 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
   37963 */
   37964 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   37965 # define expensive_assert(X)  assert(X)
   37966 #else
   37967 # define expensive_assert(X)
   37968 #endif
   37969 
   37970 /********************************** Linked List Management ********************/
   37971 
   37972 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
   37973 /*
   37974 ** Check that the pCache->pSynced variable is set correctly. If it
   37975 ** is not, either fail an assert or return zero. Otherwise, return
   37976 ** non-zero. This is only used in debugging builds, as follows:
   37977 **
   37978 **   expensive_assert( pcacheCheckSynced(pCache) );
   37979 */
   37980 static int pcacheCheckSynced(PCache *pCache){
   37981   PgHdr *p;
   37982   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
   37983     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
   37984   }
   37985   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
   37986 }
   37987 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
   37988 
   37989 /*
   37990 ** Remove page pPage from the list of dirty pages.
   37991 */
   37992 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
   37993   PCache *p = pPage->pCache;
   37994 
   37995   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
   37996   assert( pPage->pDirtyPrev || pPage==p->pDirty );
   37997 
   37998   /* Update the PCache1.pSynced variable if necessary. */
   37999   if( p->pSynced==pPage ){
   38000     PgHdr *pSynced = pPage->pDirtyPrev;
   38001     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
   38002       pSynced = pSynced->pDirtyPrev;
   38003     }
   38004     p->pSynced = pSynced;
   38005   }
   38006 
   38007   if( pPage->pDirtyNext ){
   38008     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
   38009   }else{
   38010     assert( pPage==p->pDirtyTail );
   38011     p->pDirtyTail = pPage->pDirtyPrev;
   38012   }
   38013   if( pPage->pDirtyPrev ){
   38014     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
   38015   }else{
   38016     assert( pPage==p->pDirty );
   38017     p->pDirty = pPage->pDirtyNext;
   38018     if( p->pDirty==0 && p->bPurgeable ){
   38019       assert( p->eCreate==1 );
   38020       p->eCreate = 2;
   38021     }
   38022   }
   38023   pPage->pDirtyNext = 0;
   38024   pPage->pDirtyPrev = 0;
   38025 
   38026   expensive_assert( pcacheCheckSynced(p) );
   38027 }
   38028 
   38029 /*
   38030 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
   38031 ** pPage).
   38032 */
   38033 static void pcacheAddToDirtyList(PgHdr *pPage){
   38034   PCache *p = pPage->pCache;
   38035 
   38036   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
   38037 
   38038   pPage->pDirtyNext = p->pDirty;
   38039   if( pPage->pDirtyNext ){
   38040     assert( pPage->pDirtyNext->pDirtyPrev==0 );
   38041     pPage->pDirtyNext->pDirtyPrev = pPage;
   38042   }else if( p->bPurgeable ){
   38043     assert( p->eCreate==2 );
   38044     p->eCreate = 1;
   38045   }
   38046   p->pDirty = pPage;
   38047   if( !p->pDirtyTail ){
   38048     p->pDirtyTail = pPage;
   38049   }
   38050   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
   38051     p->pSynced = pPage;
   38052   }
   38053   expensive_assert( pcacheCheckSynced(p) );
   38054 }
   38055 
   38056 /*
   38057 ** Wrapper around the pluggable caches xUnpin method. If the cache is
   38058 ** being used for an in-memory database, this function is a no-op.
   38059 */
   38060 static void pcacheUnpin(PgHdr *p){
   38061   PCache *pCache = p->pCache;
   38062   if( pCache->bPurgeable ){
   38063     if( p->pgno==1 ){
   38064       pCache->pPage1 = 0;
   38065     }
   38066     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
   38067   }
   38068 }
   38069 
   38070 /*************************************************** General Interfaces ******
   38071 **
   38072 ** Initialize and shutdown the page cache subsystem. Neither of these
   38073 ** functions are threadsafe.
   38074 */
   38075 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
   38076   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   38077     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
   38078     ** built-in default page cache is used instead of the application defined
   38079     ** page cache. */
   38080     sqlite3PCacheSetDefault();
   38081   }
   38082   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
   38083 }
   38084 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
   38085   if( sqlite3GlobalConfig.pcache2.xShutdown ){
   38086     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
   38087     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
   38088   }
   38089 }
   38090 
   38091 /*
   38092 ** Return the size in bytes of a PCache object.
   38093 */
   38094 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
   38095 
   38096 /*
   38097 ** Create a new PCache object. Storage space to hold the object
   38098 ** has already been allocated and is passed in as the p pointer.
   38099 ** The caller discovers how much space needs to be allocated by
   38100 ** calling sqlite3PcacheSize().
   38101 */
   38102 SQLITE_PRIVATE void sqlite3PcacheOpen(
   38103   int szPage,                  /* Size of every page */
   38104   int szExtra,                 /* Extra space associated with each page */
   38105   int bPurgeable,              /* True if pages are on backing store */
   38106   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
   38107   void *pStress,               /* Argument to xStress */
   38108   PCache *p                    /* Preallocated space for the PCache */
   38109 ){
   38110   memset(p, 0, sizeof(PCache));
   38111   p->szPage = szPage;
   38112   p->szExtra = szExtra;
   38113   p->bPurgeable = bPurgeable;
   38114   p->eCreate = 2;
   38115   p->xStress = xStress;
   38116   p->pStress = pStress;
   38117   p->szCache = 100;
   38118 }
   38119 
   38120 /*
   38121 ** Change the page size for PCache object. The caller must ensure that there
   38122 ** are no outstanding page references when this function is called.
   38123 */
   38124 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
   38125   assert( pCache->nRef==0 && pCache->pDirty==0 );
   38126   if( pCache->pCache ){
   38127     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   38128     pCache->pCache = 0;
   38129     pCache->pPage1 = 0;
   38130   }
   38131   pCache->szPage = szPage;
   38132 }
   38133 
   38134 /*
   38135 ** Compute the number of pages of cache requested.
   38136 */
   38137 static int numberOfCachePages(PCache *p){
   38138   if( p->szCache>=0 ){
   38139     return p->szCache;
   38140   }else{
   38141     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
   38142   }
   38143 }
   38144 
   38145 /*
   38146 ** Try to obtain a page from the cache.
   38147 */
   38148 SQLITE_PRIVATE int sqlite3PcacheFetch(
   38149   PCache *pCache,       /* Obtain the page from this cache */
   38150   Pgno pgno,            /* Page number to obtain */
   38151   int createFlag,       /* If true, create page if it does not exist already */
   38152   PgHdr **ppPage        /* Write the page here */
   38153 ){
   38154   sqlite3_pcache_page *pPage;
   38155   PgHdr *pPgHdr = 0;
   38156   int eCreate;
   38157 
   38158   assert( pCache!=0 );
   38159   assert( createFlag==1 || createFlag==0 );
   38160   assert( pgno>0 );
   38161 
   38162   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
   38163   ** allocate it now.
   38164   */
   38165   if( !pCache->pCache ){
   38166     sqlite3_pcache *p;
   38167     if( !createFlag ){
   38168       *ppPage = 0;
   38169       return SQLITE_OK;
   38170     }
   38171     p = sqlite3GlobalConfig.pcache2.xCreate(
   38172         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
   38173     );
   38174     if( !p ){
   38175       return SQLITE_NOMEM;
   38176     }
   38177     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
   38178     pCache->pCache = p;
   38179   }
   38180 
   38181   /* eCreate defines what to do if the page does not exist.
   38182   **    0     Do not allocate a new page.  (createFlag==0)
   38183   **    1     Allocate a new page if doing so is inexpensive.
   38184   **          (createFlag==1 AND bPurgeable AND pDirty)
   38185   **    2     Allocate a new page even it doing so is difficult.
   38186   **          (createFlag==1 AND !(bPurgeable AND pDirty)
   38187   */
   38188   eCreate = createFlag==0 ? 0 : pCache->eCreate;
   38189   assert( (createFlag*(1+(!pCache->bPurgeable||!pCache->pDirty)))==eCreate );
   38190   pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
   38191   if( !pPage && eCreate==1 ){
   38192     PgHdr *pPg;
   38193 
   38194     /* Find a dirty page to write-out and recycle. First try to find a
   38195     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
   38196     ** cleared), but if that is not possible settle for any other
   38197     ** unreferenced dirty page.
   38198     */
   38199     expensive_assert( pcacheCheckSynced(pCache) );
   38200     for(pPg=pCache->pSynced;
   38201         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
   38202         pPg=pPg->pDirtyPrev
   38203     );
   38204     pCache->pSynced = pPg;
   38205     if( !pPg ){
   38206       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
   38207     }
   38208     if( pPg ){
   38209       int rc;
   38210 #ifdef SQLITE_LOG_CACHE_SPILL
   38211       sqlite3_log(SQLITE_FULL,
   38212                   "spill page %d making room for %d - cache used: %d/%d",
   38213                   pPg->pgno, pgno,
   38214                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
   38215                   numberOfCachePages(pCache));
   38216 #endif
   38217       rc = pCache->xStress(pCache->pStress, pPg);
   38218       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   38219         return rc;
   38220       }
   38221     }
   38222 
   38223     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
   38224   }
   38225 
   38226   if( pPage ){
   38227     pPgHdr = (PgHdr *)pPage->pExtra;
   38228 
   38229     if( !pPgHdr->pPage ){
   38230       memset(pPgHdr, 0, sizeof(PgHdr));
   38231       pPgHdr->pPage = pPage;
   38232       pPgHdr->pData = pPage->pBuf;
   38233       pPgHdr->pExtra = (void *)&pPgHdr[1];
   38234       memset(pPgHdr->pExtra, 0, pCache->szExtra);
   38235       pPgHdr->pCache = pCache;
   38236       pPgHdr->pgno = pgno;
   38237     }
   38238     assert( pPgHdr->pCache==pCache );
   38239     assert( pPgHdr->pgno==pgno );
   38240     assert( pPgHdr->pData==pPage->pBuf );
   38241     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
   38242 
   38243     if( 0==pPgHdr->nRef ){
   38244       pCache->nRef++;
   38245     }
   38246     pPgHdr->nRef++;
   38247     if( pgno==1 ){
   38248       pCache->pPage1 = pPgHdr;
   38249     }
   38250   }
   38251   *ppPage = pPgHdr;
   38252   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
   38253 }
   38254 
   38255 /*
   38256 ** Decrement the reference count on a page. If the page is clean and the
   38257 ** reference count drops to 0, then it is made elible for recycling.
   38258 */
   38259 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
   38260   assert( p->nRef>0 );
   38261   p->nRef--;
   38262   if( p->nRef==0 ){
   38263     PCache *pCache = p->pCache;
   38264     pCache->nRef--;
   38265     if( (p->flags&PGHDR_DIRTY)==0 ){
   38266       pcacheUnpin(p);
   38267     }else{
   38268       /* Move the page to the head of the dirty list. */
   38269       pcacheRemoveFromDirtyList(p);
   38270       pcacheAddToDirtyList(p);
   38271     }
   38272   }
   38273 }
   38274 
   38275 /*
   38276 ** Increase the reference count of a supplied page by 1.
   38277 */
   38278 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
   38279   assert(p->nRef>0);
   38280   p->nRef++;
   38281 }
   38282 
   38283 /*
   38284 ** Drop a page from the cache. There must be exactly one reference to the
   38285 ** page. This function deletes that reference, so after it returns the
   38286 ** page pointed to by p is invalid.
   38287 */
   38288 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
   38289   PCache *pCache;
   38290   assert( p->nRef==1 );
   38291   if( p->flags&PGHDR_DIRTY ){
   38292     pcacheRemoveFromDirtyList(p);
   38293   }
   38294   pCache = p->pCache;
   38295   pCache->nRef--;
   38296   if( p->pgno==1 ){
   38297     pCache->pPage1 = 0;
   38298   }
   38299   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
   38300 }
   38301 
   38302 /*
   38303 ** Make sure the page is marked as dirty. If it isn't dirty already,
   38304 ** make it so.
   38305 */
   38306 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
   38307   p->flags &= ~PGHDR_DONT_WRITE;
   38308   assert( p->nRef>0 );
   38309   if( 0==(p->flags & PGHDR_DIRTY) ){
   38310     p->flags |= PGHDR_DIRTY;
   38311     pcacheAddToDirtyList( p);
   38312   }
   38313 }
   38314 
   38315 /*
   38316 ** Make sure the page is marked as clean. If it isn't clean already,
   38317 ** make it so.
   38318 */
   38319 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
   38320   if( (p->flags & PGHDR_DIRTY) ){
   38321     pcacheRemoveFromDirtyList(p);
   38322     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
   38323     if( p->nRef==0 ){
   38324       pcacheUnpin(p);
   38325     }
   38326   }
   38327 }
   38328 
   38329 /*
   38330 ** Make every page in the cache clean.
   38331 */
   38332 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
   38333   PgHdr *p;
   38334   while( (p = pCache->pDirty)!=0 ){
   38335     sqlite3PcacheMakeClean(p);
   38336   }
   38337 }
   38338 
   38339 /*
   38340 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
   38341 */
   38342 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
   38343   PgHdr *p;
   38344   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   38345     p->flags &= ~PGHDR_NEED_SYNC;
   38346   }
   38347   pCache->pSynced = pCache->pDirtyTail;
   38348 }
   38349 
   38350 /*
   38351 ** Change the page number of page p to newPgno.
   38352 */
   38353 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   38354   PCache *pCache = p->pCache;
   38355   assert( p->nRef>0 );
   38356   assert( newPgno>0 );
   38357   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
   38358   p->pgno = newPgno;
   38359   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
   38360     pcacheRemoveFromDirtyList(p);
   38361     pcacheAddToDirtyList(p);
   38362   }
   38363 }
   38364 
   38365 /*
   38366 ** Drop every cache entry whose page number is greater than "pgno". The
   38367 ** caller must ensure that there are no outstanding references to any pages
   38368 ** other than page 1 with a page number greater than pgno.
   38369 **
   38370 ** If there is a reference to page 1 and the pgno parameter passed to this
   38371 ** function is 0, then the data area associated with page 1 is zeroed, but
   38372 ** the page object is not dropped.
   38373 */
   38374 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
   38375   if( pCache->pCache ){
   38376     PgHdr *p;
   38377     PgHdr *pNext;
   38378     for(p=pCache->pDirty; p; p=pNext){
   38379       pNext = p->pDirtyNext;
   38380       /* This routine never gets call with a positive pgno except right
   38381       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
   38382       ** it must be that pgno==0.
   38383       */
   38384       assert( p->pgno>0 );
   38385       if( ALWAYS(p->pgno>pgno) ){
   38386         assert( p->flags&PGHDR_DIRTY );
   38387         sqlite3PcacheMakeClean(p);
   38388       }
   38389     }
   38390     if( pgno==0 && pCache->pPage1 ){
   38391       memset(pCache->pPage1->pData, 0, pCache->szPage);
   38392       pgno = 1;
   38393     }
   38394     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
   38395   }
   38396 }
   38397 
   38398 /*
   38399 ** Close a cache.
   38400 */
   38401 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
   38402   if( pCache->pCache ){
   38403     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   38404   }
   38405 }
   38406 
   38407 /*
   38408 ** Discard the contents of the cache.
   38409 */
   38410 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
   38411   sqlite3PcacheTruncate(pCache, 0);
   38412 }
   38413 
   38414 /*
   38415 ** Merge two lists of pages connected by pDirty and in pgno order.
   38416 ** Do not both fixing the pDirtyPrev pointers.
   38417 */
   38418 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
   38419   PgHdr result, *pTail;
   38420   pTail = &result;
   38421   while( pA && pB ){
   38422     if( pA->pgno<pB->pgno ){
   38423       pTail->pDirty = pA;
   38424       pTail = pA;
   38425       pA = pA->pDirty;
   38426     }else{
   38427       pTail->pDirty = pB;
   38428       pTail = pB;
   38429       pB = pB->pDirty;
   38430     }
   38431   }
   38432   if( pA ){
   38433     pTail->pDirty = pA;
   38434   }else if( pB ){
   38435     pTail->pDirty = pB;
   38436   }else{
   38437     pTail->pDirty = 0;
   38438   }
   38439   return result.pDirty;
   38440 }
   38441 
   38442 /*
   38443 ** Sort the list of pages in accending order by pgno.  Pages are
   38444 ** connected by pDirty pointers.  The pDirtyPrev pointers are
   38445 ** corrupted by this sort.
   38446 **
   38447 ** Since there cannot be more than 2^31 distinct pages in a database,
   38448 ** there cannot be more than 31 buckets required by the merge sorter.
   38449 ** One extra bucket is added to catch overflow in case something
   38450 ** ever changes to make the previous sentence incorrect.
   38451 */
   38452 #define N_SORT_BUCKET  32
   38453 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
   38454   PgHdr *a[N_SORT_BUCKET], *p;
   38455   int i;
   38456   memset(a, 0, sizeof(a));
   38457   while( pIn ){
   38458     p = pIn;
   38459     pIn = p->pDirty;
   38460     p->pDirty = 0;
   38461     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
   38462       if( a[i]==0 ){
   38463         a[i] = p;
   38464         break;
   38465       }else{
   38466         p = pcacheMergeDirtyList(a[i], p);
   38467         a[i] = 0;
   38468       }
   38469     }
   38470     if( NEVER(i==N_SORT_BUCKET-1) ){
   38471       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
   38472       ** the input list.  But that is impossible.
   38473       */
   38474       a[i] = pcacheMergeDirtyList(a[i], p);
   38475     }
   38476   }
   38477   p = a[0];
   38478   for(i=1; i<N_SORT_BUCKET; i++){
   38479     p = pcacheMergeDirtyList(p, a[i]);
   38480   }
   38481   return p;
   38482 }
   38483 
   38484 /*
   38485 ** Return a list of all dirty pages in the cache, sorted by page number.
   38486 */
   38487 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
   38488   PgHdr *p;
   38489   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   38490     p->pDirty = p->pDirtyNext;
   38491   }
   38492   return pcacheSortDirtyList(pCache->pDirty);
   38493 }
   38494 
   38495 /*
   38496 ** Return the total number of referenced pages held by the cache.
   38497 */
   38498 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
   38499   return pCache->nRef;
   38500 }
   38501 
   38502 /*
   38503 ** Return the number of references to the page supplied as an argument.
   38504 */
   38505 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
   38506   return p->nRef;
   38507 }
   38508 
   38509 /*
   38510 ** Return the total number of pages in the cache.
   38511 */
   38512 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
   38513   int nPage = 0;
   38514   if( pCache->pCache ){
   38515     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
   38516   }
   38517   return nPage;
   38518 }
   38519 
   38520 #ifdef SQLITE_TEST
   38521 /*
   38522 ** Get the suggested cache-size value.
   38523 */
   38524 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
   38525   return numberOfCachePages(pCache);
   38526 }
   38527 #endif
   38528 
   38529 /*
   38530 ** Set the suggested cache-size value.
   38531 */
   38532 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
   38533   pCache->szCache = mxPage;
   38534   if( pCache->pCache ){
   38535     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
   38536                                            numberOfCachePages(pCache));
   38537   }
   38538 }
   38539 
   38540 /*
   38541 ** Free up as much memory as possible from the page cache.
   38542 */
   38543 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
   38544   if( pCache->pCache ){
   38545     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
   38546   }
   38547 }
   38548 
   38549 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   38550 /*
   38551 ** For all dirty pages currently in the cache, invoke the specified
   38552 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
   38553 ** defined.
   38554 */
   38555 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
   38556   PgHdr *pDirty;
   38557   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
   38558     xIter(pDirty);
   38559   }
   38560 }
   38561 #endif
   38562 
   38563 /************** End of pcache.c **********************************************/
   38564 /************** Begin file pcache1.c *****************************************/
   38565 /*
   38566 ** 2008 November 05
   38567 **
   38568 ** The author disclaims copyright to this source code.  In place of
   38569 ** a legal notice, here is a blessing:
   38570 **
   38571 **    May you do good and not evil.
   38572 **    May you find forgiveness for yourself and forgive others.
   38573 **    May you share freely, never taking more than you give.
   38574 **
   38575 *************************************************************************
   38576 **
   38577 ** This file implements the default page cache implementation (the
   38578 ** sqlite3_pcache interface). It also contains part of the implementation
   38579 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
   38580 ** If the default page cache implementation is overriden, then neither of
   38581 ** these two features are available.
   38582 */
   38583 
   38584 
   38585 typedef struct PCache1 PCache1;
   38586 typedef struct PgHdr1 PgHdr1;
   38587 typedef struct PgFreeslot PgFreeslot;
   38588 typedef struct PGroup PGroup;
   38589 
   38590 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
   38591 ** of one or more PCaches that are able to recycle each others unpinned
   38592 ** pages when they are under memory pressure.  A PGroup is an instance of
   38593 ** the following object.
   38594 **
   38595 ** This page cache implementation works in one of two modes:
   38596 **
   38597 **   (1)  Every PCache is the sole member of its own PGroup.  There is
   38598 **        one PGroup per PCache.
   38599 **
   38600 **   (2)  There is a single global PGroup that all PCaches are a member
   38601 **        of.
   38602 **
   38603 ** Mode 1 uses more memory (since PCache instances are not able to rob
   38604 ** unused pages from other PCaches) but it also operates without a mutex,
   38605 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
   38606 ** threadsafe, but recycles pages more efficiently.
   38607 **
   38608 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
   38609 ** PGroup which is the pcache1.grp global variable and its mutex is
   38610 ** SQLITE_MUTEX_STATIC_LRU.
   38611 */
   38612 struct PGroup {
   38613   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
   38614   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
   38615   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
   38616   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
   38617   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
   38618   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
   38619 };
   38620 
   38621 /* Each page cache is an instance of the following object.  Every
   38622 ** open database file (including each in-memory database and each
   38623 ** temporary or transient database) has a single page cache which
   38624 ** is an instance of this object.
   38625 **
   38626 ** Pointers to structures of this type are cast and returned as
   38627 ** opaque sqlite3_pcache* handles.
   38628 */
   38629 struct PCache1 {
   38630   /* Cache configuration parameters. Page size (szPage) and the purgeable
   38631   ** flag (bPurgeable) are set when the cache is created. nMax may be
   38632   ** modified at any time by a call to the pcache1Cachesize() method.
   38633   ** The PGroup mutex must be held when accessing nMax.
   38634   */
   38635   PGroup *pGroup;                     /* PGroup this cache belongs to */
   38636   int szPage;                         /* Size of allocated pages in bytes */
   38637   int szExtra;                        /* Size of extra space in bytes */
   38638   int bPurgeable;                     /* True if cache is purgeable */
   38639   unsigned int nMin;                  /* Minimum number of pages reserved */
   38640   unsigned int nMax;                  /* Configured "cache_size" value */
   38641   unsigned int n90pct;                /* nMax*9/10 */
   38642   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
   38643 
   38644   /* Hash table of all pages. The following variables may only be accessed
   38645   ** when the accessor is holding the PGroup mutex.
   38646   */
   38647   unsigned int nRecyclable;           /* Number of pages in the LRU list */
   38648   unsigned int nPage;                 /* Total number of pages in apHash */
   38649   unsigned int nHash;                 /* Number of slots in apHash[] */
   38650   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
   38651 };
   38652 
   38653 /*
   38654 ** Each cache entry is represented by an instance of the following
   38655 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
   38656 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
   38657 ** in memory.
   38658 */
   38659 struct PgHdr1 {
   38660   sqlite3_pcache_page page;
   38661   unsigned int iKey;             /* Key value (page number) */
   38662   u8 isPinned;                   /* Page in use, not on the LRU list */
   38663   PgHdr1 *pNext;                 /* Next in hash table chain */
   38664   PCache1 *pCache;               /* Cache that currently owns this page */
   38665   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
   38666   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
   38667 };
   38668 
   38669 /*
   38670 ** Free slots in the allocator used to divide up the buffer provided using
   38671 ** the SQLITE_CONFIG_PAGECACHE mechanism.
   38672 */
   38673 struct PgFreeslot {
   38674   PgFreeslot *pNext;  /* Next free slot */
   38675 };
   38676 
   38677 /*
   38678 ** Global data used by this cache.
   38679 */
   38680 static SQLITE_WSD struct PCacheGlobal {
   38681   PGroup grp;                    /* The global PGroup for mode (2) */
   38682 
   38683   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
   38684   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
   38685   ** fixed at sqlite3_initialize() time and do not require mutex protection.
   38686   ** The nFreeSlot and pFree values do require mutex protection.
   38687   */
   38688   int isInit;                    /* True if initialized */
   38689   int szSlot;                    /* Size of each free slot */
   38690   int nSlot;                     /* The number of pcache slots */
   38691   int nReserve;                  /* Try to keep nFreeSlot above this */
   38692   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
   38693   /* Above requires no mutex.  Use mutex below for variable that follow. */
   38694   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
   38695   PgFreeslot *pFree;             /* Free page blocks */
   38696   int nFreeSlot;                 /* Number of unused pcache slots */
   38697   /* The following value requires a mutex to change.  We skip the mutex on
   38698   ** reading because (1) most platforms read a 32-bit integer atomically and
   38699   ** (2) even if an incorrect value is read, no great harm is done since this
   38700   ** is really just an optimization. */
   38701   int bUnderPressure;            /* True if low on PAGECACHE memory */
   38702 } pcache1_g;
   38703 
   38704 /*
   38705 ** All code in this file should access the global structure above via the
   38706 ** alias "pcache1". This ensures that the WSD emulation is used when
   38707 ** compiling for systems that do not support real WSD.
   38708 */
   38709 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
   38710 
   38711 /*
   38712 ** Macros to enter and leave the PCache LRU mutex.
   38713 */
   38714 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
   38715 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
   38716 
   38717 /******************************************************************************/
   38718 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
   38719 
   38720 /*
   38721 ** This function is called during initialization if a static buffer is
   38722 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
   38723 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
   38724 ** enough to contain 'n' buffers of 'sz' bytes each.
   38725 **
   38726 ** This routine is called from sqlite3_initialize() and so it is guaranteed
   38727 ** to be serialized already.  There is no need for further mutexing.
   38728 */
   38729 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
   38730   if( pcache1.isInit ){
   38731     PgFreeslot *p;
   38732     sz = ROUNDDOWN8(sz);
   38733     pcache1.szSlot = sz;
   38734     pcache1.nSlot = pcache1.nFreeSlot = n;
   38735     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
   38736     pcache1.pStart = pBuf;
   38737     pcache1.pFree = 0;
   38738     pcache1.bUnderPressure = 0;
   38739     while( n-- ){
   38740       p = (PgFreeslot*)pBuf;
   38741       p->pNext = pcache1.pFree;
   38742       pcache1.pFree = p;
   38743       pBuf = (void*)&((char*)pBuf)[sz];
   38744     }
   38745     pcache1.pEnd = pBuf;
   38746   }
   38747 }
   38748 
   38749 /*
   38750 ** Malloc function used within this file to allocate space from the buffer
   38751 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
   38752 ** such buffer exists or there is no space left in it, this function falls
   38753 ** back to sqlite3Malloc().
   38754 **
   38755 ** Multiple threads can run this routine at the same time.  Global variables
   38756 ** in pcache1 need to be protected via mutex.
   38757 */
   38758 static void *pcache1Alloc(int nByte){
   38759   void *p = 0;
   38760   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   38761   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
   38762   if( nByte<=pcache1.szSlot ){
   38763     sqlite3_mutex_enter(pcache1.mutex);
   38764     p = (PgHdr1 *)pcache1.pFree;
   38765     if( p ){
   38766       pcache1.pFree = pcache1.pFree->pNext;
   38767       pcache1.nFreeSlot--;
   38768       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   38769       assert( pcache1.nFreeSlot>=0 );
   38770       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
   38771     }
   38772     sqlite3_mutex_leave(pcache1.mutex);
   38773   }
   38774   if( p==0 ){
   38775     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
   38776     ** it from sqlite3Malloc instead.
   38777     */
   38778     p = sqlite3Malloc(nByte);
   38779 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
   38780     if( p ){
   38781       int sz = sqlite3MallocSize(p);
   38782       sqlite3_mutex_enter(pcache1.mutex);
   38783       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
   38784       sqlite3_mutex_leave(pcache1.mutex);
   38785     }
   38786 #endif
   38787     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   38788   }
   38789   return p;
   38790 }
   38791 
   38792 /*
   38793 ** Free an allocated buffer obtained from pcache1Alloc().
   38794 */
   38795 static int pcache1Free(void *p){
   38796   int nFreed = 0;
   38797   if( p==0 ) return 0;
   38798   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   38799     PgFreeslot *pSlot;
   38800     sqlite3_mutex_enter(pcache1.mutex);
   38801     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
   38802     pSlot = (PgFreeslot*)p;
   38803     pSlot->pNext = pcache1.pFree;
   38804     pcache1.pFree = pSlot;
   38805     pcache1.nFreeSlot++;
   38806     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   38807     assert( pcache1.nFreeSlot<=pcache1.nSlot );
   38808     sqlite3_mutex_leave(pcache1.mutex);
   38809   }else{
   38810     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   38811     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   38812     nFreed = sqlite3MallocSize(p);
   38813 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
   38814     sqlite3_mutex_enter(pcache1.mutex);
   38815     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
   38816     sqlite3_mutex_leave(pcache1.mutex);
   38817 #endif
   38818     sqlite3_free(p);
   38819   }
   38820   return nFreed;
   38821 }
   38822 
   38823 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   38824 /*
   38825 ** Return the size of a pcache allocation
   38826 */
   38827 static int pcache1MemSize(void *p){
   38828   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   38829     return pcache1.szSlot;
   38830   }else{
   38831     int iSize;
   38832     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   38833     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   38834     iSize = sqlite3MallocSize(p);
   38835     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   38836     return iSize;
   38837   }
   38838 }
   38839 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   38840 
   38841 /*
   38842 ** Allocate a new page object initially associated with cache pCache.
   38843 */
   38844 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
   38845   PgHdr1 *p = 0;
   38846   void *pPg;
   38847 
   38848   /* The group mutex must be released before pcache1Alloc() is called. This
   38849   ** is because it may call sqlite3_release_memory(), which assumes that
   38850   ** this mutex is not held. */
   38851   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   38852   pcache1LeaveMutex(pCache->pGroup);
   38853 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   38854   pPg = pcache1Alloc(pCache->szPage);
   38855   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
   38856   if( !pPg || !p ){
   38857     pcache1Free(pPg);
   38858     sqlite3_free(p);
   38859     pPg = 0;
   38860   }
   38861 #else
   38862   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
   38863   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
   38864 #endif
   38865   pcache1EnterMutex(pCache->pGroup);
   38866 
   38867   if( pPg ){
   38868     p->page.pBuf = pPg;
   38869     p->page.pExtra = &p[1];
   38870     if( pCache->bPurgeable ){
   38871       pCache->pGroup->nCurrentPage++;
   38872     }
   38873     return p;
   38874   }
   38875   return 0;
   38876 }
   38877 
   38878 /*
   38879 ** Free a page object allocated by pcache1AllocPage().
   38880 **
   38881 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
   38882 ** that the current implementation happens to never call this routine
   38883 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
   38884 */
   38885 static void pcache1FreePage(PgHdr1 *p){
   38886   if( ALWAYS(p) ){
   38887     PCache1 *pCache = p->pCache;
   38888     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
   38889     pcache1Free(p->page.pBuf);
   38890 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   38891     sqlite3_free(p);
   38892 #endif
   38893     if( pCache->bPurgeable ){
   38894       pCache->pGroup->nCurrentPage--;
   38895     }
   38896   }
   38897 }
   38898 
   38899 /*
   38900 ** Malloc function used by SQLite to obtain space from the buffer configured
   38901 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
   38902 ** exists, this function falls back to sqlite3Malloc().
   38903 */
   38904 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
   38905   return pcache1Alloc(sz);
   38906 }
   38907 
   38908 /*
   38909 ** Free an allocated buffer obtained from sqlite3PageMalloc().
   38910 */
   38911 SQLITE_PRIVATE void sqlite3PageFree(void *p){
   38912   pcache1Free(p);
   38913 }
   38914 
   38915 
   38916 /*
   38917 ** Return true if it desirable to avoid allocating a new page cache
   38918 ** entry.
   38919 **
   38920 ** If memory was allocated specifically to the page cache using
   38921 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
   38922 ** it is desirable to avoid allocating a new page cache entry because
   38923 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
   38924 ** for all page cache needs and we should not need to spill the
   38925 ** allocation onto the heap.
   38926 **
   38927 ** Or, the heap is used for all page cache memory but the heap is
   38928 ** under memory pressure, then again it is desirable to avoid
   38929 ** allocating a new page cache entry in order to avoid stressing
   38930 ** the heap even further.
   38931 */
   38932 static int pcache1UnderMemoryPressure(PCache1 *pCache){
   38933   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
   38934     return pcache1.bUnderPressure;
   38935   }else{
   38936     return sqlite3HeapNearlyFull();
   38937   }
   38938 }
   38939 
   38940 /******************************************************************************/
   38941 /******** General Implementation Functions ************************************/
   38942 
   38943 /*
   38944 ** This function is used to resize the hash table used by the cache passed
   38945 ** as the first argument.
   38946 **
   38947 ** The PCache mutex must be held when this function is called.
   38948 */
   38949 static int pcache1ResizeHash(PCache1 *p){
   38950   PgHdr1 **apNew;
   38951   unsigned int nNew;
   38952   unsigned int i;
   38953 
   38954   assert( sqlite3_mutex_held(p->pGroup->mutex) );
   38955 
   38956   nNew = p->nHash*2;
   38957   if( nNew<256 ){
   38958     nNew = 256;
   38959   }
   38960 
   38961   pcache1LeaveMutex(p->pGroup);
   38962   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
   38963   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
   38964   if( p->nHash ){ sqlite3EndBenignMalloc(); }
   38965   pcache1EnterMutex(p->pGroup);
   38966   if( apNew ){
   38967     for(i=0; i<p->nHash; i++){
   38968       PgHdr1 *pPage;
   38969       PgHdr1 *pNext = p->apHash[i];
   38970       while( (pPage = pNext)!=0 ){
   38971         unsigned int h = pPage->iKey % nNew;
   38972         pNext = pPage->pNext;
   38973         pPage->pNext = apNew[h];
   38974         apNew[h] = pPage;
   38975       }
   38976     }
   38977     sqlite3_free(p->apHash);
   38978     p->apHash = apNew;
   38979     p->nHash = nNew;
   38980   }
   38981 
   38982   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
   38983 }
   38984 
   38985 /*
   38986 ** This function is used internally to remove the page pPage from the
   38987 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
   38988 ** LRU list, then this function is a no-op.
   38989 **
   38990 ** The PGroup mutex must be held when this function is called.
   38991 */
   38992 static void pcache1PinPage(PgHdr1 *pPage){
   38993   PCache1 *pCache;
   38994   PGroup *pGroup;
   38995 
   38996   assert( pPage!=0 );
   38997   assert( pPage->isPinned==0 );
   38998   pCache = pPage->pCache;
   38999   pGroup = pCache->pGroup;
   39000   assert( pPage->pLruNext || pPage==pGroup->pLruTail );
   39001   assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
   39002   assert( sqlite3_mutex_held(pGroup->mutex) );
   39003   if( pPage->pLruPrev ){
   39004     pPage->pLruPrev->pLruNext = pPage->pLruNext;
   39005   }else{
   39006     pGroup->pLruHead = pPage->pLruNext;
   39007   }
   39008   if( pPage->pLruNext ){
   39009     pPage->pLruNext->pLruPrev = pPage->pLruPrev;
   39010   }else{
   39011     pGroup->pLruTail = pPage->pLruPrev;
   39012   }
   39013   pPage->pLruNext = 0;
   39014   pPage->pLruPrev = 0;
   39015   pPage->isPinned = 1;
   39016   pCache->nRecyclable--;
   39017 }
   39018 
   39019 
   39020 /*
   39021 ** Remove the page supplied as an argument from the hash table
   39022 ** (PCache1.apHash structure) that it is currently stored in.
   39023 **
   39024 ** The PGroup mutex must be held when this function is called.
   39025 */
   39026 static void pcache1RemoveFromHash(PgHdr1 *pPage){
   39027   unsigned int h;
   39028   PCache1 *pCache = pPage->pCache;
   39029   PgHdr1 **pp;
   39030 
   39031   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   39032   h = pPage->iKey % pCache->nHash;
   39033   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
   39034   *pp = (*pp)->pNext;
   39035 
   39036   pCache->nPage--;
   39037 }
   39038 
   39039 /*
   39040 ** If there are currently more than nMaxPage pages allocated, try
   39041 ** to recycle pages to reduce the number allocated to nMaxPage.
   39042 */
   39043 static void pcache1EnforceMaxPage(PGroup *pGroup){
   39044   assert( sqlite3_mutex_held(pGroup->mutex) );
   39045   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
   39046     PgHdr1 *p = pGroup->pLruTail;
   39047     assert( p->pCache->pGroup==pGroup );
   39048     assert( p->isPinned==0 );
   39049     pcache1PinPage(p);
   39050     pcache1RemoveFromHash(p);
   39051     pcache1FreePage(p);
   39052   }
   39053 }
   39054 
   39055 /*
   39056 ** Discard all pages from cache pCache with a page number (key value)
   39057 ** greater than or equal to iLimit. Any pinned pages that meet this
   39058 ** criteria are unpinned before they are discarded.
   39059 **
   39060 ** The PCache mutex must be held when this function is called.
   39061 */
   39062 static void pcache1TruncateUnsafe(
   39063   PCache1 *pCache,             /* The cache to truncate */
   39064   unsigned int iLimit          /* Drop pages with this pgno or larger */
   39065 ){
   39066   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
   39067   unsigned int h;
   39068   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   39069   for(h=0; h<pCache->nHash; h++){
   39070     PgHdr1 **pp = &pCache->apHash[h];
   39071     PgHdr1 *pPage;
   39072     while( (pPage = *pp)!=0 ){
   39073       if( pPage->iKey>=iLimit ){
   39074         pCache->nPage--;
   39075         *pp = pPage->pNext;
   39076         if( !pPage->isPinned ) pcache1PinPage(pPage);
   39077         pcache1FreePage(pPage);
   39078       }else{
   39079         pp = &pPage->pNext;
   39080         TESTONLY( nPage++; )
   39081       }
   39082     }
   39083   }
   39084   assert( pCache->nPage==nPage );
   39085 }
   39086 
   39087 /******************************************************************************/
   39088 /******** sqlite3_pcache Methods **********************************************/
   39089 
   39090 /*
   39091 ** Implementation of the sqlite3_pcache.xInit method.
   39092 */
   39093 static int pcache1Init(void *NotUsed){
   39094   UNUSED_PARAMETER(NotUsed);
   39095   assert( pcache1.isInit==0 );
   39096   memset(&pcache1, 0, sizeof(pcache1));
   39097   if( sqlite3GlobalConfig.bCoreMutex ){
   39098     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
   39099     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
   39100   }
   39101   pcache1.grp.mxPinned = 10;
   39102   pcache1.isInit = 1;
   39103   return SQLITE_OK;
   39104 }
   39105 
   39106 /*
   39107 ** Implementation of the sqlite3_pcache.xShutdown method.
   39108 ** Note that the static mutex allocated in xInit does
   39109 ** not need to be freed.
   39110 */
   39111 static void pcache1Shutdown(void *NotUsed){
   39112   UNUSED_PARAMETER(NotUsed);
   39113   assert( pcache1.isInit!=0 );
   39114   memset(&pcache1, 0, sizeof(pcache1));
   39115 }
   39116 
   39117 /*
   39118 ** Implementation of the sqlite3_pcache.xCreate method.
   39119 **
   39120 ** Allocate a new cache.
   39121 */
   39122 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
   39123   PCache1 *pCache;      /* The newly created page cache */
   39124   PGroup *pGroup;       /* The group the new page cache will belong to */
   39125   int sz;               /* Bytes of memory required to allocate the new cache */
   39126 
   39127   /*
   39128   ** The separateCache variable is true if each PCache has its own private
   39129   ** PGroup.  In other words, separateCache is true for mode (1) where no
   39130   ** mutexing is required.
   39131   **
   39132   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
   39133   **
   39134   **   *  Always use a unified cache in single-threaded applications
   39135   **
   39136   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
   39137   **      use separate caches (mode-1)
   39138   */
   39139 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
   39140   const int separateCache = 0;
   39141 #else
   39142   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
   39143 #endif
   39144 
   39145   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
   39146   assert( szExtra < 300 );
   39147 
   39148   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
   39149   pCache = (PCache1 *)sqlite3MallocZero(sz);
   39150   if( pCache ){
   39151     if( separateCache ){
   39152       pGroup = (PGroup*)&pCache[1];
   39153       pGroup->mxPinned = 10;
   39154     }else{
   39155       pGroup = &pcache1.grp;
   39156     }
   39157     pCache->pGroup = pGroup;
   39158     pCache->szPage = szPage;
   39159     pCache->szExtra = szExtra;
   39160     pCache->bPurgeable = (bPurgeable ? 1 : 0);
   39161     if( bPurgeable ){
   39162       pCache->nMin = 10;
   39163       pcache1EnterMutex(pGroup);
   39164       pGroup->nMinPage += pCache->nMin;
   39165       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   39166       pcache1LeaveMutex(pGroup);
   39167     }
   39168   }
   39169   return (sqlite3_pcache *)pCache;
   39170 }
   39171 
   39172 /*
   39173 ** Implementation of the sqlite3_pcache.xCachesize method.
   39174 **
   39175 ** Configure the cache_size limit for a cache.
   39176 */
   39177 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
   39178   PCache1 *pCache = (PCache1 *)p;
   39179   if( pCache->bPurgeable ){
   39180     PGroup *pGroup = pCache->pGroup;
   39181     pcache1EnterMutex(pGroup);
   39182     pGroup->nMaxPage += (nMax - pCache->nMax);
   39183     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   39184     pCache->nMax = nMax;
   39185     pCache->n90pct = pCache->nMax*9/10;
   39186     pcache1EnforceMaxPage(pGroup);
   39187     pcache1LeaveMutex(pGroup);
   39188   }
   39189 }
   39190 
   39191 /*
   39192 ** Implementation of the sqlite3_pcache.xShrink method.
   39193 **
   39194 ** Free up as much memory as possible.
   39195 */
   39196 static void pcache1Shrink(sqlite3_pcache *p){
   39197   PCache1 *pCache = (PCache1*)p;
   39198   if( pCache->bPurgeable ){
   39199     PGroup *pGroup = pCache->pGroup;
   39200     int savedMaxPage;
   39201     pcache1EnterMutex(pGroup);
   39202     savedMaxPage = pGroup->nMaxPage;
   39203     pGroup->nMaxPage = 0;
   39204     pcache1EnforceMaxPage(pGroup);
   39205     pGroup->nMaxPage = savedMaxPage;
   39206     pcache1LeaveMutex(pGroup);
   39207   }
   39208 }
   39209 
   39210 /*
   39211 ** Implementation of the sqlite3_pcache.xPagecount method.
   39212 */
   39213 static int pcache1Pagecount(sqlite3_pcache *p){
   39214   int n;
   39215   PCache1 *pCache = (PCache1*)p;
   39216   pcache1EnterMutex(pCache->pGroup);
   39217   n = pCache->nPage;
   39218   pcache1LeaveMutex(pCache->pGroup);
   39219   return n;
   39220 }
   39221 
   39222 /*
   39223 ** Implementation of the sqlite3_pcache.xFetch method.
   39224 **
   39225 ** Fetch a page by key value.
   39226 **
   39227 ** Whether or not a new page may be allocated by this function depends on
   39228 ** the value of the createFlag argument.  0 means do not allocate a new
   39229 ** page.  1 means allocate a new page if space is easily available.  2
   39230 ** means to try really hard to allocate a new page.
   39231 **
   39232 ** For a non-purgeable cache (a cache used as the storage for an in-memory
   39233 ** database) there is really no difference between createFlag 1 and 2.  So
   39234 ** the calling function (pcache.c) will never have a createFlag of 1 on
   39235 ** a non-purgeable cache.
   39236 **
   39237 ** There are three different approaches to obtaining space for a page,
   39238 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
   39239 **
   39240 **   1. Regardless of the value of createFlag, the cache is searched for a
   39241 **      copy of the requested page. If one is found, it is returned.
   39242 **
   39243 **   2. If createFlag==0 and the page is not already in the cache, NULL is
   39244 **      returned.
   39245 **
   39246 **   3. If createFlag is 1, and the page is not already in the cache, then
   39247 **      return NULL (do not allocate a new page) if any of the following
   39248 **      conditions are true:
   39249 **
   39250 **       (a) the number of pages pinned by the cache is greater than
   39251 **           PCache1.nMax, or
   39252 **
   39253 **       (b) the number of pages pinned by the cache is greater than
   39254 **           the sum of nMax for all purgeable caches, less the sum of
   39255 **           nMin for all other purgeable caches, or
   39256 **
   39257 **   4. If none of the first three conditions apply and the cache is marked
   39258 **      as purgeable, and if one of the following is true:
   39259 **
   39260 **       (a) The number of pages allocated for the cache is already
   39261 **           PCache1.nMax, or
   39262 **
   39263 **       (b) The number of pages allocated for all purgeable caches is
   39264 **           already equal to or greater than the sum of nMax for all
   39265 **           purgeable caches,
   39266 **
   39267 **       (c) The system is under memory pressure and wants to avoid
   39268 **           unnecessary pages cache entry allocations
   39269 **
   39270 **      then attempt to recycle a page from the LRU list. If it is the right
   39271 **      size, return the recycled buffer. Otherwise, free the buffer and
   39272 **      proceed to step 5.
   39273 **
   39274 **   5. Otherwise, allocate and return a new page buffer.
   39275 */
   39276 static sqlite3_pcache_page *pcache1Fetch(
   39277   sqlite3_pcache *p,
   39278   unsigned int iKey,
   39279   int createFlag
   39280 ){
   39281   unsigned int nPinned;
   39282   PCache1 *pCache = (PCache1 *)p;
   39283   PGroup *pGroup;
   39284   PgHdr1 *pPage = 0;
   39285 
   39286   assert( offsetof(PgHdr1,page)==0 );
   39287   assert( pCache->bPurgeable || createFlag!=1 );
   39288   assert( pCache->bPurgeable || pCache->nMin==0 );
   39289   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
   39290   assert( pCache->nMin==0 || pCache->bPurgeable );
   39291   pcache1EnterMutex(pGroup = pCache->pGroup);
   39292 
   39293   /* Step 1: Search the hash table for an existing entry. */
   39294   if( pCache->nHash>0 ){
   39295     unsigned int h = iKey % pCache->nHash;
   39296     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
   39297   }
   39298 
   39299   /* Step 2: Abort if no existing page is found and createFlag is 0 */
   39300   if( pPage ){
   39301     if( !pPage->isPinned ) pcache1PinPage(pPage);
   39302     goto fetch_out;
   39303   }
   39304   if( createFlag==0 ){
   39305     goto fetch_out;
   39306   }
   39307 
   39308   /* The pGroup local variable will normally be initialized by the
   39309   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
   39310   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
   39311   ** local variable here.  Delaying the initialization of pGroup is an
   39312   ** optimization:  The common case is to exit the module before reaching
   39313   ** this point.
   39314   */
   39315 #ifdef SQLITE_MUTEX_OMIT
   39316   pGroup = pCache->pGroup;
   39317 #endif
   39318 
   39319   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
   39320   assert( pCache->nPage >= pCache->nRecyclable );
   39321   nPinned = pCache->nPage - pCache->nRecyclable;
   39322   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
   39323   assert( pCache->n90pct == pCache->nMax*9/10 );
   39324   if( createFlag==1 && (
   39325         nPinned>=pGroup->mxPinned
   39326      || nPinned>=pCache->n90pct
   39327      || pcache1UnderMemoryPressure(pCache)
   39328   )){
   39329     goto fetch_out;
   39330   }
   39331 
   39332   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
   39333     goto fetch_out;
   39334   }
   39335   assert( pCache->nHash>0 && pCache->apHash );
   39336 
   39337   /* Step 4. Try to recycle a page. */
   39338   if( pCache->bPurgeable && pGroup->pLruTail && (
   39339          (pCache->nPage+1>=pCache->nMax)
   39340       || pGroup->nCurrentPage>=pGroup->nMaxPage
   39341       || pcache1UnderMemoryPressure(pCache)
   39342   )){
   39343     PCache1 *pOther;
   39344     pPage = pGroup->pLruTail;
   39345     assert( pPage->isPinned==0 );
   39346     pcache1RemoveFromHash(pPage);
   39347     pcache1PinPage(pPage);
   39348     pOther = pPage->pCache;
   39349 
   39350     /* We want to verify that szPage and szExtra are the same for pOther
   39351     ** and pCache.  Assert that we can verify this by comparing sums. */
   39352     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
   39353     assert( pCache->szExtra<512 );
   39354     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
   39355     assert( pOther->szExtra<512 );
   39356 
   39357     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
   39358       pcache1FreePage(pPage);
   39359       pPage = 0;
   39360     }else{
   39361       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
   39362     }
   39363   }
   39364 
   39365   /* Step 5. If a usable page buffer has still not been found,
   39366   ** attempt to allocate a new one.
   39367   */
   39368   if( !pPage ){
   39369     if( createFlag==1 ) sqlite3BeginBenignMalloc();
   39370     pPage = pcache1AllocPage(pCache);
   39371     if( createFlag==1 ) sqlite3EndBenignMalloc();
   39372   }
   39373 
   39374   if( pPage ){
   39375     unsigned int h = iKey % pCache->nHash;
   39376     pCache->nPage++;
   39377     pPage->iKey = iKey;
   39378     pPage->pNext = pCache->apHash[h];
   39379     pPage->pCache = pCache;
   39380     pPage->pLruPrev = 0;
   39381     pPage->pLruNext = 0;
   39382     pPage->isPinned = 1;
   39383     *(void **)pPage->page.pExtra = 0;
   39384     pCache->apHash[h] = pPage;
   39385   }
   39386 
   39387 fetch_out:
   39388   if( pPage && iKey>pCache->iMaxKey ){
   39389     pCache->iMaxKey = iKey;
   39390   }
   39391   pcache1LeaveMutex(pGroup);
   39392   return (sqlite3_pcache_page*)pPage;
   39393 }
   39394 
   39395 
   39396 /*
   39397 ** Implementation of the sqlite3_pcache.xUnpin method.
   39398 **
   39399 ** Mark a page as unpinned (eligible for asynchronous recycling).
   39400 */
   39401 static void pcache1Unpin(
   39402   sqlite3_pcache *p,
   39403   sqlite3_pcache_page *pPg,
   39404   int reuseUnlikely
   39405 ){
   39406   PCache1 *pCache = (PCache1 *)p;
   39407   PgHdr1 *pPage = (PgHdr1 *)pPg;
   39408   PGroup *pGroup = pCache->pGroup;
   39409 
   39410   assert( pPage->pCache==pCache );
   39411   pcache1EnterMutex(pGroup);
   39412 
   39413   /* It is an error to call this function if the page is already
   39414   ** part of the PGroup LRU list.
   39415   */
   39416   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
   39417   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
   39418   assert( pPage->isPinned==1 );
   39419 
   39420   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
   39421     pcache1RemoveFromHash(pPage);
   39422     pcache1FreePage(pPage);
   39423   }else{
   39424     /* Add the page to the PGroup LRU list. */
   39425     if( pGroup->pLruHead ){
   39426       pGroup->pLruHead->pLruPrev = pPage;
   39427       pPage->pLruNext = pGroup->pLruHead;
   39428       pGroup->pLruHead = pPage;
   39429     }else{
   39430       pGroup->pLruTail = pPage;
   39431       pGroup->pLruHead = pPage;
   39432     }
   39433     pCache->nRecyclable++;
   39434     pPage->isPinned = 0;
   39435   }
   39436 
   39437   pcache1LeaveMutex(pCache->pGroup);
   39438 }
   39439 
   39440 /*
   39441 ** Implementation of the sqlite3_pcache.xRekey method.
   39442 */
   39443 static void pcache1Rekey(
   39444   sqlite3_pcache *p,
   39445   sqlite3_pcache_page *pPg,
   39446   unsigned int iOld,
   39447   unsigned int iNew
   39448 ){
   39449   PCache1 *pCache = (PCache1 *)p;
   39450   PgHdr1 *pPage = (PgHdr1 *)pPg;
   39451   PgHdr1 **pp;
   39452   unsigned int h;
   39453   assert( pPage->iKey==iOld );
   39454   assert( pPage->pCache==pCache );
   39455 
   39456   pcache1EnterMutex(pCache->pGroup);
   39457 
   39458   h = iOld%pCache->nHash;
   39459   pp = &pCache->apHash[h];
   39460   while( (*pp)!=pPage ){
   39461     pp = &(*pp)->pNext;
   39462   }
   39463   *pp = pPage->pNext;
   39464 
   39465   h = iNew%pCache->nHash;
   39466   pPage->iKey = iNew;
   39467   pPage->pNext = pCache->apHash[h];
   39468   pCache->apHash[h] = pPage;
   39469   if( iNew>pCache->iMaxKey ){
   39470     pCache->iMaxKey = iNew;
   39471   }
   39472 
   39473   pcache1LeaveMutex(pCache->pGroup);
   39474 }
   39475 
   39476 /*
   39477 ** Implementation of the sqlite3_pcache.xTruncate method.
   39478 **
   39479 ** Discard all unpinned pages in the cache with a page number equal to
   39480 ** or greater than parameter iLimit. Any pinned pages with a page number
   39481 ** equal to or greater than iLimit are implicitly unpinned.
   39482 */
   39483 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
   39484   PCache1 *pCache = (PCache1 *)p;
   39485   pcache1EnterMutex(pCache->pGroup);
   39486   if( iLimit<=pCache->iMaxKey ){
   39487     pcache1TruncateUnsafe(pCache, iLimit);
   39488     pCache->iMaxKey = iLimit-1;
   39489   }
   39490   pcache1LeaveMutex(pCache->pGroup);
   39491 }
   39492 
   39493 /*
   39494 ** Implementation of the sqlite3_pcache.xDestroy method.
   39495 **
   39496 ** Destroy a cache allocated using pcache1Create().
   39497 */
   39498 static void pcache1Destroy(sqlite3_pcache *p){
   39499   PCache1 *pCache = (PCache1 *)p;
   39500   PGroup *pGroup = pCache->pGroup;
   39501   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
   39502   pcache1EnterMutex(pGroup);
   39503   pcache1TruncateUnsafe(pCache, 0);
   39504   assert( pGroup->nMaxPage >= pCache->nMax );
   39505   pGroup->nMaxPage -= pCache->nMax;
   39506   assert( pGroup->nMinPage >= pCache->nMin );
   39507   pGroup->nMinPage -= pCache->nMin;
   39508   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   39509   pcache1EnforceMaxPage(pGroup);
   39510   pcache1LeaveMutex(pGroup);
   39511   sqlite3_free(pCache->apHash);
   39512   sqlite3_free(pCache);
   39513 }
   39514 
   39515 /*
   39516 ** This function is called during initialization (sqlite3_initialize()) to
   39517 ** install the default pluggable cache module, assuming the user has not
   39518 ** already provided an alternative.
   39519 */
   39520 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
   39521   static const sqlite3_pcache_methods2 defaultMethods = {
   39522     1,                       /* iVersion */
   39523     0,                       /* pArg */
   39524     pcache1Init,             /* xInit */
   39525     pcache1Shutdown,         /* xShutdown */
   39526     pcache1Create,           /* xCreate */
   39527     pcache1Cachesize,        /* xCachesize */
   39528     pcache1Pagecount,        /* xPagecount */
   39529     pcache1Fetch,            /* xFetch */
   39530     pcache1Unpin,            /* xUnpin */
   39531     pcache1Rekey,            /* xRekey */
   39532     pcache1Truncate,         /* xTruncate */
   39533     pcache1Destroy,          /* xDestroy */
   39534     pcache1Shrink            /* xShrink */
   39535   };
   39536   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
   39537 }
   39538 
   39539 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   39540 /*
   39541 ** This function is called to free superfluous dynamically allocated memory
   39542 ** held by the pager system. Memory in use by any SQLite pager allocated
   39543 ** by the current thread may be sqlite3_free()ed.
   39544 **
   39545 ** nReq is the number of bytes of memory required. Once this much has
   39546 ** been released, the function returns. The return value is the total number
   39547 ** of bytes of memory released.
   39548 */
   39549 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
   39550   int nFree = 0;
   39551   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   39552   assert( sqlite3_mutex_notheld(pcache1.mutex) );
   39553   if( pcache1.pStart==0 ){
   39554     PgHdr1 *p;
   39555     pcache1EnterMutex(&pcache1.grp);
   39556     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
   39557       nFree += pcache1MemSize(p->page.pBuf);
   39558 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   39559       nFree += sqlite3MemSize(p);
   39560 #endif
   39561       assert( p->isPinned==0 );
   39562       pcache1PinPage(p);
   39563       pcache1RemoveFromHash(p);
   39564       pcache1FreePage(p);
   39565     }
   39566     pcache1LeaveMutex(&pcache1.grp);
   39567   }
   39568   return nFree;
   39569 }
   39570 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   39571 
   39572 #ifdef SQLITE_TEST
   39573 /*
   39574 ** This function is used by test procedures to inspect the internal state
   39575 ** of the global cache.
   39576 */
   39577 SQLITE_PRIVATE void sqlite3PcacheStats(
   39578   int *pnCurrent,      /* OUT: Total number of pages cached */
   39579   int *pnMax,          /* OUT: Global maximum cache size */
   39580   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
   39581   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
   39582 ){
   39583   PgHdr1 *p;
   39584   int nRecyclable = 0;
   39585   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
   39586     assert( p->isPinned==0 );
   39587     nRecyclable++;
   39588   }
   39589   *pnCurrent = pcache1.grp.nCurrentPage;
   39590   *pnMax = (int)pcache1.grp.nMaxPage;
   39591   *pnMin = (int)pcache1.grp.nMinPage;
   39592   *pnRecyclable = nRecyclable;
   39593 }
   39594 #endif
   39595 
   39596 /************** End of pcache1.c *********************************************/
   39597 /************** Begin file rowset.c ******************************************/
   39598 /*
   39599 ** 2008 December 3
   39600 **
   39601 ** The author disclaims copyright to this source code.  In place of
   39602 ** a legal notice, here is a blessing:
   39603 **
   39604 **    May you do good and not evil.
   39605 **    May you find forgiveness for yourself and forgive others.
   39606 **    May you share freely, never taking more than you give.
   39607 **
   39608 *************************************************************************
   39609 **
   39610 ** This module implements an object we call a "RowSet".
   39611 **
   39612 ** The RowSet object is a collection of rowids.  Rowids
   39613 ** are inserted into the RowSet in an arbitrary order.  Inserts
   39614 ** can be intermixed with tests to see if a given rowid has been
   39615 ** previously inserted into the RowSet.
   39616 **
   39617 ** After all inserts are finished, it is possible to extract the
   39618 ** elements of the RowSet in sorted order.  Once this extraction
   39619 ** process has started, no new elements may be inserted.
   39620 **
   39621 ** Hence, the primitive operations for a RowSet are:
   39622 **
   39623 **    CREATE
   39624 **    INSERT
   39625 **    TEST
   39626 **    SMALLEST
   39627 **    DESTROY
   39628 **
   39629 ** The CREATE and DESTROY primitives are the constructor and destructor,
   39630 ** obviously.  The INSERT primitive adds a new element to the RowSet.
   39631 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
   39632 ** extracts the least value from the RowSet.
   39633 **
   39634 ** The INSERT primitive might allocate additional memory.  Memory is
   39635 ** allocated in chunks so most INSERTs do no allocation.  There is an
   39636 ** upper bound on the size of allocated memory.  No memory is freed
   39637 ** until DESTROY.
   39638 **
   39639 ** The TEST primitive includes a "batch" number.  The TEST primitive
   39640 ** will only see elements that were inserted before the last change
   39641 ** in the batch number.  In other words, if an INSERT occurs between
   39642 ** two TESTs where the TESTs have the same batch nubmer, then the
   39643 ** value added by the INSERT will not be visible to the second TEST.
   39644 ** The initial batch number is zero, so if the very first TEST contains
   39645 ** a non-zero batch number, it will see all prior INSERTs.
   39646 **
   39647 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
   39648 ** that is attempted.
   39649 **
   39650 ** The cost of an INSERT is roughly constant.  (Sometime new memory
   39651 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
   39652 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
   39653 ** The cost of a TEST using the same batch number is O(logN).  The cost
   39654 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
   39655 ** primitives are constant time.  The cost of DESTROY is O(N).
   39656 **
   39657 ** There is an added cost of O(N) when switching between TEST and
   39658 ** SMALLEST primitives.
   39659 */
   39660 
   39661 
   39662 /*
   39663 ** Target size for allocation chunks.
   39664 */
   39665 #define ROWSET_ALLOCATION_SIZE 1024
   39666 
   39667 /*
   39668 ** The number of rowset entries per allocation chunk.
   39669 */
   39670 #define ROWSET_ENTRY_PER_CHUNK  \
   39671                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
   39672 
   39673 /*
   39674 ** Each entry in a RowSet is an instance of the following object.
   39675 **
   39676 ** This same object is reused to store a linked list of trees of RowSetEntry
   39677 ** objects.  In that alternative use, pRight points to the next entry
   39678 ** in the list, pLeft points to the tree, and v is unused.  The
   39679 ** RowSet.pForest value points to the head of this forest list.
   39680 */
   39681 struct RowSetEntry {
   39682   i64 v;                        /* ROWID value for this entry */
   39683   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
   39684   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
   39685 };
   39686 
   39687 /*
   39688 ** RowSetEntry objects are allocated in large chunks (instances of the
   39689 ** following structure) to reduce memory allocation overhead.  The
   39690 ** chunks are kept on a linked list so that they can be deallocated
   39691 ** when the RowSet is destroyed.
   39692 */
   39693 struct RowSetChunk {
   39694   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
   39695   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
   39696 };
   39697 
   39698 /*
   39699 ** A RowSet in an instance of the following structure.
   39700 **
   39701 ** A typedef of this structure if found in sqliteInt.h.
   39702 */
   39703 struct RowSet {
   39704   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
   39705   sqlite3 *db;                   /* The database connection */
   39706   struct RowSetEntry *pEntry;    /* List of entries using pRight */
   39707   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
   39708   struct RowSetEntry *pFresh;    /* Source of new entry objects */
   39709   struct RowSetEntry *pForest;   /* List of binary trees of entries */
   39710   u16 nFresh;                    /* Number of objects on pFresh */
   39711   u16 rsFlags;                   /* Various flags */
   39712   int iBatch;                    /* Current insert batch */
   39713 };
   39714 
   39715 /*
   39716 ** Allowed values for RowSet.rsFlags
   39717 */
   39718 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
   39719 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
   39720 
   39721 /*
   39722 ** Turn bulk memory into a RowSet object.  N bytes of memory
   39723 ** are available at pSpace.  The db pointer is used as a memory context
   39724 ** for any subsequent allocations that need to occur.
   39725 ** Return a pointer to the new RowSet object.
   39726 **
   39727 ** It must be the case that N is sufficient to make a Rowset.  If not
   39728 ** an assertion fault occurs.
   39729 **
   39730 ** If N is larger than the minimum, use the surplus as an initial
   39731 ** allocation of entries available to be filled.
   39732 */
   39733 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
   39734   RowSet *p;
   39735   assert( N >= ROUND8(sizeof(*p)) );
   39736   p = pSpace;
   39737   p->pChunk = 0;
   39738   p->db = db;
   39739   p->pEntry = 0;
   39740   p->pLast = 0;
   39741   p->pForest = 0;
   39742   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
   39743   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
   39744   p->rsFlags = ROWSET_SORTED;
   39745   p->iBatch = 0;
   39746   return p;
   39747 }
   39748 
   39749 /*
   39750 ** Deallocate all chunks from a RowSet.  This frees all memory that
   39751 ** the RowSet has allocated over its lifetime.  This routine is
   39752 ** the destructor for the RowSet.
   39753 */
   39754 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
   39755   struct RowSetChunk *pChunk, *pNextChunk;
   39756   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
   39757     pNextChunk = pChunk->pNextChunk;
   39758     sqlite3DbFree(p->db, pChunk);
   39759   }
   39760   p->pChunk = 0;
   39761   p->nFresh = 0;
   39762   p->pEntry = 0;
   39763   p->pLast = 0;
   39764   p->pForest = 0;
   39765   p->rsFlags = ROWSET_SORTED;
   39766 }
   39767 
   39768 /*
   39769 ** Allocate a new RowSetEntry object that is associated with the
   39770 ** given RowSet.  Return a pointer to the new and completely uninitialized
   39771 ** objected.
   39772 **
   39773 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
   39774 ** routine returns NULL.
   39775 */
   39776 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
   39777   assert( p!=0 );
   39778   if( p->nFresh==0 ){
   39779     struct RowSetChunk *pNew;
   39780     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
   39781     if( pNew==0 ){
   39782       return 0;
   39783     }
   39784     pNew->pNextChunk = p->pChunk;
   39785     p->pChunk = pNew;
   39786     p->pFresh = pNew->aEntry;
   39787     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
   39788   }
   39789   p->nFresh--;
   39790   return p->pFresh++;
   39791 }
   39792 
   39793 /*
   39794 ** Insert a new value into a RowSet.
   39795 **
   39796 ** The mallocFailed flag of the database connection is set if a
   39797 ** memory allocation fails.
   39798 */
   39799 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
   39800   struct RowSetEntry *pEntry;  /* The new entry */
   39801   struct RowSetEntry *pLast;   /* The last prior entry */
   39802 
   39803   /* This routine is never called after sqlite3RowSetNext() */
   39804   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
   39805 
   39806   pEntry = rowSetEntryAlloc(p);
   39807   if( pEntry==0 ) return;
   39808   pEntry->v = rowid;
   39809   pEntry->pRight = 0;
   39810   pLast = p->pLast;
   39811   if( pLast ){
   39812     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
   39813       p->rsFlags &= ~ROWSET_SORTED;
   39814     }
   39815     pLast->pRight = pEntry;
   39816   }else{
   39817     p->pEntry = pEntry;
   39818   }
   39819   p->pLast = pEntry;
   39820 }
   39821 
   39822 /*
   39823 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
   39824 **
   39825 ** The input lists are connected via pRight pointers and are
   39826 ** assumed to each already be in sorted order.
   39827 */
   39828 static struct RowSetEntry *rowSetEntryMerge(
   39829   struct RowSetEntry *pA,    /* First sorted list to be merged */
   39830   struct RowSetEntry *pB     /* Second sorted list to be merged */
   39831 ){
   39832   struct RowSetEntry head;
   39833   struct RowSetEntry *pTail;
   39834 
   39835   pTail = &head;
   39836   while( pA && pB ){
   39837     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   39838     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
   39839     if( pA->v<pB->v ){
   39840       pTail->pRight = pA;
   39841       pA = pA->pRight;
   39842       pTail = pTail->pRight;
   39843     }else if( pB->v<pA->v ){
   39844       pTail->pRight = pB;
   39845       pB = pB->pRight;
   39846       pTail = pTail->pRight;
   39847     }else{
   39848       pA = pA->pRight;
   39849     }
   39850   }
   39851   if( pA ){
   39852     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   39853     pTail->pRight = pA;
   39854   }else{
   39855     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
   39856     pTail->pRight = pB;
   39857   }
   39858   return head.pRight;
   39859 }
   39860 
   39861 /*
   39862 ** Sort all elements on the list of RowSetEntry objects into order of
   39863 ** increasing v.
   39864 */
   39865 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
   39866   unsigned int i;
   39867   struct RowSetEntry *pNext, *aBucket[40];
   39868 
   39869   memset(aBucket, 0, sizeof(aBucket));
   39870   while( pIn ){
   39871     pNext = pIn->pRight;
   39872     pIn->pRight = 0;
   39873     for(i=0; aBucket[i]; i++){
   39874       pIn = rowSetEntryMerge(aBucket[i], pIn);
   39875       aBucket[i] = 0;
   39876     }
   39877     aBucket[i] = pIn;
   39878     pIn = pNext;
   39879   }
   39880   pIn = 0;
   39881   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
   39882     pIn = rowSetEntryMerge(pIn, aBucket[i]);
   39883   }
   39884   return pIn;
   39885 }
   39886 
   39887 
   39888 /*
   39889 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
   39890 ** Convert this tree into a linked list connected by the pRight pointers
   39891 ** and return pointers to the first and last elements of the new list.
   39892 */
   39893 static void rowSetTreeToList(
   39894   struct RowSetEntry *pIn,         /* Root of the input tree */
   39895   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
   39896   struct RowSetEntry **ppLast      /* Write tail of the output list here */
   39897 ){
   39898   assert( pIn!=0 );
   39899   if( pIn->pLeft ){
   39900     struct RowSetEntry *p;
   39901     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
   39902     p->pRight = pIn;
   39903   }else{
   39904     *ppFirst = pIn;
   39905   }
   39906   if( pIn->pRight ){
   39907     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
   39908   }else{
   39909     *ppLast = pIn;
   39910   }
   39911   assert( (*ppLast)->pRight==0 );
   39912 }
   39913 
   39914 
   39915 /*
   39916 ** Convert a sorted list of elements (connected by pRight) into a binary
   39917 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
   39918 ** node taken from the head of *ppList.  A depth of 2 means a tree with
   39919 ** three nodes.  And so forth.
   39920 **
   39921 ** Use as many entries from the input list as required and update the
   39922 ** *ppList to point to the unused elements of the list.  If the input
   39923 ** list contains too few elements, then construct an incomplete tree
   39924 ** and leave *ppList set to NULL.
   39925 **
   39926 ** Return a pointer to the root of the constructed binary tree.
   39927 */
   39928 static struct RowSetEntry *rowSetNDeepTree(
   39929   struct RowSetEntry **ppList,
   39930   int iDepth
   39931 ){
   39932   struct RowSetEntry *p;         /* Root of the new tree */
   39933   struct RowSetEntry *pLeft;     /* Left subtree */
   39934   if( *ppList==0 ){
   39935     return 0;
   39936   }
   39937   if( iDepth==1 ){
   39938     p = *ppList;
   39939     *ppList = p->pRight;
   39940     p->pLeft = p->pRight = 0;
   39941     return p;
   39942   }
   39943   pLeft = rowSetNDeepTree(ppList, iDepth-1);
   39944   p = *ppList;
   39945   if( p==0 ){
   39946     return pLeft;
   39947   }
   39948   p->pLeft = pLeft;
   39949   *ppList = p->pRight;
   39950   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
   39951   return p;
   39952 }
   39953 
   39954 /*
   39955 ** Convert a sorted list of elements into a binary tree. Make the tree
   39956 ** as deep as it needs to be in order to contain the entire list.
   39957 */
   39958 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
   39959   int iDepth;           /* Depth of the tree so far */
   39960   struct RowSetEntry *p;       /* Current tree root */
   39961   struct RowSetEntry *pLeft;   /* Left subtree */
   39962 
   39963   assert( pList!=0 );
   39964   p = pList;
   39965   pList = p->pRight;
   39966   p->pLeft = p->pRight = 0;
   39967   for(iDepth=1; pList; iDepth++){
   39968     pLeft = p;
   39969     p = pList;
   39970     pList = p->pRight;
   39971     p->pLeft = pLeft;
   39972     p->pRight = rowSetNDeepTree(&pList, iDepth);
   39973   }
   39974   return p;
   39975 }
   39976 
   39977 /*
   39978 ** Take all the entries on p->pEntry and on the trees in p->pForest and
   39979 ** sort them all together into one big ordered list on p->pEntry.
   39980 **
   39981 ** This routine should only be called once in the life of a RowSet.
   39982 */
   39983 static void rowSetToList(RowSet *p){
   39984 
   39985   /* This routine is called only once */
   39986   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
   39987 
   39988   if( (p->rsFlags & ROWSET_SORTED)==0 ){
   39989     p->pEntry = rowSetEntrySort(p->pEntry);
   39990   }
   39991 
   39992   /* While this module could theoretically support it, sqlite3RowSetNext()
   39993   ** is never called after sqlite3RowSetText() for the same RowSet.  So
   39994   ** there is never a forest to deal with.  Should this change, simply
   39995   ** remove the assert() and the #if 0. */
   39996   assert( p->pForest==0 );
   39997 #if 0
   39998   while( p->pForest ){
   39999     struct RowSetEntry *pTree = p->pForest->pLeft;
   40000     if( pTree ){
   40001       struct RowSetEntry *pHead, *pTail;
   40002       rowSetTreeToList(pTree, &pHead, &pTail);
   40003       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
   40004     }
   40005     p->pForest = p->pForest->pRight;
   40006   }
   40007 #endif
   40008   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
   40009 }
   40010 
   40011 /*
   40012 ** Extract the smallest element from the RowSet.
   40013 ** Write the element into *pRowid.  Return 1 on success.  Return
   40014 ** 0 if the RowSet is already empty.
   40015 **
   40016 ** After this routine has been called, the sqlite3RowSetInsert()
   40017 ** routine may not be called again.
   40018 */
   40019 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
   40020   assert( p!=0 );
   40021 
   40022   /* Merge the forest into a single sorted list on first call */
   40023   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
   40024 
   40025   /* Return the next entry on the list */
   40026   if( p->pEntry ){
   40027     *pRowid = p->pEntry->v;
   40028     p->pEntry = p->pEntry->pRight;
   40029     if( p->pEntry==0 ){
   40030       sqlite3RowSetClear(p);
   40031     }
   40032     return 1;
   40033   }else{
   40034     return 0;
   40035   }
   40036 }
   40037 
   40038 /*
   40039 ** Check to see if element iRowid was inserted into the rowset as
   40040 ** part of any insert batch prior to iBatch.  Return 1 or 0.
   40041 **
   40042 ** If this is the first test of a new batch and if there exist entires
   40043 ** on pRowSet->pEntry, then sort those entires into the forest at
   40044 ** pRowSet->pForest so that they can be tested.
   40045 */
   40046 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
   40047   struct RowSetEntry *p, *pTree;
   40048 
   40049   /* This routine is never called after sqlite3RowSetNext() */
   40050   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
   40051 
   40052   /* Sort entries into the forest on the first test of a new batch
   40053   */
   40054   if( iBatch!=pRowSet->iBatch ){
   40055     p = pRowSet->pEntry;
   40056     if( p ){
   40057       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
   40058       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
   40059         p = rowSetEntrySort(p);
   40060       }
   40061       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
   40062         ppPrevTree = &pTree->pRight;
   40063         if( pTree->pLeft==0 ){
   40064           pTree->pLeft = rowSetListToTree(p);
   40065           break;
   40066         }else{
   40067           struct RowSetEntry *pAux, *pTail;
   40068           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
   40069           pTree->pLeft = 0;
   40070           p = rowSetEntryMerge(pAux, p);
   40071         }
   40072       }
   40073       if( pTree==0 ){
   40074         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
   40075         if( pTree ){
   40076           pTree->v = 0;
   40077           pTree->pRight = 0;
   40078           pTree->pLeft = rowSetListToTree(p);
   40079         }
   40080       }
   40081       pRowSet->pEntry = 0;
   40082       pRowSet->pLast = 0;
   40083       pRowSet->rsFlags |= ROWSET_SORTED;
   40084     }
   40085     pRowSet->iBatch = iBatch;
   40086   }
   40087 
   40088   /* Test to see if the iRowid value appears anywhere in the forest.
   40089   ** Return 1 if it does and 0 if not.
   40090   */
   40091   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
   40092     p = pTree->pLeft;
   40093     while( p ){
   40094       if( p->v<iRowid ){
   40095         p = p->pRight;
   40096       }else if( p->v>iRowid ){
   40097         p = p->pLeft;
   40098       }else{
   40099         return 1;
   40100       }
   40101     }
   40102   }
   40103   return 0;
   40104 }
   40105 
   40106 /************** End of rowset.c **********************************************/
   40107 /************** Begin file pager.c *******************************************/
   40108 /*
   40109 ** 2001 September 15
   40110 **
   40111 ** The author disclaims copyright to this source code.  In place of
   40112 ** a legal notice, here is a blessing:
   40113 **
   40114 **    May you do good and not evil.
   40115 **    May you find forgiveness for yourself and forgive others.
   40116 **    May you share freely, never taking more than you give.
   40117 **
   40118 *************************************************************************
   40119 ** This is the implementation of the page cache subsystem or "pager".
   40120 **
   40121 ** The pager is used to access a database disk file.  It implements
   40122 ** atomic commit and rollback through the use of a journal file that
   40123 ** is separate from the database file.  The pager also implements file
   40124 ** locking to prevent two processes from writing the same database
   40125 ** file simultaneously, or one process from reading the database while
   40126 ** another is writing.
   40127 */
   40128 #ifndef SQLITE_OMIT_DISKIO
   40129 /************** Include wal.h in the middle of pager.c ***********************/
   40130 /************** Begin file wal.h *********************************************/
   40131 /*
   40132 ** 2010 February 1
   40133 **
   40134 ** The author disclaims copyright to this source code.  In place of
   40135 ** a legal notice, here is a blessing:
   40136 **
   40137 **    May you do good and not evil.
   40138 **    May you find forgiveness for yourself and forgive others.
   40139 **    May you share freely, never taking more than you give.
   40140 **
   40141 *************************************************************************
   40142 ** This header file defines the interface to the write-ahead logging
   40143 ** system. Refer to the comments below and the header comment attached to
   40144 ** the implementation of each function in log.c for further details.
   40145 */
   40146 
   40147 #ifndef _WAL_H_
   40148 #define _WAL_H_
   40149 
   40150 
   40151 /* Additional values that can be added to the sync_flags argument of
   40152 ** sqlite3WalFrames():
   40153 */
   40154 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
   40155 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
   40156 
   40157 #ifdef SQLITE_OMIT_WAL
   40158 # define sqlite3WalOpen(x,y,z)                   0
   40159 # define sqlite3WalLimit(x,y)
   40160 # define sqlite3WalClose(w,x,y,z)                0
   40161 # define sqlite3WalBeginReadTransaction(y,z)     0
   40162 # define sqlite3WalEndReadTransaction(z)
   40163 # define sqlite3WalDbsize(y)                     0
   40164 # define sqlite3WalBeginWriteTransaction(y)      0
   40165 # define sqlite3WalEndWriteTransaction(x)        0
   40166 # define sqlite3WalUndo(x,y,z)                   0
   40167 # define sqlite3WalSavepoint(y,z)
   40168 # define sqlite3WalSavepointUndo(y,z)            0
   40169 # define sqlite3WalFrames(u,v,w,x,y,z)           0
   40170 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
   40171 # define sqlite3WalCallback(z)                   0
   40172 # define sqlite3WalExclusiveMode(y,z)            0
   40173 # define sqlite3WalHeapMemory(z)                 0
   40174 # define sqlite3WalFramesize(z)                  0
   40175 # define sqlite3WalFindFrame(x,y,z)              0
   40176 #else
   40177 
   40178 #define WAL_SAVEPOINT_NDATA 4
   40179 
   40180 /* Connection to a write-ahead log (WAL) file.
   40181 ** There is one object of this type for each pager.
   40182 */
   40183 typedef struct Wal Wal;
   40184 
   40185 /* Open and close a connection to a write-ahead log. */
   40186 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
   40187 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
   40188 
   40189 /* Set the limiting size of a WAL file. */
   40190 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
   40191 
   40192 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
   40193 ** snapshot is like a read-transaction.  It is the state of the database
   40194 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
   40195 ** preserves the current state even if the other threads or processes
   40196 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
   40197 ** transaction and releases the lock.
   40198 */
   40199 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
   40200 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
   40201 
   40202 /* Read a page from the write-ahead log, if it is present. */
   40203 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
   40204 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
   40205 
   40206 /* If the WAL is not empty, return the size of the database. */
   40207 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
   40208 
   40209 /* Obtain or release the WRITER lock. */
   40210 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
   40211 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
   40212 
   40213 /* Undo any frames written (but not committed) to the log */
   40214 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
   40215 
   40216 /* Return an integer that records the current (uncommitted) write
   40217 ** position in the WAL */
   40218 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
   40219 
   40220 /* Move the write position of the WAL back to iFrame.  Called in
   40221 ** response to a ROLLBACK TO command. */
   40222 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
   40223 
   40224 /* Write a frame or frames to the log. */
   40225 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
   40226 
   40227 /* Copy pages from the log to the database file */
   40228 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   40229   Wal *pWal,                      /* Write-ahead log connection */
   40230   int eMode,                      /* One of PASSIVE, FULL and RESTART */
   40231   int (*xBusy)(void*),            /* Function to call when busy */
   40232   void *pBusyArg,                 /* Context argument for xBusyHandler */
   40233   int sync_flags,                 /* Flags to sync db file with (or 0) */
   40234   int nBuf,                       /* Size of buffer nBuf */
   40235   u8 *zBuf,                       /* Temporary buffer to use */
   40236   int *pnLog,                     /* OUT: Number of frames in WAL */
   40237   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   40238 );
   40239 
   40240 /* Return the value to pass to a sqlite3_wal_hook callback, the
   40241 ** number of frames in the WAL at the point of the last commit since
   40242 ** sqlite3WalCallback() was called.  If no commits have occurred since
   40243 ** the last call, then return 0.
   40244 */
   40245 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
   40246 
   40247 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
   40248 ** by the pager layer on the database file.
   40249 */
   40250 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
   40251 
   40252 /* Return true if the argument is non-NULL and the WAL module is using
   40253 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   40254 ** WAL module is using shared-memory, return false.
   40255 */
   40256 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
   40257 
   40258 #ifdef SQLITE_ENABLE_ZIPVFS
   40259 /* If the WAL file is not empty, return the number of bytes of content
   40260 ** stored in each frame (i.e. the db page-size when the WAL was created).
   40261 */
   40262 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
   40263 #endif
   40264 
   40265 #endif /* ifndef SQLITE_OMIT_WAL */
   40266 #endif /* _WAL_H_ */
   40267 
   40268 /************** End of wal.h *************************************************/
   40269 /************** Continuing where we left off in pager.c **********************/
   40270 
   40271 
   40272 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
   40273 **
   40274 ** This comment block describes invariants that hold when using a rollback
   40275 ** journal.  These invariants do not apply for journal_mode=WAL,
   40276 ** journal_mode=MEMORY, or journal_mode=OFF.
   40277 **
   40278 ** Within this comment block, a page is deemed to have been synced
   40279 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
   40280 ** Otherwise, the page is not synced until the xSync method of the VFS
   40281 ** is called successfully on the file containing the page.
   40282 **
   40283 ** Definition:  A page of the database file is said to be "overwriteable" if
   40284 ** one or more of the following are true about the page:
   40285 **
   40286 **     (a)  The original content of the page as it was at the beginning of
   40287 **          the transaction has been written into the rollback journal and
   40288 **          synced.
   40289 **
   40290 **     (b)  The page was a freelist leaf page at the start of the transaction.
   40291 **
   40292 **     (c)  The page number is greater than the largest page that existed in
   40293 **          the database file at the start of the transaction.
   40294 **
   40295 ** (1) A page of the database file is never overwritten unless one of the
   40296 **     following are true:
   40297 **
   40298 **     (a) The page and all other pages on the same sector are overwriteable.
   40299 **
   40300 **     (b) The atomic page write optimization is enabled, and the entire
   40301 **         transaction other than the update of the transaction sequence
   40302 **         number consists of a single page change.
   40303 **
   40304 ** (2) The content of a page written into the rollback journal exactly matches
   40305 **     both the content in the database when the rollback journal was written
   40306 **     and the content in the database at the beginning of the current
   40307 **     transaction.
   40308 **
   40309 ** (3) Writes to the database file are an integer multiple of the page size
   40310 **     in length and are aligned on a page boundary.
   40311 **
   40312 ** (4) Reads from the database file are either aligned on a page boundary and
   40313 **     an integer multiple of the page size in length or are taken from the
   40314 **     first 100 bytes of the database file.
   40315 **
   40316 ** (5) All writes to the database file are synced prior to the rollback journal
   40317 **     being deleted, truncated, or zeroed.
   40318 **
   40319 ** (6) If a master journal file is used, then all writes to the database file
   40320 **     are synced prior to the master journal being deleted.
   40321 **
   40322 ** Definition: Two databases (or the same database at two points it time)
   40323 ** are said to be "logically equivalent" if they give the same answer to
   40324 ** all queries.  Note in particular the content of freelist leaf
   40325 ** pages can be changed arbitarily without effecting the logical equivalence
   40326 ** of the database.
   40327 **
   40328 ** (7) At any time, if any subset, including the empty set and the total set,
   40329 **     of the unsynced changes to a rollback journal are removed and the
   40330 **     journal is rolled back, the resulting database file will be logical
   40331 **     equivalent to the database file at the beginning of the transaction.
   40332 **
   40333 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
   40334 **     is called to restore the database file to the same size it was at
   40335 **     the beginning of the transaction.  (In some VFSes, the xTruncate
   40336 **     method is a no-op, but that does not change the fact the SQLite will
   40337 **     invoke it.)
   40338 **
   40339 ** (9) Whenever the database file is modified, at least one bit in the range
   40340 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
   40341 **     the EXCLUSIVE lock, thus signaling other connections on the same
   40342 **     database to flush their caches.
   40343 **
   40344 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
   40345 **      than one billion transactions.
   40346 **
   40347 ** (11) A database file is well-formed at the beginning and at the conclusion
   40348 **      of every transaction.
   40349 **
   40350 ** (12) An EXCLUSIVE lock is held on the database file when writing to
   40351 **      the database file.
   40352 **
   40353 ** (13) A SHARED lock is held on the database file while reading any
   40354 **      content out of the database file.
   40355 **
   40356 ******************************************************************************/
   40357 
   40358 /*
   40359 ** Macros for troubleshooting.  Normally turned off
   40360 */
   40361 #if 0
   40362 int sqlite3PagerTrace=1;  /* True to enable tracing */
   40363 #define sqlite3DebugPrintf printf
   40364 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
   40365 #else
   40366 #define PAGERTRACE(X)
   40367 #endif
   40368 
   40369 /*
   40370 ** The following two macros are used within the PAGERTRACE() macros above
   40371 ** to print out file-descriptors.
   40372 **
   40373 ** PAGERID() takes a pointer to a Pager struct as its argument. The
   40374 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
   40375 ** struct as its argument.
   40376 */
   40377 #define PAGERID(p) ((int)(p->fd))
   40378 #define FILEHANDLEID(fd) ((int)fd)
   40379 
   40380 /*
   40381 ** The Pager.eState variable stores the current 'state' of a pager. A
   40382 ** pager may be in any one of the seven states shown in the following
   40383 ** state diagram.
   40384 **
   40385 **                            OPEN <------+------+
   40386 **                              |         |      |
   40387 **                              V         |      |
   40388 **               +---------> READER-------+      |
   40389 **               |              |                |
   40390 **               |              V                |
   40391 **               |<-------WRITER_LOCKED------> ERROR
   40392 **               |              |                ^
   40393 **               |              V                |
   40394 **               |<------WRITER_CACHEMOD-------->|
   40395 **               |              |                |
   40396 **               |              V                |
   40397 **               |<-------WRITER_DBMOD---------->|
   40398 **               |              |                |
   40399 **               |              V                |
   40400 **               +<------WRITER_FINISHED-------->+
   40401 **
   40402 **
   40403 ** List of state transitions and the C [function] that performs each:
   40404 **
   40405 **   OPEN              -> READER              [sqlite3PagerSharedLock]
   40406 **   READER            -> OPEN                [pager_unlock]
   40407 **
   40408 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
   40409 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
   40410 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
   40411 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
   40412 **   WRITER_***        -> READER              [pager_end_transaction]
   40413 **
   40414 **   WRITER_***        -> ERROR               [pager_error]
   40415 **   ERROR             -> OPEN                [pager_unlock]
   40416 **
   40417 **
   40418 **  OPEN:
   40419 **
   40420 **    The pager starts up in this state. Nothing is guaranteed in this
   40421 **    state - the file may or may not be locked and the database size is
   40422 **    unknown. The database may not be read or written.
   40423 **
   40424 **    * No read or write transaction is active.
   40425 **    * Any lock, or no lock at all, may be held on the database file.
   40426 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
   40427 **
   40428 **  READER:
   40429 **
   40430 **    In this state all the requirements for reading the database in
   40431 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
   40432 **    was) in exclusive-locking mode, a user-level read transaction is
   40433 **    open. The database size is known in this state.
   40434 **
   40435 **    A connection running with locking_mode=normal enters this state when
   40436 **    it opens a read-transaction on the database and returns to state
   40437 **    OPEN after the read-transaction is completed. However a connection
   40438 **    running in locking_mode=exclusive (including temp databases) remains in
   40439 **    this state even after the read-transaction is closed. The only way
   40440 **    a locking_mode=exclusive connection can transition from READER to OPEN
   40441 **    is via the ERROR state (see below).
   40442 **
   40443 **    * A read transaction may be active (but a write-transaction cannot).
   40444 **    * A SHARED or greater lock is held on the database file.
   40445 **    * The dbSize variable may be trusted (even if a user-level read
   40446 **      transaction is not active). The dbOrigSize and dbFileSize variables
   40447 **      may not be trusted at this point.
   40448 **    * If the database is a WAL database, then the WAL connection is open.
   40449 **    * Even if a read-transaction is not open, it is guaranteed that
   40450 **      there is no hot-journal in the file-system.
   40451 **
   40452 **  WRITER_LOCKED:
   40453 **
   40454 **    The pager moves to this state from READER when a write-transaction
   40455 **    is first opened on the database. In WRITER_LOCKED state, all locks
   40456 **    required to start a write-transaction are held, but no actual
   40457 **    modifications to the cache or database have taken place.
   40458 **
   40459 **    In rollback mode, a RESERVED or (if the transaction was opened with
   40460 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
   40461 **    moving to this state, but the journal file is not written to or opened
   40462 **    to in this state. If the transaction is committed or rolled back while
   40463 **    in WRITER_LOCKED state, all that is required is to unlock the database
   40464 **    file.
   40465 **
   40466 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
   40467 **    If the connection is running with locking_mode=exclusive, an attempt
   40468 **    is made to obtain an EXCLUSIVE lock on the database file.
   40469 **
   40470 **    * A write transaction is active.
   40471 **    * If the connection is open in rollback-mode, a RESERVED or greater
   40472 **      lock is held on the database file.
   40473 **    * If the connection is open in WAL-mode, a WAL write transaction
   40474 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
   40475 **      called).
   40476 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
   40477 **    * The contents of the pager cache have not been modified.
   40478 **    * The journal file may or may not be open.
   40479 **    * Nothing (not even the first header) has been written to the journal.
   40480 **
   40481 **  WRITER_CACHEMOD:
   40482 **
   40483 **    A pager moves from WRITER_LOCKED state to this state when a page is
   40484 **    first modified by the upper layer. In rollback mode the journal file
   40485 **    is opened (if it is not already open) and a header written to the
   40486 **    start of it. The database file on disk has not been modified.
   40487 **
   40488 **    * A write transaction is active.
   40489 **    * A RESERVED or greater lock is held on the database file.
   40490 **    * The journal file is open and the first header has been written
   40491 **      to it, but the header has not been synced to disk.
   40492 **    * The contents of the page cache have been modified.
   40493 **
   40494 **  WRITER_DBMOD:
   40495 **
   40496 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
   40497 **    when it modifies the contents of the database file. WAL connections
   40498 **    never enter this state (since they do not modify the database file,
   40499 **    just the log file).
   40500 **
   40501 **    * A write transaction is active.
   40502 **    * An EXCLUSIVE or greater lock is held on the database file.
   40503 **    * The journal file is open and the first header has been written
   40504 **      and synced to disk.
   40505 **    * The contents of the page cache have been modified (and possibly
   40506 **      written to disk).
   40507 **
   40508 **  WRITER_FINISHED:
   40509 **
   40510 **    It is not possible for a WAL connection to enter this state.
   40511 **
   40512 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
   40513 **    state after the entire transaction has been successfully written into the
   40514 **    database file. In this state the transaction may be committed simply
   40515 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
   40516 **    not possible to modify the database further. At this point, the upper
   40517 **    layer must either commit or rollback the transaction.
   40518 **
   40519 **    * A write transaction is active.
   40520 **    * An EXCLUSIVE or greater lock is held on the database file.
   40521 **    * All writing and syncing of journal and database data has finished.
   40522 **      If no error occurred, all that remains is to finalize the journal to
   40523 **      commit the transaction. If an error did occur, the caller will need
   40524 **      to rollback the transaction.
   40525 **
   40526 **  ERROR:
   40527 **
   40528 **    The ERROR state is entered when an IO or disk-full error (including
   40529 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
   40530 **    difficult to be sure that the in-memory pager state (cache contents,
   40531 **    db size etc.) are consistent with the contents of the file-system.
   40532 **
   40533 **    Temporary pager files may enter the ERROR state, but in-memory pagers
   40534 **    cannot.
   40535 **
   40536 **    For example, if an IO error occurs while performing a rollback,
   40537 **    the contents of the page-cache may be left in an inconsistent state.
   40538 **    At this point it would be dangerous to change back to READER state
   40539 **    (as usually happens after a rollback). Any subsequent readers might
   40540 **    report database corruption (due to the inconsistent cache), and if
   40541 **    they upgrade to writers, they may inadvertently corrupt the database
   40542 **    file. To avoid this hazard, the pager switches into the ERROR state
   40543 **    instead of READER following such an error.
   40544 **
   40545 **    Once it has entered the ERROR state, any attempt to use the pager
   40546 **    to read or write data returns an error. Eventually, once all
   40547 **    outstanding transactions have been abandoned, the pager is able to
   40548 **    transition back to OPEN state, discarding the contents of the
   40549 **    page-cache and any other in-memory state at the same time. Everything
   40550 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
   40551 **    when a read-transaction is next opened on the pager (transitioning
   40552 **    the pager into READER state). At that point the system has recovered
   40553 **    from the error.
   40554 **
   40555 **    Specifically, the pager jumps into the ERROR state if:
   40556 **
   40557 **      1. An error occurs while attempting a rollback. This happens in
   40558 **         function sqlite3PagerRollback().
   40559 **
   40560 **      2. An error occurs while attempting to finalize a journal file
   40561 **         following a commit in function sqlite3PagerCommitPhaseTwo().
   40562 **
   40563 **      3. An error occurs while attempting to write to the journal or
   40564 **         database file in function pagerStress() in order to free up
   40565 **         memory.
   40566 **
   40567 **    In other cases, the error is returned to the b-tree layer. The b-tree
   40568 **    layer then attempts a rollback operation. If the error condition
   40569 **    persists, the pager enters the ERROR state via condition (1) above.
   40570 **
   40571 **    Condition (3) is necessary because it can be triggered by a read-only
   40572 **    statement executed within a transaction. In this case, if the error
   40573 **    code were simply returned to the user, the b-tree layer would not
   40574 **    automatically attempt a rollback, as it assumes that an error in a
   40575 **    read-only statement cannot leave the pager in an internally inconsistent
   40576 **    state.
   40577 **
   40578 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
   40579 **    * There are one or more outstanding references to pages (after the
   40580 **      last reference is dropped the pager should move back to OPEN state).
   40581 **    * The pager is not an in-memory pager.
   40582 **
   40583 **
   40584 ** Notes:
   40585 **
   40586 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
   40587 **     connection is open in WAL mode. A WAL connection is always in one
   40588 **     of the first four states.
   40589 **
   40590 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
   40591 **     state. There are two exceptions: immediately after exclusive-mode has
   40592 **     been turned on (and before any read or write transactions are
   40593 **     executed), and when the pager is leaving the "error state".
   40594 **
   40595 **   * See also: assert_pager_state().
   40596 */
   40597 #define PAGER_OPEN                  0
   40598 #define PAGER_READER                1
   40599 #define PAGER_WRITER_LOCKED         2
   40600 #define PAGER_WRITER_CACHEMOD       3
   40601 #define PAGER_WRITER_DBMOD          4
   40602 #define PAGER_WRITER_FINISHED       5
   40603 #define PAGER_ERROR                 6
   40604 
   40605 /*
   40606 ** The Pager.eLock variable is almost always set to one of the
   40607 ** following locking-states, according to the lock currently held on
   40608 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   40609 ** This variable is kept up to date as locks are taken and released by
   40610 ** the pagerLockDb() and pagerUnlockDb() wrappers.
   40611 **
   40612 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
   40613 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
   40614 ** the operation was successful. In these circumstances pagerLockDb() and
   40615 ** pagerUnlockDb() take a conservative approach - eLock is always updated
   40616 ** when unlocking the file, and only updated when locking the file if the
   40617 ** VFS call is successful. This way, the Pager.eLock variable may be set
   40618 ** to a less exclusive (lower) value than the lock that is actually held
   40619 ** at the system level, but it is never set to a more exclusive value.
   40620 **
   40621 ** This is usually safe. If an xUnlock fails or appears to fail, there may
   40622 ** be a few redundant xLock() calls or a lock may be held for longer than
   40623 ** required, but nothing really goes wrong.
   40624 **
   40625 ** The exception is when the database file is unlocked as the pager moves
   40626 ** from ERROR to OPEN state. At this point there may be a hot-journal file
   40627 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
   40628 ** transition, by the same pager or any other). If the call to xUnlock()
   40629 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
   40630 ** can confuse the call to xCheckReservedLock() call made later as part
   40631 ** of hot-journal detection.
   40632 **
   40633 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
   40634 ** lock held by this process or any others". So xCheckReservedLock may
   40635 ** return true because the caller itself is holding an EXCLUSIVE lock (but
   40636 ** doesn't know it because of a previous error in xUnlock). If this happens
   40637 ** a hot-journal may be mistaken for a journal being created by an active
   40638 ** transaction in another process, causing SQLite to read from the database
   40639 ** without rolling it back.
   40640 **
   40641 ** To work around this, if a call to xUnlock() fails when unlocking the
   40642 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
   40643 ** is only changed back to a real locking state after a successful call
   40644 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
   40645 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
   40646 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
   40647 ** lock on the database file before attempting to roll it back. See function
   40648 ** PagerSharedLock() for more detail.
   40649 **
   40650 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
   40651 ** PAGER_OPEN state.
   40652 */
   40653 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
   40654 
   40655 /*
   40656 ** A macro used for invoking the codec if there is one
   40657 */
   40658 #ifdef SQLITE_HAS_CODEC
   40659 # define CODEC1(P,D,N,X,E) \
   40660     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
   40661 # define CODEC2(P,D,N,X,E,O) \
   40662     if( P->xCodec==0 ){ O=(char*)D; }else \
   40663     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
   40664 #else
   40665 # define CODEC1(P,D,N,X,E)   /* NO-OP */
   40666 # define CODEC2(P,D,N,X,E,O) O=(char*)D
   40667 #endif
   40668 
   40669 /*
   40670 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
   40671 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
   40672 ** This could conceivably cause corruption following a power failure on
   40673 ** such a system. This is currently an undocumented limit.
   40674 */
   40675 #define MAX_SECTOR_SIZE 0x10000
   40676 
   40677 /*
   40678 ** An instance of the following structure is allocated for each active
   40679 ** savepoint and statement transaction in the system. All such structures
   40680 ** are stored in the Pager.aSavepoint[] array, which is allocated and
   40681 ** resized using sqlite3Realloc().
   40682 **
   40683 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
   40684 ** set to 0. If a journal-header is written into the main journal while
   40685 ** the savepoint is active, then iHdrOffset is set to the byte offset
   40686 ** immediately following the last journal record written into the main
   40687 ** journal before the journal-header. This is required during savepoint
   40688 ** rollback (see pagerPlaybackSavepoint()).
   40689 */
   40690 typedef struct PagerSavepoint PagerSavepoint;
   40691 struct PagerSavepoint {
   40692   i64 iOffset;                 /* Starting offset in main journal */
   40693   i64 iHdrOffset;              /* See above */
   40694   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
   40695   Pgno nOrig;                  /* Original number of pages in file */
   40696   Pgno iSubRec;                /* Index of first record in sub-journal */
   40697 #ifndef SQLITE_OMIT_WAL
   40698   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
   40699 #endif
   40700 };
   40701 
   40702 /*
   40703 ** Bits of the Pager.doNotSpill flag.  See further description below.
   40704 */
   40705 #define SPILLFLAG_OFF         0x01      /* Never spill cache.  Set via pragma */
   40706 #define SPILLFLAG_ROLLBACK    0x02      /* Current rolling back, so do not spill */
   40707 #define SPILLFLAG_NOSYNC      0x04      /* Spill is ok, but do not sync */
   40708 
   40709 /*
   40710 ** A open page cache is an instance of struct Pager. A description of
   40711 ** some of the more important member variables follows:
   40712 **
   40713 ** eState
   40714 **
   40715 **   The current 'state' of the pager object. See the comment and state
   40716 **   diagram above for a description of the pager state.
   40717 **
   40718 ** eLock
   40719 **
   40720 **   For a real on-disk database, the current lock held on the database file -
   40721 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   40722 **
   40723 **   For a temporary or in-memory database (neither of which require any
   40724 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
   40725 **   databases always have Pager.exclusiveMode==1, this tricks the pager
   40726 **   logic into thinking that it already has all the locks it will ever
   40727 **   need (and no reason to release them).
   40728 **
   40729 **   In some (obscure) circumstances, this variable may also be set to
   40730 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
   40731 **   details.
   40732 **
   40733 ** changeCountDone
   40734 **
   40735 **   This boolean variable is used to make sure that the change-counter
   40736 **   (the 4-byte header field at byte offset 24 of the database file) is
   40737 **   not updated more often than necessary.
   40738 **
   40739 **   It is set to true when the change-counter field is updated, which
   40740 **   can only happen if an exclusive lock is held on the database file.
   40741 **   It is cleared (set to false) whenever an exclusive lock is
   40742 **   relinquished on the database file. Each time a transaction is committed,
   40743 **   The changeCountDone flag is inspected. If it is true, the work of
   40744 **   updating the change-counter is omitted for the current transaction.
   40745 **
   40746 **   This mechanism means that when running in exclusive mode, a connection
   40747 **   need only update the change-counter once, for the first transaction
   40748 **   committed.
   40749 **
   40750 ** setMaster
   40751 **
   40752 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
   40753 **   (or may not) specify a master-journal name to be written into the
   40754 **   journal file before it is synced to disk.
   40755 **
   40756 **   Whether or not a journal file contains a master-journal pointer affects
   40757 **   the way in which the journal file is finalized after the transaction is
   40758 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
   40759 **   If a journal file does not contain a master-journal pointer, it is
   40760 **   finalized by overwriting the first journal header with zeroes. If
   40761 **   it does contain a master-journal pointer the journal file is finalized
   40762 **   by truncating it to zero bytes, just as if the connection were
   40763 **   running in "journal_mode=truncate" mode.
   40764 **
   40765 **   Journal files that contain master journal pointers cannot be finalized
   40766 **   simply by overwriting the first journal-header with zeroes, as the
   40767 **   master journal pointer could interfere with hot-journal rollback of any
   40768 **   subsequently interrupted transaction that reuses the journal file.
   40769 **
   40770 **   The flag is cleared as soon as the journal file is finalized (either
   40771 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
   40772 **   journal file from being successfully finalized, the setMaster flag
   40773 **   is cleared anyway (and the pager will move to ERROR state).
   40774 **
   40775 ** doNotSpill
   40776 **
   40777 **   This variables control the behavior of cache-spills  (calls made by
   40778 **   the pcache module to the pagerStress() routine to write cached data
   40779 **   to the file-system in order to free up memory).
   40780 **
   40781 **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
   40782 **   writing to the database from pagerStress() is disabled altogether.
   40783 **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
   40784 **   comes up during savepoint rollback that requires the pcache module
   40785 **   to allocate a new page to prevent the journal file from being written
   40786 **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
   40787 **   case is a user preference.
   40788 **
   40789 **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
   40790 **   is permitted, but syncing the journal file is not. This flag is set
   40791 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
   40792 **   the database page-size in order to prevent a journal sync from happening
   40793 **   in between the journalling of two pages on the same sector.
   40794 **
   40795 ** subjInMemory
   40796 **
   40797 **   This is a boolean variable. If true, then any required sub-journal
   40798 **   is opened as an in-memory journal file. If false, then in-memory
   40799 **   sub-journals are only used for in-memory pager files.
   40800 **
   40801 **   This variable is updated by the upper layer each time a new
   40802 **   write-transaction is opened.
   40803 **
   40804 ** dbSize, dbOrigSize, dbFileSize
   40805 **
   40806 **   Variable dbSize is set to the number of pages in the database file.
   40807 **   It is valid in PAGER_READER and higher states (all states except for
   40808 **   OPEN and ERROR).
   40809 **
   40810 **   dbSize is set based on the size of the database file, which may be
   40811 **   larger than the size of the database (the value stored at offset
   40812 **   28 of the database header by the btree). If the size of the file
   40813 **   is not an integer multiple of the page-size, the value stored in
   40814 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
   40815 **   Except, any file that is greater than 0 bytes in size is considered
   40816 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
   40817 **   to dbSize==1).
   40818 **
   40819 **   During a write-transaction, if pages with page-numbers greater than
   40820 **   dbSize are modified in the cache, dbSize is updated accordingly.
   40821 **   Similarly, if the database is truncated using PagerTruncateImage(),
   40822 **   dbSize is updated.
   40823 **
   40824 **   Variables dbOrigSize and dbFileSize are valid in states
   40825 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
   40826 **   variable at the start of the transaction. It is used during rollback,
   40827 **   and to determine whether or not pages need to be journalled before
   40828 **   being modified.
   40829 **
   40830 **   Throughout a write-transaction, dbFileSize contains the size of
   40831 **   the file on disk in pages. It is set to a copy of dbSize when the
   40832 **   write-transaction is first opened, and updated when VFS calls are made
   40833 **   to write or truncate the database file on disk.
   40834 **
   40835 **   The only reason the dbFileSize variable is required is to suppress
   40836 **   unnecessary calls to xTruncate() after committing a transaction. If,
   40837 **   when a transaction is committed, the dbFileSize variable indicates
   40838 **   that the database file is larger than the database image (Pager.dbSize),
   40839 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
   40840 **   to measure the database file on disk, and then truncates it if required.
   40841 **   dbFileSize is not used when rolling back a transaction. In this case
   40842 **   pager_truncate() is called unconditionally (which means there may be
   40843 **   a call to xFilesize() that is not strictly required). In either case,
   40844 **   pager_truncate() may cause the file to become smaller or larger.
   40845 **
   40846 ** dbHintSize
   40847 **
   40848 **   The dbHintSize variable is used to limit the number of calls made to
   40849 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
   40850 **
   40851 **   dbHintSize is set to a copy of the dbSize variable when a
   40852 **   write-transaction is opened (at the same time as dbFileSize and
   40853 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
   40854 **   dbHintSize is increased to the number of pages that correspond to the
   40855 **   size-hint passed to the method call. See pager_write_pagelist() for
   40856 **   details.
   40857 **
   40858 ** errCode
   40859 **
   40860 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
   40861 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
   40862 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
   40863 **   sub-codes.
   40864 */
   40865 struct Pager {
   40866   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
   40867   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
   40868   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
   40869   u8 useJournal;              /* Use a rollback journal on this file */
   40870   u8 noSync;                  /* Do not sync the journal if true */
   40871   u8 fullSync;                /* Do extra syncs of the journal for robustness */
   40872   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
   40873   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
   40874   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
   40875   u8 tempFile;                /* zFilename is a temporary or immutable file */
   40876   u8 noLock;                  /* Do not lock (except in WAL mode) */
   40877   u8 readOnly;                /* True for a read-only database */
   40878   u8 memDb;                   /* True to inhibit all file I/O */
   40879 
   40880   /**************************************************************************
   40881   ** The following block contains those class members that change during
   40882   ** routine opertion.  Class members not in this block are either fixed
   40883   ** when the pager is first created or else only change when there is a
   40884   ** significant mode change (such as changing the page_size, locking_mode,
   40885   ** or the journal_mode).  From another view, these class members describe
   40886   ** the "state" of the pager, while other class members describe the
   40887   ** "configuration" of the pager.
   40888   */
   40889   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
   40890   u8 eLock;                   /* Current lock held on database file */
   40891   u8 changeCountDone;         /* Set after incrementing the change-counter */
   40892   u8 setMaster;               /* True if a m-j name has been written to jrnl */
   40893   u8 doNotSpill;              /* Do not spill the cache when non-zero */
   40894   u8 subjInMemory;            /* True to use in-memory sub-journals */
   40895   Pgno dbSize;                /* Number of pages in the database */
   40896   Pgno dbOrigSize;            /* dbSize before the current transaction */
   40897   Pgno dbFileSize;            /* Number of pages in the database file */
   40898   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
   40899   int errCode;                /* One of several kinds of errors */
   40900   int nRec;                   /* Pages journalled since last j-header written */
   40901   u32 cksumInit;              /* Quasi-random value added to every checksum */
   40902   u32 nSubRec;                /* Number of records written to sub-journal */
   40903   Bitvec *pInJournal;         /* One bit for each page in the database file */
   40904   sqlite3_file *fd;           /* File descriptor for database */
   40905   sqlite3_file *jfd;          /* File descriptor for main journal */
   40906   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
   40907   i64 journalOff;             /* Current write offset in the journal file */
   40908   i64 journalHdr;             /* Byte offset to previous journal header */
   40909   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
   40910   PagerSavepoint *aSavepoint; /* Array of active savepoints */
   40911   int nSavepoint;             /* Number of elements in aSavepoint[] */
   40912   char dbFileVers[16];        /* Changes whenever database file changes */
   40913 
   40914   u8 bUseFetch;               /* True to use xFetch() */
   40915   int nMmapOut;               /* Number of mmap pages currently outstanding */
   40916   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
   40917   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
   40918   /*
   40919   ** End of the routinely-changing class members
   40920   ***************************************************************************/
   40921 
   40922   u16 nExtra;                 /* Add this many bytes to each in-memory page */
   40923   i16 nReserve;               /* Number of unused bytes at end of each page */
   40924   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
   40925   u32 sectorSize;             /* Assumed sector size during rollback */
   40926   int pageSize;               /* Number of bytes in a page */
   40927   Pgno mxPgno;                /* Maximum allowed size of the database */
   40928   i64 journalSizeLimit;       /* Size limit for persistent journal files */
   40929   char *zFilename;            /* Name of the database file */
   40930   char *zJournal;             /* Name of the journal file */
   40931   int (*xBusyHandler)(void*); /* Function to call when busy */
   40932   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
   40933   int aStat[3];               /* Total cache hits, misses and writes */
   40934 #ifdef SQLITE_TEST
   40935   int nRead;                  /* Database pages read */
   40936 #endif
   40937   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
   40938 #ifdef SQLITE_HAS_CODEC
   40939   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
   40940   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
   40941   void (*xCodecFree)(void*);             /* Destructor for the codec */
   40942   void *pCodec;               /* First argument to xCodec... methods */
   40943 #endif
   40944   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
   40945   PCache *pPCache;            /* Pointer to page cache object */
   40946 #ifndef SQLITE_OMIT_WAL
   40947   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
   40948   char *zWal;                 /* File name for write-ahead log */
   40949 #endif
   40950 };
   40951 
   40952 /*
   40953 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
   40954 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
   40955 ** or CACHE_WRITE to sqlite3_db_status().
   40956 */
   40957 #define PAGER_STAT_HIT   0
   40958 #define PAGER_STAT_MISS  1
   40959 #define PAGER_STAT_WRITE 2
   40960 
   40961 /*
   40962 ** The following global variables hold counters used for
   40963 ** testing purposes only.  These variables do not exist in
   40964 ** a non-testing build.  These variables are not thread-safe.
   40965 */
   40966 #ifdef SQLITE_TEST
   40967 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
   40968 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
   40969 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
   40970 # define PAGER_INCR(v)  v++
   40971 #else
   40972 # define PAGER_INCR(v)
   40973 #endif
   40974 
   40975 
   40976 
   40977 /*
   40978 ** Journal files begin with the following magic string.  The data
   40979 ** was obtained from /dev/random.  It is used only as a sanity check.
   40980 **
   40981 ** Since version 2.8.0, the journal format contains additional sanity
   40982 ** checking information.  If the power fails while the journal is being
   40983 ** written, semi-random garbage data might appear in the journal
   40984 ** file after power is restored.  If an attempt is then made
   40985 ** to roll the journal back, the database could be corrupted.  The additional
   40986 ** sanity checking data is an attempt to discover the garbage in the
   40987 ** journal and ignore it.
   40988 **
   40989 ** The sanity checking information for the new journal format consists
   40990 ** of a 32-bit checksum on each page of data.  The checksum covers both
   40991 ** the page number and the pPager->pageSize bytes of data for the page.
   40992 ** This cksum is initialized to a 32-bit random value that appears in the
   40993 ** journal file right after the header.  The random initializer is important,
   40994 ** because garbage data that appears at the end of a journal is likely
   40995 ** data that was once in other files that have now been deleted.  If the
   40996 ** garbage data came from an obsolete journal file, the checksums might
   40997 ** be correct.  But by initializing the checksum to random value which
   40998 ** is different for every journal, we minimize that risk.
   40999 */
   41000 static const unsigned char aJournalMagic[] = {
   41001   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
   41002 };
   41003 
   41004 /*
   41005 ** The size of the of each page record in the journal is given by
   41006 ** the following macro.
   41007 */
   41008 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
   41009 
   41010 /*
   41011 ** The journal header size for this pager. This is usually the same
   41012 ** size as a single disk sector. See also setSectorSize().
   41013 */
   41014 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
   41015 
   41016 /*
   41017 ** The macro MEMDB is true if we are dealing with an in-memory database.
   41018 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
   41019 ** the value of MEMDB will be a constant and the compiler will optimize
   41020 ** out code that would never execute.
   41021 */
   41022 #ifdef SQLITE_OMIT_MEMORYDB
   41023 # define MEMDB 0
   41024 #else
   41025 # define MEMDB pPager->memDb
   41026 #endif
   41027 
   41028 /*
   41029 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
   41030 ** interfaces to access the database using memory-mapped I/O.
   41031 */
   41032 #if SQLITE_MAX_MMAP_SIZE>0
   41033 # define USEFETCH(x) ((x)->bUseFetch)
   41034 #else
   41035 # define USEFETCH(x) 0
   41036 #endif
   41037 
   41038 /*
   41039 ** The maximum legal page number is (2^31 - 1).
   41040 */
   41041 #define PAGER_MAX_PGNO 2147483647
   41042 
   41043 /*
   41044 ** The argument to this macro is a file descriptor (type sqlite3_file*).
   41045 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
   41046 **
   41047 ** This is so that expressions can be written as:
   41048 **
   41049 **   if( isOpen(pPager->jfd) ){ ...
   41050 **
   41051 ** instead of
   41052 **
   41053 **   if( pPager->jfd->pMethods ){ ...
   41054 */
   41055 #define isOpen(pFd) ((pFd)->pMethods)
   41056 
   41057 /*
   41058 ** Return true if this pager uses a write-ahead log instead of the usual
   41059 ** rollback journal. Otherwise false.
   41060 */
   41061 #ifndef SQLITE_OMIT_WAL
   41062 static int pagerUseWal(Pager *pPager){
   41063   return (pPager->pWal!=0);
   41064 }
   41065 #else
   41066 # define pagerUseWal(x) 0
   41067 # define pagerRollbackWal(x) 0
   41068 # define pagerWalFrames(v,w,x,y) 0
   41069 # define pagerOpenWalIfPresent(z) SQLITE_OK
   41070 # define pagerBeginReadTransaction(z) SQLITE_OK
   41071 #endif
   41072 
   41073 #ifndef NDEBUG
   41074 /*
   41075 ** Usage:
   41076 **
   41077 **   assert( assert_pager_state(pPager) );
   41078 **
   41079 ** This function runs many asserts to try to find inconsistencies in
   41080 ** the internal state of the Pager object.
   41081 */
   41082 static int assert_pager_state(Pager *p){
   41083   Pager *pPager = p;
   41084 
   41085   /* State must be valid. */
   41086   assert( p->eState==PAGER_OPEN
   41087        || p->eState==PAGER_READER
   41088        || p->eState==PAGER_WRITER_LOCKED
   41089        || p->eState==PAGER_WRITER_CACHEMOD
   41090        || p->eState==PAGER_WRITER_DBMOD
   41091        || p->eState==PAGER_WRITER_FINISHED
   41092        || p->eState==PAGER_ERROR
   41093   );
   41094 
   41095   /* Regardless of the current state, a temp-file connection always behaves
   41096   ** as if it has an exclusive lock on the database file. It never updates
   41097   ** the change-counter field, so the changeCountDone flag is always set.
   41098   */
   41099   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
   41100   assert( p->tempFile==0 || pPager->changeCountDone );
   41101 
   41102   /* If the useJournal flag is clear, the journal-mode must be "OFF".
   41103   ** And if the journal-mode is "OFF", the journal file must not be open.
   41104   */
   41105   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
   41106   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
   41107 
   41108   /* Check that MEMDB implies noSync. And an in-memory journal. Since
   41109   ** this means an in-memory pager performs no IO at all, it cannot encounter
   41110   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
   41111   ** a journal file. (although the in-memory journal implementation may
   41112   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
   41113   ** is therefore not possible for an in-memory pager to enter the ERROR
   41114   ** state.
   41115   */
   41116   if( MEMDB ){
   41117     assert( p->noSync );
   41118     assert( p->journalMode==PAGER_JOURNALMODE_OFF
   41119          || p->journalMode==PAGER_JOURNALMODE_MEMORY
   41120     );
   41121     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
   41122     assert( pagerUseWal(p)==0 );
   41123   }
   41124 
   41125   /* If changeCountDone is set, a RESERVED lock or greater must be held
   41126   ** on the file.
   41127   */
   41128   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
   41129   assert( p->eLock!=PENDING_LOCK );
   41130 
   41131   switch( p->eState ){
   41132     case PAGER_OPEN:
   41133       assert( !MEMDB );
   41134       assert( pPager->errCode==SQLITE_OK );
   41135       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
   41136       break;
   41137 
   41138     case PAGER_READER:
   41139       assert( pPager->errCode==SQLITE_OK );
   41140       assert( p->eLock!=UNKNOWN_LOCK );
   41141       assert( p->eLock>=SHARED_LOCK );
   41142       break;
   41143 
   41144     case PAGER_WRITER_LOCKED:
   41145       assert( p->eLock!=UNKNOWN_LOCK );
   41146       assert( pPager->errCode==SQLITE_OK );
   41147       if( !pagerUseWal(pPager) ){
   41148         assert( p->eLock>=RESERVED_LOCK );
   41149       }
   41150       assert( pPager->dbSize==pPager->dbOrigSize );
   41151       assert( pPager->dbOrigSize==pPager->dbFileSize );
   41152       assert( pPager->dbOrigSize==pPager->dbHintSize );
   41153       assert( pPager->setMaster==0 );
   41154       break;
   41155 
   41156     case PAGER_WRITER_CACHEMOD:
   41157       assert( p->eLock!=UNKNOWN_LOCK );
   41158       assert( pPager->errCode==SQLITE_OK );
   41159       if( !pagerUseWal(pPager) ){
   41160         /* It is possible that if journal_mode=wal here that neither the
   41161         ** journal file nor the WAL file are open. This happens during
   41162         ** a rollback transaction that switches from journal_mode=off
   41163         ** to journal_mode=wal.
   41164         */
   41165         assert( p->eLock>=RESERVED_LOCK );
   41166         assert( isOpen(p->jfd)
   41167              || p->journalMode==PAGER_JOURNALMODE_OFF
   41168              || p->journalMode==PAGER_JOURNALMODE_WAL
   41169         );
   41170       }
   41171       assert( pPager->dbOrigSize==pPager->dbFileSize );
   41172       assert( pPager->dbOrigSize==pPager->dbHintSize );
   41173       break;
   41174 
   41175     case PAGER_WRITER_DBMOD:
   41176       assert( p->eLock==EXCLUSIVE_LOCK );
   41177       assert( pPager->errCode==SQLITE_OK );
   41178       assert( !pagerUseWal(pPager) );
   41179       assert( p->eLock>=EXCLUSIVE_LOCK );
   41180       assert( isOpen(p->jfd)
   41181            || p->journalMode==PAGER_JOURNALMODE_OFF
   41182            || p->journalMode==PAGER_JOURNALMODE_WAL
   41183       );
   41184       assert( pPager->dbOrigSize<=pPager->dbHintSize );
   41185       break;
   41186 
   41187     case PAGER_WRITER_FINISHED:
   41188       assert( p->eLock==EXCLUSIVE_LOCK );
   41189       assert( pPager->errCode==SQLITE_OK );
   41190       assert( !pagerUseWal(pPager) );
   41191       assert( isOpen(p->jfd)
   41192            || p->journalMode==PAGER_JOURNALMODE_OFF
   41193            || p->journalMode==PAGER_JOURNALMODE_WAL
   41194       );
   41195       break;
   41196 
   41197     case PAGER_ERROR:
   41198       /* There must be at least one outstanding reference to the pager if
   41199       ** in ERROR state. Otherwise the pager should have already dropped
   41200       ** back to OPEN state.
   41201       */
   41202       assert( pPager->errCode!=SQLITE_OK );
   41203       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
   41204       break;
   41205   }
   41206 
   41207   return 1;
   41208 }
   41209 #endif /* ifndef NDEBUG */
   41210 
   41211 #ifdef SQLITE_DEBUG
   41212 /*
   41213 ** Return a pointer to a human readable string in a static buffer
   41214 ** containing the state of the Pager object passed as an argument. This
   41215 ** is intended to be used within debuggers. For example, as an alternative
   41216 ** to "print *pPager" in gdb:
   41217 **
   41218 ** (gdb) printf "%s", print_pager_state(pPager)
   41219 */
   41220 static char *print_pager_state(Pager *p){
   41221   static char zRet[1024];
   41222 
   41223   sqlite3_snprintf(1024, zRet,
   41224       "Filename:      %s\n"
   41225       "State:         %s errCode=%d\n"
   41226       "Lock:          %s\n"
   41227       "Locking mode:  locking_mode=%s\n"
   41228       "Journal mode:  journal_mode=%s\n"
   41229       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
   41230       "Journal:       journalOff=%lld journalHdr=%lld\n"
   41231       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
   41232       , p->zFilename
   41233       , p->eState==PAGER_OPEN            ? "OPEN" :
   41234         p->eState==PAGER_READER          ? "READER" :
   41235         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
   41236         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
   41237         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
   41238         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
   41239         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
   41240       , (int)p->errCode
   41241       , p->eLock==NO_LOCK         ? "NO_LOCK" :
   41242         p->eLock==RESERVED_LOCK   ? "RESERVED" :
   41243         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
   41244         p->eLock==SHARED_LOCK     ? "SHARED" :
   41245         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
   41246       , p->exclusiveMode ? "exclusive" : "normal"
   41247       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
   41248         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
   41249         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
   41250         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
   41251         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
   41252         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
   41253       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
   41254       , p->journalOff, p->journalHdr
   41255       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
   41256   );
   41257 
   41258   return zRet;
   41259 }
   41260 #endif
   41261 
   41262 /*
   41263 ** Return true if it is necessary to write page *pPg into the sub-journal.
   41264 ** A page needs to be written into the sub-journal if there exists one
   41265 ** or more open savepoints for which:
   41266 **
   41267 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
   41268 **   * The bit corresponding to the page-number is not set in
   41269 **     PagerSavepoint.pInSavepoint.
   41270 */
   41271 static int subjRequiresPage(PgHdr *pPg){
   41272   Pager *pPager = pPg->pPager;
   41273   PagerSavepoint *p;
   41274   Pgno pgno = pPg->pgno;
   41275   int i;
   41276   for(i=0; i<pPager->nSavepoint; i++){
   41277     p = &pPager->aSavepoint[i];
   41278     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
   41279       return 1;
   41280     }
   41281   }
   41282   return 0;
   41283 }
   41284 
   41285 /*
   41286 ** Return true if the page is already in the journal file.
   41287 */
   41288 static int pageInJournal(Pager *pPager, PgHdr *pPg){
   41289   return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
   41290 }
   41291 
   41292 /*
   41293 ** Read a 32-bit integer from the given file descriptor.  Store the integer
   41294 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
   41295 ** error code is something goes wrong.
   41296 **
   41297 ** All values are stored on disk as big-endian.
   41298 */
   41299 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
   41300   unsigned char ac[4];
   41301   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
   41302   if( rc==SQLITE_OK ){
   41303     *pRes = sqlite3Get4byte(ac);
   41304   }
   41305   return rc;
   41306 }
   41307 
   41308 /*
   41309 ** Write a 32-bit integer into a string buffer in big-endian byte order.
   41310 */
   41311 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
   41312 
   41313 
   41314 /*
   41315 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
   41316 ** on success or an error code is something goes wrong.
   41317 */
   41318 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
   41319   char ac[4];
   41320   put32bits(ac, val);
   41321   return sqlite3OsWrite(fd, ac, 4, offset);
   41322 }
   41323 
   41324 /*
   41325 ** Unlock the database file to level eLock, which must be either NO_LOCK
   41326 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
   41327 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
   41328 **
   41329 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   41330 ** called, do not modify it. See the comment above the #define of
   41331 ** UNKNOWN_LOCK for an explanation of this.
   41332 */
   41333 static int pagerUnlockDb(Pager *pPager, int eLock){
   41334   int rc = SQLITE_OK;
   41335 
   41336   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
   41337   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
   41338   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
   41339   if( isOpen(pPager->fd) ){
   41340     assert( pPager->eLock>=eLock );
   41341     rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
   41342     if( pPager->eLock!=UNKNOWN_LOCK ){
   41343       pPager->eLock = (u8)eLock;
   41344     }
   41345     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
   41346   }
   41347   return rc;
   41348 }
   41349 
   41350 /*
   41351 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
   41352 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
   41353 ** Pager.eLock variable to the new locking state.
   41354 **
   41355 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   41356 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
   41357 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
   41358 ** of this.
   41359 */
   41360 static int pagerLockDb(Pager *pPager, int eLock){
   41361   int rc = SQLITE_OK;
   41362 
   41363   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
   41364   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
   41365     rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
   41366     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
   41367       pPager->eLock = (u8)eLock;
   41368       IOTRACE(("LOCK %p %d\n", pPager, eLock))
   41369     }
   41370   }
   41371   return rc;
   41372 }
   41373 
   41374 /*
   41375 ** This function determines whether or not the atomic-write optimization
   41376 ** can be used with this pager. The optimization can be used if:
   41377 **
   41378 **  (a) the value returned by OsDeviceCharacteristics() indicates that
   41379 **      a database page may be written atomically, and
   41380 **  (b) the value returned by OsSectorSize() is less than or equal
   41381 **      to the page size.
   41382 **
   41383 ** The optimization is also always enabled for temporary files. It is
   41384 ** an error to call this function if pPager is opened on an in-memory
   41385 ** database.
   41386 **
   41387 ** If the optimization cannot be used, 0 is returned. If it can be used,
   41388 ** then the value returned is the size of the journal file when it
   41389 ** contains rollback data for exactly one page.
   41390 */
   41391 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   41392 static int jrnlBufferSize(Pager *pPager){
   41393   assert( !MEMDB );
   41394   if( !pPager->tempFile ){
   41395     int dc;                           /* Device characteristics */
   41396     int nSector;                      /* Sector size */
   41397     int szPage;                       /* Page size */
   41398 
   41399     assert( isOpen(pPager->fd) );
   41400     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
   41401     nSector = pPager->sectorSize;
   41402     szPage = pPager->pageSize;
   41403 
   41404     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   41405     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   41406     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
   41407       return 0;
   41408     }
   41409   }
   41410 
   41411   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
   41412 }
   41413 #endif
   41414 
   41415 /*
   41416 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
   41417 ** on the cache using a hash function.  This is used for testing
   41418 ** and debugging only.
   41419 */
   41420 #ifdef SQLITE_CHECK_PAGES
   41421 /*
   41422 ** Return a 32-bit hash of the page data for pPage.
   41423 */
   41424 static u32 pager_datahash(int nByte, unsigned char *pData){
   41425   u32 hash = 0;
   41426   int i;
   41427   for(i=0; i<nByte; i++){
   41428     hash = (hash*1039) + pData[i];
   41429   }
   41430   return hash;
   41431 }
   41432 static u32 pager_pagehash(PgHdr *pPage){
   41433   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
   41434 }
   41435 static void pager_set_pagehash(PgHdr *pPage){
   41436   pPage->pageHash = pager_pagehash(pPage);
   41437 }
   41438 
   41439 /*
   41440 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
   41441 ** is defined, and NDEBUG is not defined, an assert() statement checks
   41442 ** that the page is either dirty or still matches the calculated page-hash.
   41443 */
   41444 #define CHECK_PAGE(x) checkPage(x)
   41445 static void checkPage(PgHdr *pPg){
   41446   Pager *pPager = pPg->pPager;
   41447   assert( pPager->eState!=PAGER_ERROR );
   41448   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
   41449 }
   41450 
   41451 #else
   41452 #define pager_datahash(X,Y)  0
   41453 #define pager_pagehash(X)  0
   41454 #define pager_set_pagehash(X)
   41455 #define CHECK_PAGE(x)
   41456 #endif  /* SQLITE_CHECK_PAGES */
   41457 
   41458 /*
   41459 ** When this is called the journal file for pager pPager must be open.
   41460 ** This function attempts to read a master journal file name from the
   41461 ** end of the file and, if successful, copies it into memory supplied
   41462 ** by the caller. See comments above writeMasterJournal() for the format
   41463 ** used to store a master journal file name at the end of a journal file.
   41464 **
   41465 ** zMaster must point to a buffer of at least nMaster bytes allocated by
   41466 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
   41467 ** enough space to write the master journal name). If the master journal
   41468 ** name in the journal is longer than nMaster bytes (including a
   41469 ** nul-terminator), then this is handled as if no master journal name
   41470 ** were present in the journal.
   41471 **
   41472 ** If a master journal file name is present at the end of the journal
   41473 ** file, then it is copied into the buffer pointed to by zMaster. A
   41474 ** nul-terminator byte is appended to the buffer following the master
   41475 ** journal file name.
   41476 **
   41477 ** If it is determined that no master journal file name is present
   41478 ** zMaster[0] is set to 0 and SQLITE_OK returned.
   41479 **
   41480 ** If an error occurs while reading from the journal file, an SQLite
   41481 ** error code is returned.
   41482 */
   41483 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
   41484   int rc;                    /* Return code */
   41485   u32 len;                   /* Length in bytes of master journal name */
   41486   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
   41487   u32 cksum;                 /* MJ checksum value read from journal */
   41488   u32 u;                     /* Unsigned loop counter */
   41489   unsigned char aMagic[8];   /* A buffer to hold the magic header */
   41490   zMaster[0] = '\0';
   41491 
   41492   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   41493    || szJ<16
   41494    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
   41495    || len>=nMaster
   41496    || len==0
   41497    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
   41498    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   41499    || memcmp(aMagic, aJournalMagic, 8)
   41500    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
   41501   ){
   41502     return rc;
   41503   }
   41504 
   41505   /* See if the checksum matches the master journal name */
   41506   for(u=0; u<len; u++){
   41507     cksum -= zMaster[u];
   41508   }
   41509   if( cksum ){
   41510     /* If the checksum doesn't add up, then one or more of the disk sectors
   41511     ** containing the master journal filename is corrupted. This means
   41512     ** definitely roll back, so just return SQLITE_OK and report a (nul)
   41513     ** master-journal filename.
   41514     */
   41515     len = 0;
   41516   }
   41517   zMaster[len] = '\0';
   41518 
   41519   return SQLITE_OK;
   41520 }
   41521 
   41522 /*
   41523 ** Return the offset of the sector boundary at or immediately
   41524 ** following the value in pPager->journalOff, assuming a sector
   41525 ** size of pPager->sectorSize bytes.
   41526 **
   41527 ** i.e for a sector size of 512:
   41528 **
   41529 **   Pager.journalOff          Return value
   41530 **   ---------------------------------------
   41531 **   0                         0
   41532 **   512                       512
   41533 **   100                       512
   41534 **   2000                      2048
   41535 **
   41536 */
   41537 static i64 journalHdrOffset(Pager *pPager){
   41538   i64 offset = 0;
   41539   i64 c = pPager->journalOff;
   41540   if( c ){
   41541     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
   41542   }
   41543   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
   41544   assert( offset>=c );
   41545   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
   41546   return offset;
   41547 }
   41548 
   41549 /*
   41550 ** The journal file must be open when this function is called.
   41551 **
   41552 ** This function is a no-op if the journal file has not been written to
   41553 ** within the current transaction (i.e. if Pager.journalOff==0).
   41554 **
   41555 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
   41556 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
   41557 ** zero the 28-byte header at the start of the journal file. In either case,
   41558 ** if the pager is not in no-sync mode, sync the journal file immediately
   41559 ** after writing or truncating it.
   41560 **
   41561 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
   41562 ** following the truncation or zeroing described above the size of the
   41563 ** journal file in bytes is larger than this value, then truncate the
   41564 ** journal file to Pager.journalSizeLimit bytes. The journal file does
   41565 ** not need to be synced following this operation.
   41566 **
   41567 ** If an IO error occurs, abandon processing and return the IO error code.
   41568 ** Otherwise, return SQLITE_OK.
   41569 */
   41570 static int zeroJournalHdr(Pager *pPager, int doTruncate){
   41571   int rc = SQLITE_OK;                               /* Return code */
   41572   assert( isOpen(pPager->jfd) );
   41573   if( pPager->journalOff ){
   41574     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
   41575 
   41576     IOTRACE(("JZEROHDR %p\n", pPager))
   41577     if( doTruncate || iLimit==0 ){
   41578       rc = sqlite3OsTruncate(pPager->jfd, 0);
   41579     }else{
   41580       static const char zeroHdr[28] = {0};
   41581       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
   41582     }
   41583     if( rc==SQLITE_OK && !pPager->noSync ){
   41584       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
   41585     }
   41586 
   41587     /* At this point the transaction is committed but the write lock
   41588     ** is still held on the file. If there is a size limit configured for
   41589     ** the persistent journal and the journal file currently consumes more
   41590     ** space than that limit allows for, truncate it now. There is no need
   41591     ** to sync the file following this operation.
   41592     */
   41593     if( rc==SQLITE_OK && iLimit>0 ){
   41594       i64 sz;
   41595       rc = sqlite3OsFileSize(pPager->jfd, &sz);
   41596       if( rc==SQLITE_OK && sz>iLimit ){
   41597         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
   41598       }
   41599     }
   41600   }
   41601   return rc;
   41602 }
   41603 
   41604 /*
   41605 ** The journal file must be open when this routine is called. A journal
   41606 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
   41607 ** current location.
   41608 **
   41609 ** The format for the journal header is as follows:
   41610 ** - 8 bytes: Magic identifying journal format.
   41611 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
   41612 ** - 4 bytes: Random number used for page hash.
   41613 ** - 4 bytes: Initial database page count.
   41614 ** - 4 bytes: Sector size used by the process that wrote this journal.
   41615 ** - 4 bytes: Database page size.
   41616 **
   41617 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
   41618 */
   41619 static int writeJournalHdr(Pager *pPager){
   41620   int rc = SQLITE_OK;                 /* Return code */
   41621   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
   41622   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
   41623   u32 nWrite;                         /* Bytes of header sector written */
   41624   int ii;                             /* Loop counter */
   41625 
   41626   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   41627 
   41628   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
   41629     nHeader = JOURNAL_HDR_SZ(pPager);
   41630   }
   41631 
   41632   /* If there are active savepoints and any of them were created
   41633   ** since the most recent journal header was written, update the
   41634   ** PagerSavepoint.iHdrOffset fields now.
   41635   */
   41636   for(ii=0; ii<pPager->nSavepoint; ii++){
   41637     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
   41638       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
   41639     }
   41640   }
   41641 
   41642   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
   41643 
   41644   /*
   41645   ** Write the nRec Field - the number of page records that follow this
   41646   ** journal header. Normally, zero is written to this value at this time.
   41647   ** After the records are added to the journal (and the journal synced,
   41648   ** if in full-sync mode), the zero is overwritten with the true number
   41649   ** of records (see syncJournal()).
   41650   **
   41651   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
   41652   ** reading the journal this value tells SQLite to assume that the
   41653   ** rest of the journal file contains valid page records. This assumption
   41654   ** is dangerous, as if a failure occurred whilst writing to the journal
   41655   ** file it may contain some garbage data. There are two scenarios
   41656   ** where this risk can be ignored:
   41657   **
   41658   **   * When the pager is in no-sync mode. Corruption can follow a
   41659   **     power failure in this case anyway.
   41660   **
   41661   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
   41662   **     that garbage data is never appended to the journal file.
   41663   */
   41664   assert( isOpen(pPager->fd) || pPager->noSync );
   41665   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   41666    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   41667   ){
   41668     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   41669     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
   41670   }else{
   41671     memset(zHeader, 0, sizeof(aJournalMagic)+4);
   41672   }
   41673 
   41674   /* The random check-hash initializer */
   41675   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
   41676   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
   41677   /* The initial database size */
   41678   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
   41679   /* The assumed sector size for this process */
   41680   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
   41681 
   41682   /* The page size */
   41683   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
   41684 
   41685   /* Initializing the tail of the buffer is not necessary.  Everything
   41686   ** works find if the following memset() is omitted.  But initializing
   41687   ** the memory prevents valgrind from complaining, so we are willing to
   41688   ** take the performance hit.
   41689   */
   41690   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
   41691          nHeader-(sizeof(aJournalMagic)+20));
   41692 
   41693   /* In theory, it is only necessary to write the 28 bytes that the
   41694   ** journal header consumes to the journal file here. Then increment the
   41695   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
   41696   ** record is written to the following sector (leaving a gap in the file
   41697   ** that will be implicitly filled in by the OS).
   41698   **
   41699   ** However it has been discovered that on some systems this pattern can
   41700   ** be significantly slower than contiguously writing data to the file,
   41701   ** even if that means explicitly writing data to the block of
   41702   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
   41703   ** is done.
   41704   **
   41705   ** The loop is required here in case the sector-size is larger than the
   41706   ** database page size. Since the zHeader buffer is only Pager.pageSize
   41707   ** bytes in size, more than one call to sqlite3OsWrite() may be required
   41708   ** to populate the entire journal header sector.
   41709   */
   41710   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
   41711     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
   41712     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
   41713     assert( pPager->journalHdr <= pPager->journalOff );
   41714     pPager->journalOff += nHeader;
   41715   }
   41716 
   41717   return rc;
   41718 }
   41719 
   41720 /*
   41721 ** The journal file must be open when this is called. A journal header file
   41722 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
   41723 ** file. The current location in the journal file is given by
   41724 ** pPager->journalOff. See comments above function writeJournalHdr() for
   41725 ** a description of the journal header format.
   41726 **
   41727 ** If the header is read successfully, *pNRec is set to the number of
   41728 ** page records following this header and *pDbSize is set to the size of the
   41729 ** database before the transaction began, in pages. Also, pPager->cksumInit
   41730 ** is set to the value read from the journal header. SQLITE_OK is returned
   41731 ** in this case.
   41732 **
   41733 ** If the journal header file appears to be corrupted, SQLITE_DONE is
   41734 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
   41735 ** cannot be read from the journal file an error code is returned.
   41736 */
   41737 static int readJournalHdr(
   41738   Pager *pPager,               /* Pager object */
   41739   int isHot,
   41740   i64 journalSize,             /* Size of the open journal file in bytes */
   41741   u32 *pNRec,                  /* OUT: Value read from the nRec field */
   41742   u32 *pDbSize                 /* OUT: Value of original database size field */
   41743 ){
   41744   int rc;                      /* Return code */
   41745   unsigned char aMagic[8];     /* A buffer to hold the magic header */
   41746   i64 iHdrOff;                 /* Offset of journal header being read */
   41747 
   41748   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   41749 
   41750   /* Advance Pager.journalOff to the start of the next sector. If the
   41751   ** journal file is too small for there to be a header stored at this
   41752   ** point, return SQLITE_DONE.
   41753   */
   41754   pPager->journalOff = journalHdrOffset(pPager);
   41755   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
   41756     return SQLITE_DONE;
   41757   }
   41758   iHdrOff = pPager->journalOff;
   41759 
   41760   /* Read in the first 8 bytes of the journal header. If they do not match
   41761   ** the  magic string found at the start of each journal header, return
   41762   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
   41763   ** proceed.
   41764   */
   41765   if( isHot || iHdrOff!=pPager->journalHdr ){
   41766     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
   41767     if( rc ){
   41768       return rc;
   41769     }
   41770     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
   41771       return SQLITE_DONE;
   41772     }
   41773   }
   41774 
   41775   /* Read the first three 32-bit fields of the journal header: The nRec
   41776   ** field, the checksum-initializer and the database size at the start
   41777   ** of the transaction. Return an error code if anything goes wrong.
   41778   */
   41779   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
   41780    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   41781    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
   41782   ){
   41783     return rc;
   41784   }
   41785 
   41786   if( pPager->journalOff==0 ){
   41787     u32 iPageSize;               /* Page-size field of journal header */
   41788     u32 iSectorSize;             /* Sector-size field of journal header */
   41789 
   41790     /* Read the page-size and sector-size journal header fields. */
   41791     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
   41792      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
   41793     ){
   41794       return rc;
   41795     }
   41796 
   41797     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
   41798     ** journal header to zero. In this case, assume that the Pager.pageSize
   41799     ** variable is already set to the correct page size.
   41800     */
   41801     if( iPageSize==0 ){
   41802       iPageSize = pPager->pageSize;
   41803     }
   41804 
   41805     /* Check that the values read from the page-size and sector-size fields
   41806     ** are within range. To be 'in range', both values need to be a power
   41807     ** of two greater than or equal to 512 or 32, and not greater than their
   41808     ** respective compile time maximum limits.
   41809     */
   41810     if( iPageSize<512                  || iSectorSize<32
   41811      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
   41812      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
   41813     ){
   41814       /* If the either the page-size or sector-size in the journal-header is
   41815       ** invalid, then the process that wrote the journal-header must have
   41816       ** crashed before the header was synced. In this case stop reading
   41817       ** the journal file here.
   41818       */
   41819       return SQLITE_DONE;
   41820     }
   41821 
   41822     /* Update the page-size to match the value read from the journal.
   41823     ** Use a testcase() macro to make sure that malloc failure within
   41824     ** PagerSetPagesize() is tested.
   41825     */
   41826     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
   41827     testcase( rc!=SQLITE_OK );
   41828 
   41829     /* Update the assumed sector-size to match the value used by
   41830     ** the process that created this journal. If this journal was
   41831     ** created by a process other than this one, then this routine
   41832     ** is being called from within pager_playback(). The local value
   41833     ** of Pager.sectorSize is restored at the end of that routine.
   41834     */
   41835     pPager->sectorSize = iSectorSize;
   41836   }
   41837 
   41838   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
   41839   return rc;
   41840 }
   41841 
   41842 
   41843 /*
   41844 ** Write the supplied master journal name into the journal file for pager
   41845 ** pPager at the current location. The master journal name must be the last
   41846 ** thing written to a journal file. If the pager is in full-sync mode, the
   41847 ** journal file descriptor is advanced to the next sector boundary before
   41848 ** anything is written. The format is:
   41849 **
   41850 **   + 4 bytes: PAGER_MJ_PGNO.
   41851 **   + N bytes: Master journal filename in utf-8.
   41852 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
   41853 **   + 4 bytes: Master journal name checksum.
   41854 **   + 8 bytes: aJournalMagic[].
   41855 **
   41856 ** The master journal page checksum is the sum of the bytes in the master
   41857 ** journal name, where each byte is interpreted as a signed 8-bit integer.
   41858 **
   41859 ** If zMaster is a NULL pointer (occurs for a single database transaction),
   41860 ** this call is a no-op.
   41861 */
   41862 static int writeMasterJournal(Pager *pPager, const char *zMaster){
   41863   int rc;                          /* Return code */
   41864   int nMaster;                     /* Length of string zMaster */
   41865   i64 iHdrOff;                     /* Offset of header in journal file */
   41866   i64 jrnlSize;                    /* Size of journal file on disk */
   41867   u32 cksum = 0;                   /* Checksum of string zMaster */
   41868 
   41869   assert( pPager->setMaster==0 );
   41870   assert( !pagerUseWal(pPager) );
   41871 
   41872   if( !zMaster
   41873    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   41874    || !isOpen(pPager->jfd)
   41875   ){
   41876     return SQLITE_OK;
   41877   }
   41878   pPager->setMaster = 1;
   41879   assert( pPager->journalHdr <= pPager->journalOff );
   41880 
   41881   /* Calculate the length in bytes and the checksum of zMaster */
   41882   for(nMaster=0; zMaster[nMaster]; nMaster++){
   41883     cksum += zMaster[nMaster];
   41884   }
   41885 
   41886   /* If in full-sync mode, advance to the next disk sector before writing
   41887   ** the master journal name. This is in case the previous page written to
   41888   ** the journal has already been synced.
   41889   */
   41890   if( pPager->fullSync ){
   41891     pPager->journalOff = journalHdrOffset(pPager);
   41892   }
   41893   iHdrOff = pPager->journalOff;
   41894 
   41895   /* Write the master journal data to the end of the journal file. If
   41896   ** an error occurs, return the error code to the caller.
   41897   */
   41898   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
   41899    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
   41900    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
   41901    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
   41902    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
   41903   ){
   41904     return rc;
   41905   }
   41906   pPager->journalOff += (nMaster+20);
   41907 
   41908   /* If the pager is in peristent-journal mode, then the physical
   41909   ** journal-file may extend past the end of the master-journal name
   41910   ** and 8 bytes of magic data just written to the file. This is
   41911   ** dangerous because the code to rollback a hot-journal file
   41912   ** will not be able to find the master-journal name to determine
   41913   ** whether or not the journal is hot.
   41914   **
   41915   ** Easiest thing to do in this scenario is to truncate the journal
   41916   ** file to the required size.
   41917   */
   41918   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   41919    && jrnlSize>pPager->journalOff
   41920   ){
   41921     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
   41922   }
   41923   return rc;
   41924 }
   41925 
   41926 /*
   41927 ** Find a page in the hash table given its page number. Return
   41928 ** a pointer to the page or NULL if the requested page is not
   41929 ** already in memory.
   41930 */
   41931 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
   41932   PgHdr *p = 0;                     /* Return value */
   41933 
   41934   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
   41935   ** fail, since no attempt to allocate dynamic memory will be made.
   41936   */
   41937   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
   41938   return p;
   41939 }
   41940 
   41941 /*
   41942 ** Discard the entire contents of the in-memory page-cache.
   41943 */
   41944 static void pager_reset(Pager *pPager){
   41945   sqlite3BackupRestart(pPager->pBackup);
   41946   sqlite3PcacheClear(pPager->pPCache);
   41947 }
   41948 
   41949 /*
   41950 ** Free all structures in the Pager.aSavepoint[] array and set both
   41951 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
   41952 ** if it is open and the pager is not in exclusive mode.
   41953 */
   41954 static void releaseAllSavepoints(Pager *pPager){
   41955   int ii;               /* Iterator for looping through Pager.aSavepoint */
   41956   for(ii=0; ii<pPager->nSavepoint; ii++){
   41957     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   41958   }
   41959   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
   41960     sqlite3OsClose(pPager->sjfd);
   41961   }
   41962   sqlite3_free(pPager->aSavepoint);
   41963   pPager->aSavepoint = 0;
   41964   pPager->nSavepoint = 0;
   41965   pPager->nSubRec = 0;
   41966 }
   41967 
   41968 /*
   41969 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
   41970 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
   41971 ** or SQLITE_NOMEM if a malloc failure occurs.
   41972 */
   41973 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
   41974   int ii;                   /* Loop counter */
   41975   int rc = SQLITE_OK;       /* Result code */
   41976 
   41977   for(ii=0; ii<pPager->nSavepoint; ii++){
   41978     PagerSavepoint *p = &pPager->aSavepoint[ii];
   41979     if( pgno<=p->nOrig ){
   41980       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
   41981       testcase( rc==SQLITE_NOMEM );
   41982       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   41983     }
   41984   }
   41985   return rc;
   41986 }
   41987 
   41988 /*
   41989 ** This function is a no-op if the pager is in exclusive mode and not
   41990 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
   41991 ** state.
   41992 **
   41993 ** If the pager is not in exclusive-access mode, the database file is
   41994 ** completely unlocked. If the file is unlocked and the file-system does
   41995 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
   41996 ** closed (if it is open).
   41997 **
   41998 ** If the pager is in ERROR state when this function is called, the
   41999 ** contents of the pager cache are discarded before switching back to
   42000 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
   42001 ** or not, any journal file left in the file-system will be treated
   42002 ** as a hot-journal and rolled back the next time a read-transaction
   42003 ** is opened (by this or by any other connection).
   42004 */
   42005 static void pager_unlock(Pager *pPager){
   42006 
   42007   assert( pPager->eState==PAGER_READER
   42008        || pPager->eState==PAGER_OPEN
   42009        || pPager->eState==PAGER_ERROR
   42010   );
   42011 
   42012   sqlite3BitvecDestroy(pPager->pInJournal);
   42013   pPager->pInJournal = 0;
   42014   releaseAllSavepoints(pPager);
   42015 
   42016   if( pagerUseWal(pPager) ){
   42017     assert( !isOpen(pPager->jfd) );
   42018     sqlite3WalEndReadTransaction(pPager->pWal);
   42019     pPager->eState = PAGER_OPEN;
   42020   }else if( !pPager->exclusiveMode ){
   42021     int rc;                       /* Error code returned by pagerUnlockDb() */
   42022     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
   42023 
   42024     /* If the operating system support deletion of open files, then
   42025     ** close the journal file when dropping the database lock.  Otherwise
   42026     ** another connection with journal_mode=delete might delete the file
   42027     ** out from under us.
   42028     */
   42029     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
   42030     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
   42031     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
   42032     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
   42033     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   42034     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
   42035     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
   42036      || 1!=(pPager->journalMode & 5)
   42037     ){
   42038       sqlite3OsClose(pPager->jfd);
   42039     }
   42040 
   42041     /* If the pager is in the ERROR state and the call to unlock the database
   42042     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
   42043     ** above the #define for UNKNOWN_LOCK for an explanation of why this
   42044     ** is necessary.
   42045     */
   42046     rc = pagerUnlockDb(pPager, NO_LOCK);
   42047     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
   42048       pPager->eLock = UNKNOWN_LOCK;
   42049     }
   42050 
   42051     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
   42052     ** without clearing the error code. This is intentional - the error
   42053     ** code is cleared and the cache reset in the block below.
   42054     */
   42055     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
   42056     pPager->changeCountDone = 0;
   42057     pPager->eState = PAGER_OPEN;
   42058   }
   42059 
   42060   /* If Pager.errCode is set, the contents of the pager cache cannot be
   42061   ** trusted. Now that there are no outstanding references to the pager,
   42062   ** it can safely move back to PAGER_OPEN state. This happens in both
   42063   ** normal and exclusive-locking mode.
   42064   */
   42065   if( pPager->errCode ){
   42066     assert( !MEMDB );
   42067     pager_reset(pPager);
   42068     pPager->changeCountDone = pPager->tempFile;
   42069     pPager->eState = PAGER_OPEN;
   42070     pPager->errCode = SQLITE_OK;
   42071     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
   42072   }
   42073 
   42074   pPager->journalOff = 0;
   42075   pPager->journalHdr = 0;
   42076   pPager->setMaster = 0;
   42077 }
   42078 
   42079 /*
   42080 ** This function is called whenever an IOERR or FULL error that requires
   42081 ** the pager to transition into the ERROR state may ahve occurred.
   42082 ** The first argument is a pointer to the pager structure, the second
   42083 ** the error-code about to be returned by a pager API function. The
   42084 ** value returned is a copy of the second argument to this function.
   42085 **
   42086 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
   42087 ** IOERR sub-codes, the pager enters the ERROR state and the error code
   42088 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
   42089 ** all major API calls on the Pager will immediately return Pager.errCode.
   42090 **
   42091 ** The ERROR state indicates that the contents of the pager-cache
   42092 ** cannot be trusted. This state can be cleared by completely discarding
   42093 ** the contents of the pager-cache. If a transaction was active when
   42094 ** the persistent error occurred, then the rollback journal may need
   42095 ** to be replayed to restore the contents of the database file (as if
   42096 ** it were a hot-journal).
   42097 */
   42098 static int pager_error(Pager *pPager, int rc){
   42099   int rc2 = rc & 0xff;
   42100   assert( rc==SQLITE_OK || !MEMDB );
   42101   assert(
   42102        pPager->errCode==SQLITE_FULL ||
   42103        pPager->errCode==SQLITE_OK ||
   42104        (pPager->errCode & 0xff)==SQLITE_IOERR
   42105   );
   42106   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
   42107     pPager->errCode = rc;
   42108     pPager->eState = PAGER_ERROR;
   42109   }
   42110   return rc;
   42111 }
   42112 
   42113 static int pager_truncate(Pager *pPager, Pgno nPage);
   42114 
   42115 /*
   42116 ** This routine ends a transaction. A transaction is usually ended by
   42117 ** either a COMMIT or a ROLLBACK operation. This routine may be called
   42118 ** after rollback of a hot-journal, or if an error occurs while opening
   42119 ** the journal file or writing the very first journal-header of a
   42120 ** database transaction.
   42121 **
   42122 ** This routine is never called in PAGER_ERROR state. If it is called
   42123 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
   42124 ** exclusive than a RESERVED lock, it is a no-op.
   42125 **
   42126 ** Otherwise, any active savepoints are released.
   42127 **
   42128 ** If the journal file is open, then it is "finalized". Once a journal
   42129 ** file has been finalized it is not possible to use it to roll back a
   42130 ** transaction. Nor will it be considered to be a hot-journal by this
   42131 ** or any other database connection. Exactly how a journal is finalized
   42132 ** depends on whether or not the pager is running in exclusive mode and
   42133 ** the current journal-mode (Pager.journalMode value), as follows:
   42134 **
   42135 **   journalMode==MEMORY
   42136 **     Journal file descriptor is simply closed. This destroys an
   42137 **     in-memory journal.
   42138 **
   42139 **   journalMode==TRUNCATE
   42140 **     Journal file is truncated to zero bytes in size.
   42141 **
   42142 **   journalMode==PERSIST
   42143 **     The first 28 bytes of the journal file are zeroed. This invalidates
   42144 **     the first journal header in the file, and hence the entire journal
   42145 **     file. An invalid journal file cannot be rolled back.
   42146 **
   42147 **   journalMode==DELETE
   42148 **     The journal file is closed and deleted using sqlite3OsDelete().
   42149 **
   42150 **     If the pager is running in exclusive mode, this method of finalizing
   42151 **     the journal file is never used. Instead, if the journalMode is
   42152 **     DELETE and the pager is in exclusive mode, the method described under
   42153 **     journalMode==PERSIST is used instead.
   42154 **
   42155 ** After the journal is finalized, the pager moves to PAGER_READER state.
   42156 ** If running in non-exclusive rollback mode, the lock on the file is
   42157 ** downgraded to a SHARED_LOCK.
   42158 **
   42159 ** SQLITE_OK is returned if no error occurs. If an error occurs during
   42160 ** any of the IO operations to finalize the journal file or unlock the
   42161 ** database then the IO error code is returned to the user. If the
   42162 ** operation to finalize the journal file fails, then the code still
   42163 ** tries to unlock the database file if not in exclusive mode. If the
   42164 ** unlock operation fails as well, then the first error code related
   42165 ** to the first error encountered (the journal finalization one) is
   42166 ** returned.
   42167 */
   42168 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
   42169   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
   42170   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
   42171 
   42172   /* Do nothing if the pager does not have an open write transaction
   42173   ** or at least a RESERVED lock. This function may be called when there
   42174   ** is no write-transaction active but a RESERVED or greater lock is
   42175   ** held under two circumstances:
   42176   **
   42177   **   1. After a successful hot-journal rollback, it is called with
   42178   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
   42179   **
   42180   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
   42181   **      lock switches back to locking_mode=normal and then executes a
   42182   **      read-transaction, this function is called with eState==PAGER_READER
   42183   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
   42184   */
   42185   assert( assert_pager_state(pPager) );
   42186   assert( pPager->eState!=PAGER_ERROR );
   42187   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
   42188     return SQLITE_OK;
   42189   }
   42190 
   42191   releaseAllSavepoints(pPager);
   42192   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
   42193   if( isOpen(pPager->jfd) ){
   42194     assert( !pagerUseWal(pPager) );
   42195 
   42196     /* Finalize the journal file. */
   42197     if( sqlite3IsMemJournal(pPager->jfd) ){
   42198       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
   42199       sqlite3OsClose(pPager->jfd);
   42200     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
   42201       if( pPager->journalOff==0 ){
   42202         rc = SQLITE_OK;
   42203       }else{
   42204         rc = sqlite3OsTruncate(pPager->jfd, 0);
   42205       }
   42206       pPager->journalOff = 0;
   42207     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   42208       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
   42209     ){
   42210       rc = zeroJournalHdr(pPager, hasMaster);
   42211       pPager->journalOff = 0;
   42212     }else{
   42213       /* This branch may be executed with Pager.journalMode==MEMORY if
   42214       ** a hot-journal was just rolled back. In this case the journal
   42215       ** file should be closed and deleted. If this connection writes to
   42216       ** the database file, it will do so using an in-memory journal.
   42217       */
   42218       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
   42219       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
   42220            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   42221            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   42222       );
   42223       sqlite3OsClose(pPager->jfd);
   42224       if( bDelete ){
   42225         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   42226       }
   42227     }
   42228   }
   42229 
   42230 #ifdef SQLITE_CHECK_PAGES
   42231   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
   42232   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
   42233     PgHdr *p = pager_lookup(pPager, 1);
   42234     if( p ){
   42235       p->pageHash = 0;
   42236       sqlite3PagerUnrefNotNull(p);
   42237     }
   42238   }
   42239 #endif
   42240 
   42241   sqlite3BitvecDestroy(pPager->pInJournal);
   42242   pPager->pInJournal = 0;
   42243   pPager->nRec = 0;
   42244   sqlite3PcacheCleanAll(pPager->pPCache);
   42245   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
   42246 
   42247   if( pagerUseWal(pPager) ){
   42248     /* Drop the WAL write-lock, if any. Also, if the connection was in
   42249     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
   42250     ** lock held on the database file.
   42251     */
   42252     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
   42253     assert( rc2==SQLITE_OK );
   42254   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
   42255     /* This branch is taken when committing a transaction in rollback-journal
   42256     ** mode if the database file on disk is larger than the database image.
   42257     ** At this point the journal has been finalized and the transaction
   42258     ** successfully committed, but the EXCLUSIVE lock is still held on the
   42259     ** file. So it is safe to truncate the database file to its minimum
   42260     ** required size.  */
   42261     assert( pPager->eLock==EXCLUSIVE_LOCK );
   42262     rc = pager_truncate(pPager, pPager->dbSize);
   42263   }
   42264 
   42265   if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
   42266     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
   42267     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   42268   }
   42269 
   42270   if( !pPager->exclusiveMode
   42271    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
   42272   ){
   42273     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
   42274     pPager->changeCountDone = 0;
   42275   }
   42276   pPager->eState = PAGER_READER;
   42277   pPager->setMaster = 0;
   42278 
   42279   return (rc==SQLITE_OK?rc2:rc);
   42280 }
   42281 
   42282 /*
   42283 ** Execute a rollback if a transaction is active and unlock the
   42284 ** database file.
   42285 **
   42286 ** If the pager has already entered the ERROR state, do not attempt
   42287 ** the rollback at this time. Instead, pager_unlock() is called. The
   42288 ** call to pager_unlock() will discard all in-memory pages, unlock
   42289 ** the database file and move the pager back to OPEN state. If this
   42290 ** means that there is a hot-journal left in the file-system, the next
   42291 ** connection to obtain a shared lock on the pager (which may be this one)
   42292 ** will roll it back.
   42293 **
   42294 ** If the pager has not already entered the ERROR state, but an IO or
   42295 ** malloc error occurs during a rollback, then this will itself cause
   42296 ** the pager to enter the ERROR state. Which will be cleared by the
   42297 ** call to pager_unlock(), as described above.
   42298 */
   42299 static void pagerUnlockAndRollback(Pager *pPager){
   42300   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
   42301     assert( assert_pager_state(pPager) );
   42302     if( pPager->eState>=PAGER_WRITER_LOCKED ){
   42303       sqlite3BeginBenignMalloc();
   42304       sqlite3PagerRollback(pPager);
   42305       sqlite3EndBenignMalloc();
   42306     }else if( !pPager->exclusiveMode ){
   42307       assert( pPager->eState==PAGER_READER );
   42308       pager_end_transaction(pPager, 0, 0);
   42309     }
   42310   }
   42311   pager_unlock(pPager);
   42312 }
   42313 
   42314 /*
   42315 ** Parameter aData must point to a buffer of pPager->pageSize bytes
   42316 ** of data. Compute and return a checksum based ont the contents of the
   42317 ** page of data and the current value of pPager->cksumInit.
   42318 **
   42319 ** This is not a real checksum. It is really just the sum of the
   42320 ** random initial value (pPager->cksumInit) and every 200th byte
   42321 ** of the page data, starting with byte offset (pPager->pageSize%200).
   42322 ** Each byte is interpreted as an 8-bit unsigned integer.
   42323 **
   42324 ** Changing the formula used to compute this checksum results in an
   42325 ** incompatible journal file format.
   42326 **
   42327 ** If journal corruption occurs due to a power failure, the most likely
   42328 ** scenario is that one end or the other of the record will be changed.
   42329 ** It is much less likely that the two ends of the journal record will be
   42330 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
   42331 ** though fast and simple, catches the mostly likely kind of corruption.
   42332 */
   42333 static u32 pager_cksum(Pager *pPager, const u8 *aData){
   42334   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
   42335   int i = pPager->pageSize-200;          /* Loop counter */
   42336   while( i>0 ){
   42337     cksum += aData[i];
   42338     i -= 200;
   42339   }
   42340   return cksum;
   42341 }
   42342 
   42343 /*
   42344 ** Report the current page size and number of reserved bytes back
   42345 ** to the codec.
   42346 */
   42347 #ifdef SQLITE_HAS_CODEC
   42348 static void pagerReportSize(Pager *pPager){
   42349   if( pPager->xCodecSizeChng ){
   42350     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
   42351                            (int)pPager->nReserve);
   42352   }
   42353 }
   42354 #else
   42355 # define pagerReportSize(X)     /* No-op if we do not support a codec */
   42356 #endif
   42357 
   42358 /*
   42359 ** Read a single page from either the journal file (if isMainJrnl==1) or
   42360 ** from the sub-journal (if isMainJrnl==0) and playback that page.
   42361 ** The page begins at offset *pOffset into the file. The *pOffset
   42362 ** value is increased to the start of the next page in the journal.
   42363 **
   42364 ** The main rollback journal uses checksums - the statement journal does
   42365 ** not.
   42366 **
   42367 ** If the page number of the page record read from the (sub-)journal file
   42368 ** is greater than the current value of Pager.dbSize, then playback is
   42369 ** skipped and SQLITE_OK is returned.
   42370 **
   42371 ** If pDone is not NULL, then it is a record of pages that have already
   42372 ** been played back.  If the page at *pOffset has already been played back
   42373 ** (if the corresponding pDone bit is set) then skip the playback.
   42374 ** Make sure the pDone bit corresponding to the *pOffset page is set
   42375 ** prior to returning.
   42376 **
   42377 ** If the page record is successfully read from the (sub-)journal file
   42378 ** and played back, then SQLITE_OK is returned. If an IO error occurs
   42379 ** while reading the record from the (sub-)journal file or while writing
   42380 ** to the database file, then the IO error code is returned. If data
   42381 ** is successfully read from the (sub-)journal file but appears to be
   42382 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
   42383 ** two circumstances:
   42384 **
   42385 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
   42386 **   * If the record is being rolled back from the main journal file
   42387 **     and the checksum field does not match the record content.
   42388 **
   42389 ** Neither of these two scenarios are possible during a savepoint rollback.
   42390 **
   42391 ** If this is a savepoint rollback, then memory may have to be dynamically
   42392 ** allocated by this function. If this is the case and an allocation fails,
   42393 ** SQLITE_NOMEM is returned.
   42394 */
   42395 static int pager_playback_one_page(
   42396   Pager *pPager,                /* The pager being played back */
   42397   i64 *pOffset,                 /* Offset of record to playback */
   42398   Bitvec *pDone,                /* Bitvec of pages already played back */
   42399   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
   42400   int isSavepnt                 /* True for a savepoint rollback */
   42401 ){
   42402   int rc;
   42403   PgHdr *pPg;                   /* An existing page in the cache */
   42404   Pgno pgno;                    /* The page number of a page in journal */
   42405   u32 cksum;                    /* Checksum used for sanity checking */
   42406   char *aData;                  /* Temporary storage for the page */
   42407   sqlite3_file *jfd;            /* The file descriptor for the journal file */
   42408   int isSynced;                 /* True if journal page is synced */
   42409 
   42410   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
   42411   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
   42412   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
   42413   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
   42414 
   42415   aData = pPager->pTmpSpace;
   42416   assert( aData );         /* Temp storage must have already been allocated */
   42417   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
   42418 
   42419   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
   42420   ** or savepoint rollback done at the request of the caller) or this is
   42421   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
   42422   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
   42423   ** only reads from the main journal, not the sub-journal.
   42424   */
   42425   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
   42426        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
   42427   );
   42428   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
   42429 
   42430   /* Read the page number and page data from the journal or sub-journal
   42431   ** file. Return an error code to the caller if an IO error occurs.
   42432   */
   42433   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
   42434   rc = read32bits(jfd, *pOffset, &pgno);
   42435   if( rc!=SQLITE_OK ) return rc;
   42436   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
   42437   if( rc!=SQLITE_OK ) return rc;
   42438   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
   42439 
   42440   /* Sanity checking on the page.  This is more important that I originally
   42441   ** thought.  If a power failure occurs while the journal is being written,
   42442   ** it could cause invalid data to be written into the journal.  We need to
   42443   ** detect this invalid data (with high probability) and ignore it.
   42444   */
   42445   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
   42446     assert( !isSavepnt );
   42447     return SQLITE_DONE;
   42448   }
   42449   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
   42450     return SQLITE_OK;
   42451   }
   42452   if( isMainJrnl ){
   42453     rc = read32bits(jfd, (*pOffset)-4, &cksum);
   42454     if( rc ) return rc;
   42455     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
   42456       return SQLITE_DONE;
   42457     }
   42458   }
   42459 
   42460   /* If this page has already been played by before during the current
   42461   ** rollback, then don't bother to play it back again.
   42462   */
   42463   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
   42464     return rc;
   42465   }
   42466 
   42467   /* When playing back page 1, restore the nReserve setting
   42468   */
   42469   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
   42470     pPager->nReserve = ((u8*)aData)[20];
   42471     pagerReportSize(pPager);
   42472   }
   42473 
   42474   /* If the pager is in CACHEMOD state, then there must be a copy of this
   42475   ** page in the pager cache. In this case just update the pager cache,
   42476   ** not the database file. The page is left marked dirty in this case.
   42477   **
   42478   ** An exception to the above rule: If the database is in no-sync mode
   42479   ** and a page is moved during an incremental vacuum then the page may
   42480   ** not be in the pager cache. Later: if a malloc() or IO error occurs
   42481   ** during a Movepage() call, then the page may not be in the cache
   42482   ** either. So the condition described in the above paragraph is not
   42483   ** assert()able.
   42484   **
   42485   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
   42486   ** pager cache if it exists and the main file. The page is then marked
   42487   ** not dirty. Since this code is only executed in PAGER_OPEN state for
   42488   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
   42489   ** if the pager is in OPEN state.
   42490   **
   42491   ** Ticket #1171:  The statement journal might contain page content that is
   42492   ** different from the page content at the start of the transaction.
   42493   ** This occurs when a page is changed prior to the start of a statement
   42494   ** then changed again within the statement.  When rolling back such a
   42495   ** statement we must not write to the original database unless we know
   42496   ** for certain that original page contents are synced into the main rollback
   42497   ** journal.  Otherwise, a power loss might leave modified data in the
   42498   ** database file without an entry in the rollback journal that can
   42499   ** restore the database to its original form.  Two conditions must be
   42500   ** met before writing to the database files. (1) the database must be
   42501   ** locked.  (2) we know that the original page content is fully synced
   42502   ** in the main journal either because the page is not in cache or else
   42503   ** the page is marked as needSync==0.
   42504   **
   42505   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
   42506   ** is possible to fail a statement on a database that does not yet exist.
   42507   ** Do not attempt to write if database file has never been opened.
   42508   */
   42509   if( pagerUseWal(pPager) ){
   42510     pPg = 0;
   42511   }else{
   42512     pPg = pager_lookup(pPager, pgno);
   42513   }
   42514   assert( pPg || !MEMDB );
   42515   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
   42516   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
   42517            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
   42518            (isMainJrnl?"main-journal":"sub-journal")
   42519   ));
   42520   if( isMainJrnl ){
   42521     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
   42522   }else{
   42523     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
   42524   }
   42525   if( isOpen(pPager->fd)
   42526    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   42527    && isSynced
   42528   ){
   42529     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
   42530     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
   42531     assert( !pagerUseWal(pPager) );
   42532     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
   42533     if( pgno>pPager->dbFileSize ){
   42534       pPager->dbFileSize = pgno;
   42535     }
   42536     if( pPager->pBackup ){
   42537       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
   42538       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
   42539       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
   42540     }
   42541   }else if( !isMainJrnl && pPg==0 ){
   42542     /* If this is a rollback of a savepoint and data was not written to
   42543     ** the database and the page is not in-memory, there is a potential
   42544     ** problem. When the page is next fetched by the b-tree layer, it
   42545     ** will be read from the database file, which may or may not be
   42546     ** current.
   42547     **
   42548     ** There are a couple of different ways this can happen. All are quite
   42549     ** obscure. When running in synchronous mode, this can only happen
   42550     ** if the page is on the free-list at the start of the transaction, then
   42551     ** populated, then moved using sqlite3PagerMovepage().
   42552     **
   42553     ** The solution is to add an in-memory page to the cache containing
   42554     ** the data just read from the sub-journal. Mark the page as dirty
   42555     ** and if the pager requires a journal-sync, then mark the page as
   42556     ** requiring a journal-sync before it is written.
   42557     */
   42558     assert( isSavepnt );
   42559     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
   42560     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
   42561     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
   42562     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
   42563     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
   42564     if( rc!=SQLITE_OK ) return rc;
   42565     pPg->flags &= ~PGHDR_NEED_READ;
   42566     sqlite3PcacheMakeDirty(pPg);
   42567   }
   42568   if( pPg ){
   42569     /* No page should ever be explicitly rolled back that is in use, except
   42570     ** for page 1 which is held in use in order to keep the lock on the
   42571     ** database active. However such a page may be rolled back as a result
   42572     ** of an internal error resulting in an automatic call to
   42573     ** sqlite3PagerRollback().
   42574     */
   42575     void *pData;
   42576     pData = pPg->pData;
   42577     memcpy(pData, (u8*)aData, pPager->pageSize);
   42578     pPager->xReiniter(pPg);
   42579     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
   42580       /* If the contents of this page were just restored from the main
   42581       ** journal file, then its content must be as they were when the
   42582       ** transaction was first opened. In this case we can mark the page
   42583       ** as clean, since there will be no need to write it out to the
   42584       ** database.
   42585       **
   42586       ** There is one exception to this rule. If the page is being rolled
   42587       ** back as part of a savepoint (or statement) rollback from an
   42588       ** unsynced portion of the main journal file, then it is not safe
   42589       ** to mark the page as clean. This is because marking the page as
   42590       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
   42591       ** already in the journal file (recorded in Pager.pInJournal) and
   42592       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
   42593       ** again within this transaction, it will be marked as dirty but
   42594       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
   42595       ** be written out into the database file before its journal file
   42596       ** segment is synced. If a crash occurs during or following this,
   42597       ** database corruption may ensue.
   42598       */
   42599       assert( !pagerUseWal(pPager) );
   42600       sqlite3PcacheMakeClean(pPg);
   42601     }
   42602     pager_set_pagehash(pPg);
   42603 
   42604     /* If this was page 1, then restore the value of Pager.dbFileVers.
   42605     ** Do this before any decoding. */
   42606     if( pgno==1 ){
   42607       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
   42608     }
   42609 
   42610     /* Decode the page just read from disk */
   42611     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
   42612     sqlite3PcacheRelease(pPg);
   42613   }
   42614   return rc;
   42615 }
   42616 
   42617 /*
   42618 ** Parameter zMaster is the name of a master journal file. A single journal
   42619 ** file that referred to the master journal file has just been rolled back.
   42620 ** This routine checks if it is possible to delete the master journal file,
   42621 ** and does so if it is.
   42622 **
   42623 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
   42624 ** available for use within this function.
   42625 **
   42626 ** When a master journal file is created, it is populated with the names
   42627 ** of all of its child journals, one after another, formatted as utf-8
   42628 ** encoded text. The end of each child journal file is marked with a
   42629 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
   42630 ** file for a transaction involving two databases might be:
   42631 **
   42632 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
   42633 **
   42634 ** A master journal file may only be deleted once all of its child
   42635 ** journals have been rolled back.
   42636 **
   42637 ** This function reads the contents of the master-journal file into
   42638 ** memory and loops through each of the child journal names. For
   42639 ** each child journal, it checks if:
   42640 **
   42641 **   * if the child journal exists, and if so
   42642 **   * if the child journal contains a reference to master journal
   42643 **     file zMaster
   42644 **
   42645 ** If a child journal can be found that matches both of the criteria
   42646 ** above, this function returns without doing anything. Otherwise, if
   42647 ** no such child journal can be found, file zMaster is deleted from
   42648 ** the file-system using sqlite3OsDelete().
   42649 **
   42650 ** If an IO error within this function, an error code is returned. This
   42651 ** function allocates memory by calling sqlite3Malloc(). If an allocation
   42652 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
   42653 ** occur, SQLITE_OK is returned.
   42654 **
   42655 ** TODO: This function allocates a single block of memory to load
   42656 ** the entire contents of the master journal file. This could be
   42657 ** a couple of kilobytes or so - potentially larger than the page
   42658 ** size.
   42659 */
   42660 static int pager_delmaster(Pager *pPager, const char *zMaster){
   42661   sqlite3_vfs *pVfs = pPager->pVfs;
   42662   int rc;                   /* Return code */
   42663   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
   42664   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
   42665   char *zMasterJournal = 0; /* Contents of master journal file */
   42666   i64 nMasterJournal;       /* Size of master journal file */
   42667   char *zJournal;           /* Pointer to one journal within MJ file */
   42668   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
   42669   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
   42670 
   42671   /* Allocate space for both the pJournal and pMaster file descriptors.
   42672   ** If successful, open the master journal file for reading.
   42673   */
   42674   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
   42675   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
   42676   if( !pMaster ){
   42677     rc = SQLITE_NOMEM;
   42678   }else{
   42679     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
   42680     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
   42681   }
   42682   if( rc!=SQLITE_OK ) goto delmaster_out;
   42683 
   42684   /* Load the entire master journal file into space obtained from
   42685   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
   42686   ** sufficient space (in zMasterPtr) to hold the names of master
   42687   ** journal files extracted from regular rollback-journals.
   42688   */
   42689   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
   42690   if( rc!=SQLITE_OK ) goto delmaster_out;
   42691   nMasterPtr = pVfs->mxPathname+1;
   42692   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
   42693   if( !zMasterJournal ){
   42694     rc = SQLITE_NOMEM;
   42695     goto delmaster_out;
   42696   }
   42697   zMasterPtr = &zMasterJournal[nMasterJournal+1];
   42698   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
   42699   if( rc!=SQLITE_OK ) goto delmaster_out;
   42700   zMasterJournal[nMasterJournal] = 0;
   42701 
   42702   zJournal = zMasterJournal;
   42703   while( (zJournal-zMasterJournal)<nMasterJournal ){
   42704     int exists;
   42705     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
   42706     if( rc!=SQLITE_OK ){
   42707       goto delmaster_out;
   42708     }
   42709     if( exists ){
   42710       /* One of the journals pointed to by the master journal exists.
   42711       ** Open it and check if it points at the master journal. If
   42712       ** so, return without deleting the master journal file.
   42713       */
   42714       int c;
   42715       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
   42716       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
   42717       if( rc!=SQLITE_OK ){
   42718         goto delmaster_out;
   42719       }
   42720 
   42721       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
   42722       sqlite3OsClose(pJournal);
   42723       if( rc!=SQLITE_OK ){
   42724         goto delmaster_out;
   42725       }
   42726 
   42727       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
   42728       if( c ){
   42729         /* We have a match. Do not delete the master journal file. */
   42730         goto delmaster_out;
   42731       }
   42732     }
   42733     zJournal += (sqlite3Strlen30(zJournal)+1);
   42734   }
   42735 
   42736   sqlite3OsClose(pMaster);
   42737   rc = sqlite3OsDelete(pVfs, zMaster, 0);
   42738 
   42739 delmaster_out:
   42740   sqlite3_free(zMasterJournal);
   42741   if( pMaster ){
   42742     sqlite3OsClose(pMaster);
   42743     assert( !isOpen(pJournal) );
   42744     sqlite3_free(pMaster);
   42745   }
   42746   return rc;
   42747 }
   42748 
   42749 
   42750 /*
   42751 ** This function is used to change the actual size of the database
   42752 ** file in the file-system. This only happens when committing a transaction,
   42753 ** or rolling back a transaction (including rolling back a hot-journal).
   42754 **
   42755 ** If the main database file is not open, or the pager is not in either
   42756 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
   42757 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
   42758 ** If the file on disk is currently larger than nPage pages, then use the VFS
   42759 ** xTruncate() method to truncate it.
   42760 **
   42761 ** Or, it might might be the case that the file on disk is smaller than
   42762 ** nPage pages. Some operating system implementations can get confused if
   42763 ** you try to truncate a file to some size that is larger than it
   42764 ** currently is, so detect this case and write a single zero byte to
   42765 ** the end of the new file instead.
   42766 **
   42767 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
   42768 ** the database file, return the error code to the caller.
   42769 */
   42770 static int pager_truncate(Pager *pPager, Pgno nPage){
   42771   int rc = SQLITE_OK;
   42772   assert( pPager->eState!=PAGER_ERROR );
   42773   assert( pPager->eState!=PAGER_READER );
   42774 
   42775   if( isOpen(pPager->fd)
   42776    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   42777   ){
   42778     i64 currentSize, newSize;
   42779     int szPage = pPager->pageSize;
   42780     assert( pPager->eLock==EXCLUSIVE_LOCK );
   42781     /* TODO: Is it safe to use Pager.dbFileSize here? */
   42782     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
   42783     newSize = szPage*(i64)nPage;
   42784     if( rc==SQLITE_OK && currentSize!=newSize ){
   42785       if( currentSize>newSize ){
   42786         rc = sqlite3OsTruncate(pPager->fd, newSize);
   42787       }else if( (currentSize+szPage)<=newSize ){
   42788         char *pTmp = pPager->pTmpSpace;
   42789         memset(pTmp, 0, szPage);
   42790         testcase( (newSize-szPage) == currentSize );
   42791         testcase( (newSize-szPage) >  currentSize );
   42792         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
   42793       }
   42794       if( rc==SQLITE_OK ){
   42795         pPager->dbFileSize = nPage;
   42796       }
   42797     }
   42798   }
   42799   return rc;
   42800 }
   42801 
   42802 /*
   42803 ** Return a sanitized version of the sector-size of OS file pFile. The
   42804 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
   42805 */
   42806 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
   42807   int iRet = sqlite3OsSectorSize(pFile);
   42808   if( iRet<32 ){
   42809     iRet = 512;
   42810   }else if( iRet>MAX_SECTOR_SIZE ){
   42811     assert( MAX_SECTOR_SIZE>=512 );
   42812     iRet = MAX_SECTOR_SIZE;
   42813   }
   42814   return iRet;
   42815 }
   42816 
   42817 /*
   42818 ** Set the value of the Pager.sectorSize variable for the given
   42819 ** pager based on the value returned by the xSectorSize method
   42820 ** of the open database file. The sector size will be used used
   42821 ** to determine the size and alignment of journal header and
   42822 ** master journal pointers within created journal files.
   42823 **
   42824 ** For temporary files the effective sector size is always 512 bytes.
   42825 **
   42826 ** Otherwise, for non-temporary files, the effective sector size is
   42827 ** the value returned by the xSectorSize() method rounded up to 32 if
   42828 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
   42829 ** is greater than MAX_SECTOR_SIZE.
   42830 **
   42831 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
   42832 ** the effective sector size to its minimum value (512).  The purpose of
   42833 ** pPager->sectorSize is to define the "blast radius" of bytes that
   42834 ** might change if a crash occurs while writing to a single byte in
   42835 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
   42836 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
   42837 ** size.  For backwards compatibility of the rollback journal file format,
   42838 ** we cannot reduce the effective sector size below 512.
   42839 */
   42840 static void setSectorSize(Pager *pPager){
   42841   assert( isOpen(pPager->fd) || pPager->tempFile );
   42842 
   42843   if( pPager->tempFile
   42844    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
   42845               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
   42846   ){
   42847     /* Sector size doesn't matter for temporary files. Also, the file
   42848     ** may not have been opened yet, in which case the OsSectorSize()
   42849     ** call will segfault. */
   42850     pPager->sectorSize = 512;
   42851   }else{
   42852     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
   42853   }
   42854 }
   42855 
   42856 /*
   42857 ** Playback the journal and thus restore the database file to
   42858 ** the state it was in before we started making changes.
   42859 **
   42860 ** The journal file format is as follows:
   42861 **
   42862 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
   42863 **  (2)  4 byte big-endian integer which is the number of valid page records
   42864 **       in the journal.  If this value is 0xffffffff, then compute the
   42865 **       number of page records from the journal size.
   42866 **  (3)  4 byte big-endian integer which is the initial value for the
   42867 **       sanity checksum.
   42868 **  (4)  4 byte integer which is the number of pages to truncate the
   42869 **       database to during a rollback.
   42870 **  (5)  4 byte big-endian integer which is the sector size.  The header
   42871 **       is this many bytes in size.
   42872 **  (6)  4 byte big-endian integer which is the page size.
   42873 **  (7)  zero padding out to the next sector size.
   42874 **  (8)  Zero or more pages instances, each as follows:
   42875 **        +  4 byte page number.
   42876 **        +  pPager->pageSize bytes of data.
   42877 **        +  4 byte checksum
   42878 **
   42879 ** When we speak of the journal header, we mean the first 7 items above.
   42880 ** Each entry in the journal is an instance of the 8th item.
   42881 **
   42882 ** Call the value from the second bullet "nRec".  nRec is the number of
   42883 ** valid page entries in the journal.  In most cases, you can compute the
   42884 ** value of nRec from the size of the journal file.  But if a power
   42885 ** failure occurred while the journal was being written, it could be the
   42886 ** case that the size of the journal file had already been increased but
   42887 ** the extra entries had not yet made it safely to disk.  In such a case,
   42888 ** the value of nRec computed from the file size would be too large.  For
   42889 ** that reason, we always use the nRec value in the header.
   42890 **
   42891 ** If the nRec value is 0xffffffff it means that nRec should be computed
   42892 ** from the file size.  This value is used when the user selects the
   42893 ** no-sync option for the journal.  A power failure could lead to corruption
   42894 ** in this case.  But for things like temporary table (which will be
   42895 ** deleted when the power is restored) we don't care.
   42896 **
   42897 ** If the file opened as the journal file is not a well-formed
   42898 ** journal file then all pages up to the first corrupted page are rolled
   42899 ** back (or no pages if the journal header is corrupted). The journal file
   42900 ** is then deleted and SQLITE_OK returned, just as if no corruption had
   42901 ** been encountered.
   42902 **
   42903 ** If an I/O or malloc() error occurs, the journal-file is not deleted
   42904 ** and an error code is returned.
   42905 **
   42906 ** The isHot parameter indicates that we are trying to rollback a journal
   42907 ** that might be a hot journal.  Or, it could be that the journal is
   42908 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
   42909 ** If the journal really is hot, reset the pager cache prior rolling
   42910 ** back any content.  If the journal is merely persistent, no reset is
   42911 ** needed.
   42912 */
   42913 static int pager_playback(Pager *pPager, int isHot){
   42914   sqlite3_vfs *pVfs = pPager->pVfs;
   42915   i64 szJ;                 /* Size of the journal file in bytes */
   42916   u32 nRec;                /* Number of Records in the journal */
   42917   u32 u;                   /* Unsigned loop counter */
   42918   Pgno mxPg = 0;           /* Size of the original file in pages */
   42919   int rc;                  /* Result code of a subroutine */
   42920   int res = 1;             /* Value returned by sqlite3OsAccess() */
   42921   char *zMaster = 0;       /* Name of master journal file if any */
   42922   int needPagerReset;      /* True to reset page prior to first page rollback */
   42923   int nPlayback = 0;       /* Total number of pages restored from journal */
   42924 
   42925   /* Figure out how many records are in the journal.  Abort early if
   42926   ** the journal is empty.
   42927   */
   42928   assert( isOpen(pPager->jfd) );
   42929   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
   42930   if( rc!=SQLITE_OK ){
   42931     goto end_playback;
   42932   }
   42933 
   42934   /* Read the master journal name from the journal, if it is present.
   42935   ** If a master journal file name is specified, but the file is not
   42936   ** present on disk, then the journal is not hot and does not need to be
   42937   ** played back.
   42938   **
   42939   ** TODO: Technically the following is an error because it assumes that
   42940   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
   42941   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
   42942   **  mxPathname is 512, which is the same as the minimum allowable value
   42943   ** for pageSize.
   42944   */
   42945   zMaster = pPager->pTmpSpace;
   42946   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   42947   if( rc==SQLITE_OK && zMaster[0] ){
   42948     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   42949   }
   42950   zMaster = 0;
   42951   if( rc!=SQLITE_OK || !res ){
   42952     goto end_playback;
   42953   }
   42954   pPager->journalOff = 0;
   42955   needPagerReset = isHot;
   42956 
   42957   /* This loop terminates either when a readJournalHdr() or
   42958   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
   42959   ** occurs.
   42960   */
   42961   while( 1 ){
   42962     /* Read the next journal header from the journal file.  If there are
   42963     ** not enough bytes left in the journal file for a complete header, or
   42964     ** it is corrupted, then a process must have failed while writing it.
   42965     ** This indicates nothing more needs to be rolled back.
   42966     */
   42967     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
   42968     if( rc!=SQLITE_OK ){
   42969       if( rc==SQLITE_DONE ){
   42970         rc = SQLITE_OK;
   42971       }
   42972       goto end_playback;
   42973     }
   42974 
   42975     /* If nRec is 0xffffffff, then this journal was created by a process
   42976     ** working in no-sync mode. This means that the rest of the journal
   42977     ** file consists of pages, there are no more journal headers. Compute
   42978     ** the value of nRec based on this assumption.
   42979     */
   42980     if( nRec==0xffffffff ){
   42981       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
   42982       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
   42983     }
   42984 
   42985     /* If nRec is 0 and this rollback is of a transaction created by this
   42986     ** process and if this is the final header in the journal, then it means
   42987     ** that this part of the journal was being filled but has not yet been
   42988     ** synced to disk.  Compute the number of pages based on the remaining
   42989     ** size of the file.
   42990     **
   42991     ** The third term of the test was added to fix ticket #2565.
   42992     ** When rolling back a hot journal, nRec==0 always means that the next
   42993     ** chunk of the journal contains zero pages to be rolled back.  But
   42994     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
   42995     ** the journal, it means that the journal might contain additional
   42996     ** pages that need to be rolled back and that the number of pages
   42997     ** should be computed based on the journal file size.
   42998     */
   42999     if( nRec==0 && !isHot &&
   43000         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
   43001       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
   43002     }
   43003 
   43004     /* If this is the first header read from the journal, truncate the
   43005     ** database file back to its original size.
   43006     */
   43007     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
   43008       rc = pager_truncate(pPager, mxPg);
   43009       if( rc!=SQLITE_OK ){
   43010         goto end_playback;
   43011       }
   43012       pPager->dbSize = mxPg;
   43013     }
   43014 
   43015     /* Copy original pages out of the journal and back into the
   43016     ** database file and/or page cache.
   43017     */
   43018     for(u=0; u<nRec; u++){
   43019       if( needPagerReset ){
   43020         pager_reset(pPager);
   43021         needPagerReset = 0;
   43022       }
   43023       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
   43024       if( rc==SQLITE_OK ){
   43025         nPlayback++;
   43026       }else{
   43027         if( rc==SQLITE_DONE ){
   43028           pPager->journalOff = szJ;
   43029           break;
   43030         }else if( rc==SQLITE_IOERR_SHORT_READ ){
   43031           /* If the journal has been truncated, simply stop reading and
   43032           ** processing the journal. This might happen if the journal was
   43033           ** not completely written and synced prior to a crash.  In that
   43034           ** case, the database should have never been written in the
   43035           ** first place so it is OK to simply abandon the rollback. */
   43036           rc = SQLITE_OK;
   43037           goto end_playback;
   43038         }else{
   43039           /* If we are unable to rollback, quit and return the error
   43040           ** code.  This will cause the pager to enter the error state
   43041           ** so that no further harm will be done.  Perhaps the next
   43042           ** process to come along will be able to rollback the database.
   43043           */
   43044           goto end_playback;
   43045         }
   43046       }
   43047     }
   43048   }
   43049   /*NOTREACHED*/
   43050   assert( 0 );
   43051 
   43052 end_playback:
   43053   /* Following a rollback, the database file should be back in its original
   43054   ** state prior to the start of the transaction, so invoke the
   43055   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
   43056   ** assertion that the transaction counter was modified.
   43057   */
   43058 #ifdef SQLITE_DEBUG
   43059   if( pPager->fd->pMethods ){
   43060     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
   43061   }
   43062 #endif
   43063 
   43064   /* If this playback is happening automatically as a result of an IO or
   43065   ** malloc error that occurred after the change-counter was updated but
   43066   ** before the transaction was committed, then the change-counter
   43067   ** modification may just have been reverted. If this happens in exclusive
   43068   ** mode, then subsequent transactions performed by the connection will not
   43069   ** update the change-counter at all. This may lead to cache inconsistency
   43070   ** problems for other processes at some point in the future. So, just
   43071   ** in case this has happened, clear the changeCountDone flag now.
   43072   */
   43073   pPager->changeCountDone = pPager->tempFile;
   43074 
   43075   if( rc==SQLITE_OK ){
   43076     zMaster = pPager->pTmpSpace;
   43077     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   43078     testcase( rc!=SQLITE_OK );
   43079   }
   43080   if( rc==SQLITE_OK
   43081    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   43082   ){
   43083     rc = sqlite3PagerSync(pPager, 0);
   43084   }
   43085   if( rc==SQLITE_OK ){
   43086     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
   43087     testcase( rc!=SQLITE_OK );
   43088   }
   43089   if( rc==SQLITE_OK && zMaster[0] && res ){
   43090     /* If there was a master journal and this routine will return success,
   43091     ** see if it is possible to delete the master journal.
   43092     */
   43093     rc = pager_delmaster(pPager, zMaster);
   43094     testcase( rc!=SQLITE_OK );
   43095   }
   43096   if( isHot && nPlayback ){
   43097     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
   43098                 nPlayback, pPager->zJournal);
   43099   }
   43100 
   43101   /* The Pager.sectorSize variable may have been updated while rolling
   43102   ** back a journal created by a process with a different sector size
   43103   ** value. Reset it to the correct value for this process.
   43104   */
   43105   setSectorSize(pPager);
   43106   return rc;
   43107 }
   43108 
   43109 
   43110 /*
   43111 ** Read the content for page pPg out of the database file and into
   43112 ** pPg->pData. A shared lock or greater must be held on the database
   43113 ** file before this function is called.
   43114 **
   43115 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
   43116 ** the value read from the database file.
   43117 **
   43118 ** If an IO error occurs, then the IO error is returned to the caller.
   43119 ** Otherwise, SQLITE_OK is returned.
   43120 */
   43121 static int readDbPage(PgHdr *pPg, u32 iFrame){
   43122   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
   43123   Pgno pgno = pPg->pgno;       /* Page number to read */
   43124   int rc = SQLITE_OK;          /* Return code */
   43125   int pgsz = pPager->pageSize; /* Number of bytes to read */
   43126 
   43127   assert( pPager->eState>=PAGER_READER && !MEMDB );
   43128   assert( isOpen(pPager->fd) );
   43129 
   43130 #ifndef SQLITE_OMIT_WAL
   43131   if( iFrame ){
   43132     /* Try to pull the page from the write-ahead log. */
   43133     rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
   43134   }else
   43135 #endif
   43136   {
   43137     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
   43138     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
   43139     if( rc==SQLITE_IOERR_SHORT_READ ){
   43140       rc = SQLITE_OK;
   43141     }
   43142   }
   43143 
   43144   if( pgno==1 ){
   43145     if( rc ){
   43146       /* If the read is unsuccessful, set the dbFileVers[] to something
   43147       ** that will never be a valid file version.  dbFileVers[] is a copy
   43148       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
   43149       ** zero or the size of the database in page. Bytes 32..35 and 35..39
   43150       ** should be page numbers which are never 0xffffffff.  So filling
   43151       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
   43152       **
   43153       ** For an encrypted database, the situation is more complex:  bytes
   43154       ** 24..39 of the database are white noise.  But the probability of
   43155       ** white noising equaling 16 bytes of 0xff is vanishingly small so
   43156       ** we should still be ok.
   43157       */
   43158       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
   43159     }else{
   43160       u8 *dbFileVers = &((u8*)pPg->pData)[24];
   43161       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
   43162     }
   43163   }
   43164   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
   43165 
   43166   PAGER_INCR(sqlite3_pager_readdb_count);
   43167   PAGER_INCR(pPager->nRead);
   43168   IOTRACE(("PGIN %p %d\n", pPager, pgno));
   43169   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
   43170                PAGERID(pPager), pgno, pager_pagehash(pPg)));
   43171 
   43172   return rc;
   43173 }
   43174 
   43175 /*
   43176 ** Update the value of the change-counter at offsets 24 and 92 in
   43177 ** the header and the sqlite version number at offset 96.
   43178 **
   43179 ** This is an unconditional update.  See also the pager_incr_changecounter()
   43180 ** routine which only updates the change-counter if the update is actually
   43181 ** needed, as determined by the pPager->changeCountDone state variable.
   43182 */
   43183 static void pager_write_changecounter(PgHdr *pPg){
   43184   u32 change_counter;
   43185 
   43186   /* Increment the value just read and write it back to byte 24. */
   43187   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
   43188   put32bits(((char*)pPg->pData)+24, change_counter);
   43189 
   43190   /* Also store the SQLite version number in bytes 96..99 and in
   43191   ** bytes 92..95 store the change counter for which the version number
   43192   ** is valid. */
   43193   put32bits(((char*)pPg->pData)+92, change_counter);
   43194   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
   43195 }
   43196 
   43197 #ifndef SQLITE_OMIT_WAL
   43198 /*
   43199 ** This function is invoked once for each page that has already been
   43200 ** written into the log file when a WAL transaction is rolled back.
   43201 ** Parameter iPg is the page number of said page. The pCtx argument
   43202 ** is actually a pointer to the Pager structure.
   43203 **
   43204 ** If page iPg is present in the cache, and has no outstanding references,
   43205 ** it is discarded. Otherwise, if there are one or more outstanding
   43206 ** references, the page content is reloaded from the database. If the
   43207 ** attempt to reload content from the database is required and fails,
   43208 ** return an SQLite error code. Otherwise, SQLITE_OK.
   43209 */
   43210 static int pagerUndoCallback(void *pCtx, Pgno iPg){
   43211   int rc = SQLITE_OK;
   43212   Pager *pPager = (Pager *)pCtx;
   43213   PgHdr *pPg;
   43214 
   43215   assert( pagerUseWal(pPager) );
   43216   pPg = sqlite3PagerLookup(pPager, iPg);
   43217   if( pPg ){
   43218     if( sqlite3PcachePageRefcount(pPg)==1 ){
   43219       sqlite3PcacheDrop(pPg);
   43220     }else{
   43221       u32 iFrame = 0;
   43222       rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
   43223       if( rc==SQLITE_OK ){
   43224         rc = readDbPage(pPg, iFrame);
   43225       }
   43226       if( rc==SQLITE_OK ){
   43227         pPager->xReiniter(pPg);
   43228       }
   43229       sqlite3PagerUnrefNotNull(pPg);
   43230     }
   43231   }
   43232 
   43233   /* Normally, if a transaction is rolled back, any backup processes are
   43234   ** updated as data is copied out of the rollback journal and into the
   43235   ** database. This is not generally possible with a WAL database, as
   43236   ** rollback involves simply truncating the log file. Therefore, if one
   43237   ** or more frames have already been written to the log (and therefore
   43238   ** also copied into the backup databases) as part of this transaction,
   43239   ** the backups must be restarted.
   43240   */
   43241   sqlite3BackupRestart(pPager->pBackup);
   43242 
   43243   return rc;
   43244 }
   43245 
   43246 /*
   43247 ** This function is called to rollback a transaction on a WAL database.
   43248 */
   43249 static int pagerRollbackWal(Pager *pPager){
   43250   int rc;                         /* Return Code */
   43251   PgHdr *pList;                   /* List of dirty pages to revert */
   43252 
   43253   /* For all pages in the cache that are currently dirty or have already
   43254   ** been written (but not committed) to the log file, do one of the
   43255   ** following:
   43256   **
   43257   **   + Discard the cached page (if refcount==0), or
   43258   **   + Reload page content from the database (if refcount>0).
   43259   */
   43260   pPager->dbSize = pPager->dbOrigSize;
   43261   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
   43262   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   43263   while( pList && rc==SQLITE_OK ){
   43264     PgHdr *pNext = pList->pDirty;
   43265     rc = pagerUndoCallback((void *)pPager, pList->pgno);
   43266     pList = pNext;
   43267   }
   43268 
   43269   return rc;
   43270 }
   43271 
   43272 /*
   43273 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
   43274 ** the contents of the list of pages headed by pList (connected by pDirty),
   43275 ** this function notifies any active backup processes that the pages have
   43276 ** changed.
   43277 **
   43278 ** The list of pages passed into this routine is always sorted by page number.
   43279 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
   43280 */
   43281 static int pagerWalFrames(
   43282   Pager *pPager,                  /* Pager object */
   43283   PgHdr *pList,                   /* List of frames to log */
   43284   Pgno nTruncate,                 /* Database size after this commit */
   43285   int isCommit                    /* True if this is a commit */
   43286 ){
   43287   int rc;                         /* Return code */
   43288   int nList;                      /* Number of pages in pList */
   43289 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
   43290   PgHdr *p;                       /* For looping over pages */
   43291 #endif
   43292 
   43293   assert( pPager->pWal );
   43294   assert( pList );
   43295 #ifdef SQLITE_DEBUG
   43296   /* Verify that the page list is in accending order */
   43297   for(p=pList; p && p->pDirty; p=p->pDirty){
   43298     assert( p->pgno < p->pDirty->pgno );
   43299   }
   43300 #endif
   43301 
   43302   assert( pList->pDirty==0 || isCommit );
   43303   if( isCommit ){
   43304     /* If a WAL transaction is being committed, there is no point in writing
   43305     ** any pages with page numbers greater than nTruncate into the WAL file.
   43306     ** They will never be read by any client. So remove them from the pDirty
   43307     ** list here. */
   43308     PgHdr *p;
   43309     PgHdr **ppNext = &pList;
   43310     nList = 0;
   43311     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
   43312       if( p->pgno<=nTruncate ){
   43313         ppNext = &p->pDirty;
   43314         nList++;
   43315       }
   43316     }
   43317     assert( pList );
   43318   }else{
   43319     nList = 1;
   43320   }
   43321   pPager->aStat[PAGER_STAT_WRITE] += nList;
   43322 
   43323   if( pList->pgno==1 ) pager_write_changecounter(pList);
   43324   rc = sqlite3WalFrames(pPager->pWal,
   43325       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
   43326   );
   43327   if( rc==SQLITE_OK && pPager->pBackup ){
   43328     PgHdr *p;
   43329     for(p=pList; p; p=p->pDirty){
   43330       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
   43331     }
   43332   }
   43333 
   43334 #ifdef SQLITE_CHECK_PAGES
   43335   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   43336   for(p=pList; p; p=p->pDirty){
   43337     pager_set_pagehash(p);
   43338   }
   43339 #endif
   43340 
   43341   return rc;
   43342 }
   43343 
   43344 /*
   43345 ** Begin a read transaction on the WAL.
   43346 **
   43347 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
   43348 ** makes a snapshot of the database at the current point in time and preserves
   43349 ** that snapshot for use by the reader in spite of concurrently changes by
   43350 ** other writers or checkpointers.
   43351 */
   43352 static int pagerBeginReadTransaction(Pager *pPager){
   43353   int rc;                         /* Return code */
   43354   int changed = 0;                /* True if cache must be reset */
   43355 
   43356   assert( pagerUseWal(pPager) );
   43357   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   43358 
   43359   /* sqlite3WalEndReadTransaction() was not called for the previous
   43360   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
   43361   ** are in locking_mode=NORMAL and EndRead() was previously called,
   43362   ** the duplicate call is harmless.
   43363   */
   43364   sqlite3WalEndReadTransaction(pPager->pWal);
   43365 
   43366   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
   43367   if( rc!=SQLITE_OK || changed ){
   43368     pager_reset(pPager);
   43369     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
   43370   }
   43371 
   43372   return rc;
   43373 }
   43374 #endif
   43375 
   43376 /*
   43377 ** This function is called as part of the transition from PAGER_OPEN
   43378 ** to PAGER_READER state to determine the size of the database file
   43379 ** in pages (assuming the page size currently stored in Pager.pageSize).
   43380 **
   43381 ** If no error occurs, SQLITE_OK is returned and the size of the database
   43382 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
   43383 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
   43384 */
   43385 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
   43386   Pgno nPage;                     /* Value to return via *pnPage */
   43387 
   43388   /* Query the WAL sub-system for the database size. The WalDbsize()
   43389   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
   43390   ** if the database size is not available. The database size is not
   43391   ** available from the WAL sub-system if the log file is empty or
   43392   ** contains no valid committed transactions.
   43393   */
   43394   assert( pPager->eState==PAGER_OPEN );
   43395   assert( pPager->eLock>=SHARED_LOCK );
   43396   nPage = sqlite3WalDbsize(pPager->pWal);
   43397 
   43398   /* If the database size was not available from the WAL sub-system,
   43399   ** determine it based on the size of the database file. If the size
   43400   ** of the database file is not an integer multiple of the page-size,
   43401   ** round down to the nearest page. Except, any file larger than 0
   43402   ** bytes in size is considered to contain at least one page.
   43403   */
   43404   if( nPage==0 ){
   43405     i64 n = 0;                    /* Size of db file in bytes */
   43406     assert( isOpen(pPager->fd) || pPager->tempFile );
   43407     if( isOpen(pPager->fd) ){
   43408       int rc = sqlite3OsFileSize(pPager->fd, &n);
   43409       if( rc!=SQLITE_OK ){
   43410         return rc;
   43411       }
   43412     }
   43413     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
   43414   }
   43415 
   43416   /* If the current number of pages in the file is greater than the
   43417   ** configured maximum pager number, increase the allowed limit so
   43418   ** that the file can be read.
   43419   */
   43420   if( nPage>pPager->mxPgno ){
   43421     pPager->mxPgno = (Pgno)nPage;
   43422   }
   43423 
   43424   *pnPage = nPage;
   43425   return SQLITE_OK;
   43426 }
   43427 
   43428 #ifndef SQLITE_OMIT_WAL
   43429 /*
   43430 ** Check if the *-wal file that corresponds to the database opened by pPager
   43431 ** exists if the database is not empy, or verify that the *-wal file does
   43432 ** not exist (by deleting it) if the database file is empty.
   43433 **
   43434 ** If the database is not empty and the *-wal file exists, open the pager
   43435 ** in WAL mode.  If the database is empty or if no *-wal file exists and
   43436 ** if no error occurs, make sure Pager.journalMode is not set to
   43437 ** PAGER_JOURNALMODE_WAL.
   43438 **
   43439 ** Return SQLITE_OK or an error code.
   43440 **
   43441 ** The caller must hold a SHARED lock on the database file to call this
   43442 ** function. Because an EXCLUSIVE lock on the db file is required to delete
   43443 ** a WAL on a none-empty database, this ensures there is no race condition
   43444 ** between the xAccess() below and an xDelete() being executed by some
   43445 ** other connection.
   43446 */
   43447 static int pagerOpenWalIfPresent(Pager *pPager){
   43448   int rc = SQLITE_OK;
   43449   assert( pPager->eState==PAGER_OPEN );
   43450   assert( pPager->eLock>=SHARED_LOCK );
   43451 
   43452   if( !pPager->tempFile ){
   43453     int isWal;                    /* True if WAL file exists */
   43454     Pgno nPage;                   /* Size of the database file */
   43455 
   43456     rc = pagerPagecount(pPager, &nPage);
   43457     if( rc ) return rc;
   43458     if( nPage==0 ){
   43459       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
   43460       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
   43461       isWal = 0;
   43462     }else{
   43463       rc = sqlite3OsAccess(
   43464           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
   43465       );
   43466     }
   43467     if( rc==SQLITE_OK ){
   43468       if( isWal ){
   43469         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
   43470         rc = sqlite3PagerOpenWal(pPager, 0);
   43471       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
   43472         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
   43473       }
   43474     }
   43475   }
   43476   return rc;
   43477 }
   43478 #endif
   43479 
   43480 /*
   43481 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
   43482 ** the entire master journal file. The case pSavepoint==NULL occurs when
   43483 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
   43484 ** savepoint.
   43485 **
   43486 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
   43487 ** being rolled back), then the rollback consists of up to three stages,
   43488 ** performed in the order specified:
   43489 **
   43490 **   * Pages are played back from the main journal starting at byte
   43491 **     offset PagerSavepoint.iOffset and continuing to
   43492 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
   43493 **     file if PagerSavepoint.iHdrOffset is zero.
   43494 **
   43495 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
   43496 **     back starting from the journal header immediately following
   43497 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
   43498 **
   43499 **   * Pages are then played back from the sub-journal file, starting
   43500 **     with the PagerSavepoint.iSubRec and continuing to the end of
   43501 **     the journal file.
   43502 **
   43503 ** Throughout the rollback process, each time a page is rolled back, the
   43504 ** corresponding bit is set in a bitvec structure (variable pDone in the
   43505 ** implementation below). This is used to ensure that a page is only
   43506 ** rolled back the first time it is encountered in either journal.
   43507 **
   43508 ** If pSavepoint is NULL, then pages are only played back from the main
   43509 ** journal file. There is no need for a bitvec in this case.
   43510 **
   43511 ** In either case, before playback commences the Pager.dbSize variable
   43512 ** is reset to the value that it held at the start of the savepoint
   43513 ** (or transaction). No page with a page-number greater than this value
   43514 ** is played back. If one is encountered it is simply skipped.
   43515 */
   43516 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
   43517   i64 szJ;                 /* Effective size of the main journal */
   43518   i64 iHdrOff;             /* End of first segment of main-journal records */
   43519   int rc = SQLITE_OK;      /* Return code */
   43520   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
   43521 
   43522   assert( pPager->eState!=PAGER_ERROR );
   43523   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   43524 
   43525   /* Allocate a bitvec to use to store the set of pages rolled back */
   43526   if( pSavepoint ){
   43527     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
   43528     if( !pDone ){
   43529       return SQLITE_NOMEM;
   43530     }
   43531   }
   43532 
   43533   /* Set the database size back to the value it was before the savepoint
   43534   ** being reverted was opened.
   43535   */
   43536   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
   43537   pPager->changeCountDone = pPager->tempFile;
   43538 
   43539   if( !pSavepoint && pagerUseWal(pPager) ){
   43540     return pagerRollbackWal(pPager);
   43541   }
   43542 
   43543   /* Use pPager->journalOff as the effective size of the main rollback
   43544   ** journal.  The actual file might be larger than this in
   43545   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
   43546   ** past pPager->journalOff is off-limits to us.
   43547   */
   43548   szJ = pPager->journalOff;
   43549   assert( pagerUseWal(pPager)==0 || szJ==0 );
   43550 
   43551   /* Begin by rolling back records from the main journal starting at
   43552   ** PagerSavepoint.iOffset and continuing to the next journal header.
   43553   ** There might be records in the main journal that have a page number
   43554   ** greater than the current database size (pPager->dbSize) but those
   43555   ** will be skipped automatically.  Pages are added to pDone as they
   43556   ** are played back.
   43557   */
   43558   if( pSavepoint && !pagerUseWal(pPager) ){
   43559     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
   43560     pPager->journalOff = pSavepoint->iOffset;
   43561     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
   43562       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   43563     }
   43564     assert( rc!=SQLITE_DONE );
   43565   }else{
   43566     pPager->journalOff = 0;
   43567   }
   43568 
   43569   /* Continue rolling back records out of the main journal starting at
   43570   ** the first journal header seen and continuing until the effective end
   43571   ** of the main journal file.  Continue to skip out-of-range pages and
   43572   ** continue adding pages rolled back to pDone.
   43573   */
   43574   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
   43575     u32 ii;            /* Loop counter */
   43576     u32 nJRec = 0;     /* Number of Journal Records */
   43577     u32 dummy;
   43578     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
   43579     assert( rc!=SQLITE_DONE );
   43580 
   43581     /*
   43582     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
   43583     ** test is related to ticket #2565.  See the discussion in the
   43584     ** pager_playback() function for additional information.
   43585     */
   43586     if( nJRec==0
   43587      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
   43588     ){
   43589       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
   43590     }
   43591     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
   43592       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   43593     }
   43594     assert( rc!=SQLITE_DONE );
   43595   }
   43596   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
   43597 
   43598   /* Finally,  rollback pages from the sub-journal.  Page that were
   43599   ** previously rolled back out of the main journal (and are hence in pDone)
   43600   ** will be skipped.  Out-of-range pages are also skipped.
   43601   */
   43602   if( pSavepoint ){
   43603     u32 ii;            /* Loop counter */
   43604     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
   43605 
   43606     if( pagerUseWal(pPager) ){
   43607       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
   43608     }
   43609     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
   43610       assert( offset==(i64)ii*(4+pPager->pageSize) );
   43611       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
   43612     }
   43613     assert( rc!=SQLITE_DONE );
   43614   }
   43615 
   43616   sqlite3BitvecDestroy(pDone);
   43617   if( rc==SQLITE_OK ){
   43618     pPager->journalOff = szJ;
   43619   }
   43620 
   43621   return rc;
   43622 }
   43623 
   43624 /*
   43625 ** Change the maximum number of in-memory pages that are allowed.
   43626 */
   43627 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
   43628   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
   43629 }
   43630 
   43631 /*
   43632 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
   43633 */
   43634 static void pagerFixMaplimit(Pager *pPager){
   43635 #if SQLITE_MAX_MMAP_SIZE>0
   43636   sqlite3_file *fd = pPager->fd;
   43637   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
   43638     sqlite3_int64 sz;
   43639     sz = pPager->szMmap;
   43640     pPager->bUseFetch = (sz>0);
   43641     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
   43642   }
   43643 #endif
   43644 }
   43645 
   43646 /*
   43647 ** Change the maximum size of any memory mapping made of the database file.
   43648 */
   43649 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
   43650   pPager->szMmap = szMmap;
   43651   pagerFixMaplimit(pPager);
   43652 }
   43653 
   43654 /*
   43655 ** Free as much memory as possible from the pager.
   43656 */
   43657 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
   43658   sqlite3PcacheShrink(pPager->pPCache);
   43659 }
   43660 
   43661 /*
   43662 ** Adjust settings of the pager to those specified in the pgFlags parameter.
   43663 **
   43664 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
   43665 ** of the database to damage due to OS crashes or power failures by
   43666 ** changing the number of syncs()s when writing the journals.
   43667 ** There are three levels:
   43668 **
   43669 **    OFF       sqlite3OsSync() is never called.  This is the default
   43670 **              for temporary and transient files.
   43671 **
   43672 **    NORMAL    The journal is synced once before writes begin on the
   43673 **              database.  This is normally adequate protection, but
   43674 **              it is theoretically possible, though very unlikely,
   43675 **              that an inopertune power failure could leave the journal
   43676 **              in a state which would cause damage to the database
   43677 **              when it is rolled back.
   43678 **
   43679 **    FULL      The journal is synced twice before writes begin on the
   43680 **              database (with some additional information - the nRec field
   43681 **              of the journal header - being written in between the two
   43682 **              syncs).  If we assume that writing a
   43683 **              single disk sector is atomic, then this mode provides
   43684 **              assurance that the journal will not be corrupted to the
   43685 **              point of causing damage to the database during rollback.
   43686 **
   43687 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
   43688 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
   43689 ** prior to the start of checkpoint and that the database file is synced
   43690 ** at the conclusion of the checkpoint if the entire content of the WAL
   43691 ** was written back into the database.  But no sync operations occur for
   43692 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
   43693 ** file is synced following each commit operation, in addition to the
   43694 ** syncs associated with NORMAL.
   43695 **
   43696 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
   43697 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
   43698 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
   43699 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
   43700 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
   43701 ** synchronous=FULL versus synchronous=NORMAL setting determines when
   43702 ** the xSync primitive is called and is relevant to all platforms.
   43703 **
   43704 ** Numeric values associated with these states are OFF==1, NORMAL=2,
   43705 ** and FULL=3.
   43706 */
   43707 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   43708 SQLITE_PRIVATE void sqlite3PagerSetFlags(
   43709   Pager *pPager,        /* The pager to set safety level for */
   43710   unsigned pgFlags      /* Various flags */
   43711 ){
   43712   unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
   43713   assert( level>=1 && level<=3 );
   43714   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
   43715   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
   43716   if( pPager->noSync ){
   43717     pPager->syncFlags = 0;
   43718     pPager->ckptSyncFlags = 0;
   43719   }else if( pgFlags & PAGER_FULLFSYNC ){
   43720     pPager->syncFlags = SQLITE_SYNC_FULL;
   43721     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   43722   }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
   43723     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   43724     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   43725   }else{
   43726     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   43727     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   43728   }
   43729   pPager->walSyncFlags = pPager->syncFlags;
   43730   if( pPager->fullSync ){
   43731     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
   43732   }
   43733   if( pgFlags & PAGER_CACHESPILL ){
   43734     pPager->doNotSpill &= ~SPILLFLAG_OFF;
   43735   }else{
   43736     pPager->doNotSpill |= SPILLFLAG_OFF;
   43737   }
   43738 }
   43739 #endif
   43740 
   43741 /*
   43742 ** The following global variable is incremented whenever the library
   43743 ** attempts to open a temporary file.  This information is used for
   43744 ** testing and analysis only.
   43745 */
   43746 #ifdef SQLITE_TEST
   43747 SQLITE_API int sqlite3_opentemp_count = 0;
   43748 #endif
   43749 
   43750 /*
   43751 ** Open a temporary file.
   43752 **
   43753 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
   43754 ** or some other error code if we fail. The OS will automatically
   43755 ** delete the temporary file when it is closed.
   43756 **
   43757 ** The flags passed to the VFS layer xOpen() call are those specified
   43758 ** by parameter vfsFlags ORed with the following:
   43759 **
   43760 **     SQLITE_OPEN_READWRITE
   43761 **     SQLITE_OPEN_CREATE
   43762 **     SQLITE_OPEN_EXCLUSIVE
   43763 **     SQLITE_OPEN_DELETEONCLOSE
   43764 */
   43765 static int pagerOpentemp(
   43766   Pager *pPager,        /* The pager object */
   43767   sqlite3_file *pFile,  /* Write the file descriptor here */
   43768   int vfsFlags          /* Flags passed through to the VFS */
   43769 ){
   43770   int rc;               /* Return code */
   43771 
   43772 #ifdef SQLITE_TEST
   43773   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
   43774 #endif
   43775 
   43776   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
   43777             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
   43778   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
   43779   assert( rc!=SQLITE_OK || isOpen(pFile) );
   43780   return rc;
   43781 }
   43782 
   43783 /*
   43784 ** Set the busy handler function.
   43785 **
   43786 ** The pager invokes the busy-handler if sqlite3OsLock() returns
   43787 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
   43788 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
   43789 ** lock. It does *not* invoke the busy handler when upgrading from
   43790 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
   43791 ** (which occurs during hot-journal rollback). Summary:
   43792 **
   43793 **   Transition                        | Invokes xBusyHandler
   43794 **   --------------------------------------------------------
   43795 **   NO_LOCK       -> SHARED_LOCK      | Yes
   43796 **   SHARED_LOCK   -> RESERVED_LOCK    | No
   43797 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
   43798 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
   43799 **
   43800 ** If the busy-handler callback returns non-zero, the lock is
   43801 ** retried. If it returns zero, then the SQLITE_BUSY error is
   43802 ** returned to the caller of the pager API function.
   43803 */
   43804 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
   43805   Pager *pPager,                       /* Pager object */
   43806   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
   43807   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
   43808 ){
   43809   pPager->xBusyHandler = xBusyHandler;
   43810   pPager->pBusyHandlerArg = pBusyHandlerArg;
   43811 
   43812   if( isOpen(pPager->fd) ){
   43813     void **ap = (void **)&pPager->xBusyHandler;
   43814     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
   43815     assert( ap[1]==pBusyHandlerArg );
   43816     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
   43817   }
   43818 }
   43819 
   43820 /*
   43821 ** Change the page size used by the Pager object. The new page size
   43822 ** is passed in *pPageSize.
   43823 **
   43824 ** If the pager is in the error state when this function is called, it
   43825 ** is a no-op. The value returned is the error state error code (i.e.
   43826 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
   43827 **
   43828 ** Otherwise, if all of the following are true:
   43829 **
   43830 **   * the new page size (value of *pPageSize) is valid (a power
   43831 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
   43832 **
   43833 **   * there are no outstanding page references, and
   43834 **
   43835 **   * the database is either not an in-memory database or it is
   43836 **     an in-memory database that currently consists of zero pages.
   43837 **
   43838 ** then the pager object page size is set to *pPageSize.
   43839 **
   43840 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
   43841 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
   43842 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
   43843 ** In all other cases, SQLITE_OK is returned.
   43844 **
   43845 ** If the page size is not changed, either because one of the enumerated
   43846 ** conditions above is not true, the pager was in error state when this
   43847 ** function was called, or because the memory allocation attempt failed,
   43848 ** then *pPageSize is set to the old, retained page size before returning.
   43849 */
   43850 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
   43851   int rc = SQLITE_OK;
   43852 
   43853   /* It is not possible to do a full assert_pager_state() here, as this
   43854   ** function may be called from within PagerOpen(), before the state
   43855   ** of the Pager object is internally consistent.
   43856   **
   43857   ** At one point this function returned an error if the pager was in
   43858   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
   43859   ** there is at least one outstanding page reference, this function
   43860   ** is a no-op for that case anyhow.
   43861   */
   43862 
   43863   u32 pageSize = *pPageSize;
   43864   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
   43865   if( (pPager->memDb==0 || pPager->dbSize==0)
   43866    && sqlite3PcacheRefCount(pPager->pPCache)==0
   43867    && pageSize && pageSize!=(u32)pPager->pageSize
   43868   ){
   43869     char *pNew = NULL;             /* New temp space */
   43870     i64 nByte = 0;
   43871 
   43872     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
   43873       rc = sqlite3OsFileSize(pPager->fd, &nByte);
   43874     }
   43875     if( rc==SQLITE_OK ){
   43876       pNew = (char *)sqlite3PageMalloc(pageSize);
   43877       if( !pNew ) rc = SQLITE_NOMEM;
   43878     }
   43879 
   43880     if( rc==SQLITE_OK ){
   43881       pager_reset(pPager);
   43882       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
   43883       pPager->pageSize = pageSize;
   43884       sqlite3PageFree(pPager->pTmpSpace);
   43885       pPager->pTmpSpace = pNew;
   43886       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
   43887     }
   43888   }
   43889 
   43890   *pPageSize = pPager->pageSize;
   43891   if( rc==SQLITE_OK ){
   43892     if( nReserve<0 ) nReserve = pPager->nReserve;
   43893     assert( nReserve>=0 && nReserve<1000 );
   43894     pPager->nReserve = (i16)nReserve;
   43895     pagerReportSize(pPager);
   43896     pagerFixMaplimit(pPager);
   43897   }
   43898   return rc;
   43899 }
   43900 
   43901 /*
   43902 ** Return a pointer to the "temporary page" buffer held internally
   43903 ** by the pager.  This is a buffer that is big enough to hold the
   43904 ** entire content of a database page.  This buffer is used internally
   43905 ** during rollback and will be overwritten whenever a rollback
   43906 ** occurs.  But other modules are free to use it too, as long as
   43907 ** no rollbacks are happening.
   43908 */
   43909 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
   43910   return pPager->pTmpSpace;
   43911 }
   43912 
   43913 /*
   43914 ** Attempt to set the maximum database page count if mxPage is positive.
   43915 ** Make no changes if mxPage is zero or negative.  And never reduce the
   43916 ** maximum page count below the current size of the database.
   43917 **
   43918 ** Regardless of mxPage, return the current maximum page count.
   43919 */
   43920 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
   43921   if( mxPage>0 ){
   43922     pPager->mxPgno = mxPage;
   43923   }
   43924   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
   43925   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
   43926   return pPager->mxPgno;
   43927 }
   43928 
   43929 /*
   43930 ** The following set of routines are used to disable the simulated
   43931 ** I/O error mechanism.  These routines are used to avoid simulated
   43932 ** errors in places where we do not care about errors.
   43933 **
   43934 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
   43935 ** and generate no code.
   43936 */
   43937 #ifdef SQLITE_TEST
   43938 SQLITE_API extern int sqlite3_io_error_pending;
   43939 SQLITE_API extern int sqlite3_io_error_hit;
   43940 static int saved_cnt;
   43941 void disable_simulated_io_errors(void){
   43942   saved_cnt = sqlite3_io_error_pending;
   43943   sqlite3_io_error_pending = -1;
   43944 }
   43945 void enable_simulated_io_errors(void){
   43946   sqlite3_io_error_pending = saved_cnt;
   43947 }
   43948 #else
   43949 # define disable_simulated_io_errors()
   43950 # define enable_simulated_io_errors()
   43951 #endif
   43952 
   43953 /*
   43954 ** Read the first N bytes from the beginning of the file into memory
   43955 ** that pDest points to.
   43956 **
   43957 ** If the pager was opened on a transient file (zFilename==""), or
   43958 ** opened on a file less than N bytes in size, the output buffer is
   43959 ** zeroed and SQLITE_OK returned. The rationale for this is that this
   43960 ** function is used to read database headers, and a new transient or
   43961 ** zero sized database has a header than consists entirely of zeroes.
   43962 **
   43963 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
   43964 ** the error code is returned to the caller and the contents of the
   43965 ** output buffer undefined.
   43966 */
   43967 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
   43968   int rc = SQLITE_OK;
   43969   memset(pDest, 0, N);
   43970   assert( isOpen(pPager->fd) || pPager->tempFile );
   43971 
   43972   /* This routine is only called by btree immediately after creating
   43973   ** the Pager object.  There has not been an opportunity to transition
   43974   ** to WAL mode yet.
   43975   */
   43976   assert( !pagerUseWal(pPager) );
   43977 
   43978   if( isOpen(pPager->fd) ){
   43979     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
   43980     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
   43981     if( rc==SQLITE_IOERR_SHORT_READ ){
   43982       rc = SQLITE_OK;
   43983     }
   43984   }
   43985   return rc;
   43986 }
   43987 
   43988 /*
   43989 ** This function may only be called when a read-transaction is open on
   43990 ** the pager. It returns the total number of pages in the database.
   43991 **
   43992 ** However, if the file is between 1 and <page-size> bytes in size, then
   43993 ** this is considered a 1 page file.
   43994 */
   43995 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
   43996   assert( pPager->eState>=PAGER_READER );
   43997   assert( pPager->eState!=PAGER_WRITER_FINISHED );
   43998   *pnPage = (int)pPager->dbSize;
   43999 }
   44000 
   44001 
   44002 /*
   44003 ** Try to obtain a lock of type locktype on the database file. If
   44004 ** a similar or greater lock is already held, this function is a no-op
   44005 ** (returning SQLITE_OK immediately).
   44006 **
   44007 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
   44008 ** the busy callback if the lock is currently not available. Repeat
   44009 ** until the busy callback returns false or until the attempt to
   44010 ** obtain the lock succeeds.
   44011 **
   44012 ** Return SQLITE_OK on success and an error code if we cannot obtain
   44013 ** the lock. If the lock is obtained successfully, set the Pager.state
   44014 ** variable to locktype before returning.
   44015 */
   44016 static int pager_wait_on_lock(Pager *pPager, int locktype){
   44017   int rc;                              /* Return code */
   44018 
   44019   /* Check that this is either a no-op (because the requested lock is
   44020   ** already held, or one of the transistions that the busy-handler
   44021   ** may be invoked during, according to the comment above
   44022   ** sqlite3PagerSetBusyhandler().
   44023   */
   44024   assert( (pPager->eLock>=locktype)
   44025        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
   44026        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
   44027   );
   44028 
   44029   do {
   44030     rc = pagerLockDb(pPager, locktype);
   44031   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
   44032   return rc;
   44033 }
   44034 
   44035 /*
   44036 ** Function assertTruncateConstraint(pPager) checks that one of the
   44037 ** following is true for all dirty pages currently in the page-cache:
   44038 **
   44039 **   a) The page number is less than or equal to the size of the
   44040 **      current database image, in pages, OR
   44041 **
   44042 **   b) if the page content were written at this time, it would not
   44043 **      be necessary to write the current content out to the sub-journal
   44044 **      (as determined by function subjRequiresPage()).
   44045 **
   44046 ** If the condition asserted by this function were not true, and the
   44047 ** dirty page were to be discarded from the cache via the pagerStress()
   44048 ** routine, pagerStress() would not write the current page content to
   44049 ** the database file. If a savepoint transaction were rolled back after
   44050 ** this happened, the correct behavior would be to restore the current
   44051 ** content of the page. However, since this content is not present in either
   44052 ** the database file or the portion of the rollback journal and
   44053 ** sub-journal rolled back the content could not be restored and the
   44054 ** database image would become corrupt. It is therefore fortunate that
   44055 ** this circumstance cannot arise.
   44056 */
   44057 #if defined(SQLITE_DEBUG)
   44058 static void assertTruncateConstraintCb(PgHdr *pPg){
   44059   assert( pPg->flags&PGHDR_DIRTY );
   44060   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
   44061 }
   44062 static void assertTruncateConstraint(Pager *pPager){
   44063   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
   44064 }
   44065 #else
   44066 # define assertTruncateConstraint(pPager)
   44067 #endif
   44068 
   44069 /*
   44070 ** Truncate the in-memory database file image to nPage pages. This
   44071 ** function does not actually modify the database file on disk. It
   44072 ** just sets the internal state of the pager object so that the
   44073 ** truncation will be done when the current transaction is committed.
   44074 **
   44075 ** This function is only called right before committing a transaction.
   44076 ** Once this function has been called, the transaction must either be
   44077 ** rolled back or committed. It is not safe to call this function and
   44078 ** then continue writing to the database.
   44079 */
   44080 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
   44081   assert( pPager->dbSize>=nPage );
   44082   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   44083   pPager->dbSize = nPage;
   44084 
   44085   /* At one point the code here called assertTruncateConstraint() to
   44086   ** ensure that all pages being truncated away by this operation are,
   44087   ** if one or more savepoints are open, present in the savepoint
   44088   ** journal so that they can be restored if the savepoint is rolled
   44089   ** back. This is no longer necessary as this function is now only
   44090   ** called right before committing a transaction. So although the
   44091   ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
   44092   ** they cannot be rolled back. So the assertTruncateConstraint() call
   44093   ** is no longer correct. */
   44094 }
   44095 
   44096 
   44097 /*
   44098 ** This function is called before attempting a hot-journal rollback. It
   44099 ** syncs the journal file to disk, then sets pPager->journalHdr to the
   44100 ** size of the journal file so that the pager_playback() routine knows
   44101 ** that the entire journal file has been synced.
   44102 **
   44103 ** Syncing a hot-journal to disk before attempting to roll it back ensures
   44104 ** that if a power-failure occurs during the rollback, the process that
   44105 ** attempts rollback following system recovery sees the same journal
   44106 ** content as this process.
   44107 **
   44108 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
   44109 ** an SQLite error code.
   44110 */
   44111 static int pagerSyncHotJournal(Pager *pPager){
   44112   int rc = SQLITE_OK;
   44113   if( !pPager->noSync ){
   44114     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
   44115   }
   44116   if( rc==SQLITE_OK ){
   44117     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
   44118   }
   44119   return rc;
   44120 }
   44121 
   44122 /*
   44123 ** Obtain a reference to a memory mapped page object for page number pgno.
   44124 ** The new object will use the pointer pData, obtained from xFetch().
   44125 ** If successful, set *ppPage to point to the new page reference
   44126 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
   44127 ** *ppPage to zero.
   44128 **
   44129 ** Page references obtained by calling this function should be released
   44130 ** by calling pagerReleaseMapPage().
   44131 */
   44132 static int pagerAcquireMapPage(
   44133   Pager *pPager,                  /* Pager object */
   44134   Pgno pgno,                      /* Page number */
   44135   void *pData,                    /* xFetch()'d data for this page */
   44136   PgHdr **ppPage                  /* OUT: Acquired page object */
   44137 ){
   44138   PgHdr *p;                       /* Memory mapped page to return */
   44139 
   44140   if( pPager->pMmapFreelist ){
   44141     *ppPage = p = pPager->pMmapFreelist;
   44142     pPager->pMmapFreelist = p->pDirty;
   44143     p->pDirty = 0;
   44144     memset(p->pExtra, 0, pPager->nExtra);
   44145   }else{
   44146     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
   44147     if( p==0 ){
   44148       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
   44149       return SQLITE_NOMEM;
   44150     }
   44151     p->pExtra = (void *)&p[1];
   44152     p->flags = PGHDR_MMAP;
   44153     p->nRef = 1;
   44154     p->pPager = pPager;
   44155   }
   44156 
   44157   assert( p->pExtra==(void *)&p[1] );
   44158   assert( p->pPage==0 );
   44159   assert( p->flags==PGHDR_MMAP );
   44160   assert( p->pPager==pPager );
   44161   assert( p->nRef==1 );
   44162 
   44163   p->pgno = pgno;
   44164   p->pData = pData;
   44165   pPager->nMmapOut++;
   44166 
   44167   return SQLITE_OK;
   44168 }
   44169 
   44170 /*
   44171 ** Release a reference to page pPg. pPg must have been returned by an
   44172 ** earlier call to pagerAcquireMapPage().
   44173 */
   44174 static void pagerReleaseMapPage(PgHdr *pPg){
   44175   Pager *pPager = pPg->pPager;
   44176   pPager->nMmapOut--;
   44177   pPg->pDirty = pPager->pMmapFreelist;
   44178   pPager->pMmapFreelist = pPg;
   44179 
   44180   assert( pPager->fd->pMethods->iVersion>=3 );
   44181   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
   44182 }
   44183 
   44184 /*
   44185 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
   44186 */
   44187 static void pagerFreeMapHdrs(Pager *pPager){
   44188   PgHdr *p;
   44189   PgHdr *pNext;
   44190   for(p=pPager->pMmapFreelist; p; p=pNext){
   44191     pNext = p->pDirty;
   44192     sqlite3_free(p);
   44193   }
   44194 }
   44195 
   44196 
   44197 /*
   44198 ** Shutdown the page cache.  Free all memory and close all files.
   44199 **
   44200 ** If a transaction was in progress when this routine is called, that
   44201 ** transaction is rolled back.  All outstanding pages are invalidated
   44202 ** and their memory is freed.  Any attempt to use a page associated
   44203 ** with this page cache after this function returns will likely
   44204 ** result in a coredump.
   44205 **
   44206 ** This function always succeeds. If a transaction is active an attempt
   44207 ** is made to roll it back. If an error occurs during the rollback
   44208 ** a hot journal may be left in the filesystem but no error is returned
   44209 ** to the caller.
   44210 */
   44211 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
   44212   u8 *pTmp = (u8 *)pPager->pTmpSpace;
   44213 
   44214   assert( assert_pager_state(pPager) );
   44215   disable_simulated_io_errors();
   44216   sqlite3BeginBenignMalloc();
   44217   pagerFreeMapHdrs(pPager);
   44218   /* pPager->errCode = 0; */
   44219   pPager->exclusiveMode = 0;
   44220 #ifndef SQLITE_OMIT_WAL
   44221   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
   44222   pPager->pWal = 0;
   44223 #endif
   44224   pager_reset(pPager);
   44225   if( MEMDB ){
   44226     pager_unlock(pPager);
   44227   }else{
   44228     /* If it is open, sync the journal file before calling UnlockAndRollback.
   44229     ** If this is not done, then an unsynced portion of the open journal
   44230     ** file may be played back into the database. If a power failure occurs
   44231     ** while this is happening, the database could become corrupt.
   44232     **
   44233     ** If an error occurs while trying to sync the journal, shift the pager
   44234     ** into the ERROR state. This causes UnlockAndRollback to unlock the
   44235     ** database and close the journal file without attempting to roll it
   44236     ** back or finalize it. The next database user will have to do hot-journal
   44237     ** rollback before accessing the database file.
   44238     */
   44239     if( isOpen(pPager->jfd) ){
   44240       pager_error(pPager, pagerSyncHotJournal(pPager));
   44241     }
   44242     pagerUnlockAndRollback(pPager);
   44243   }
   44244   sqlite3EndBenignMalloc();
   44245   enable_simulated_io_errors();
   44246   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
   44247   IOTRACE(("CLOSE %p\n", pPager))
   44248   sqlite3OsClose(pPager->jfd);
   44249   sqlite3OsClose(pPager->fd);
   44250   sqlite3PageFree(pTmp);
   44251   sqlite3PcacheClose(pPager->pPCache);
   44252 
   44253 #ifdef SQLITE_HAS_CODEC
   44254   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   44255 #endif
   44256 
   44257   assert( !pPager->aSavepoint && !pPager->pInJournal );
   44258   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
   44259 
   44260   sqlite3_free(pPager);
   44261   return SQLITE_OK;
   44262 }
   44263 
   44264 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   44265 /*
   44266 ** Return the page number for page pPg.
   44267 */
   44268 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
   44269   return pPg->pgno;
   44270 }
   44271 #endif
   44272 
   44273 /*
   44274 ** Increment the reference count for page pPg.
   44275 */
   44276 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
   44277   sqlite3PcacheRef(pPg);
   44278 }
   44279 
   44280 /*
   44281 ** Sync the journal. In other words, make sure all the pages that have
   44282 ** been written to the journal have actually reached the surface of the
   44283 ** disk and can be restored in the event of a hot-journal rollback.
   44284 **
   44285 ** If the Pager.noSync flag is set, then this function is a no-op.
   44286 ** Otherwise, the actions required depend on the journal-mode and the
   44287 ** device characteristics of the file-system, as follows:
   44288 **
   44289 **   * If the journal file is an in-memory journal file, no action need
   44290 **     be taken.
   44291 **
   44292 **   * Otherwise, if the device does not support the SAFE_APPEND property,
   44293 **     then the nRec field of the most recently written journal header
   44294 **     is updated to contain the number of journal records that have
   44295 **     been written following it. If the pager is operating in full-sync
   44296 **     mode, then the journal file is synced before this field is updated.
   44297 **
   44298 **   * If the device does not support the SEQUENTIAL property, then
   44299 **     journal file is synced.
   44300 **
   44301 ** Or, in pseudo-code:
   44302 **
   44303 **   if( NOT <in-memory journal> ){
   44304 **     if( NOT SAFE_APPEND ){
   44305 **       if( <full-sync mode> ) xSync(<journal file>);
   44306 **       <update nRec field>
   44307 **     }
   44308 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
   44309 **   }
   44310 **
   44311 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
   44312 ** page currently held in memory before returning SQLITE_OK. If an IO
   44313 ** error is encountered, then the IO error code is returned to the caller.
   44314 */
   44315 static int syncJournal(Pager *pPager, int newHdr){
   44316   int rc;                         /* Return code */
   44317 
   44318   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   44319        || pPager->eState==PAGER_WRITER_DBMOD
   44320   );
   44321   assert( assert_pager_state(pPager) );
   44322   assert( !pagerUseWal(pPager) );
   44323 
   44324   rc = sqlite3PagerExclusiveLock(pPager);
   44325   if( rc!=SQLITE_OK ) return rc;
   44326 
   44327   if( !pPager->noSync ){
   44328     assert( !pPager->tempFile );
   44329     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
   44330       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   44331       assert( isOpen(pPager->jfd) );
   44332 
   44333       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   44334         /* This block deals with an obscure problem. If the last connection
   44335         ** that wrote to this database was operating in persistent-journal
   44336         ** mode, then the journal file may at this point actually be larger
   44337         ** than Pager.journalOff bytes. If the next thing in the journal
   44338         ** file happens to be a journal-header (written as part of the
   44339         ** previous connection's transaction), and a crash or power-failure
   44340         ** occurs after nRec is updated but before this connection writes
   44341         ** anything else to the journal file (or commits/rolls back its
   44342         ** transaction), then SQLite may become confused when doing the
   44343         ** hot-journal rollback following recovery. It may roll back all
   44344         ** of this connections data, then proceed to rolling back the old,
   44345         ** out-of-date data that follows it. Database corruption.
   44346         **
   44347         ** To work around this, if the journal file does appear to contain
   44348         ** a valid header following Pager.journalOff, then write a 0x00
   44349         ** byte to the start of it to prevent it from being recognized.
   44350         **
   44351         ** Variable iNextHdrOffset is set to the offset at which this
   44352         ** problematic header will occur, if it exists. aMagic is used
   44353         ** as a temporary buffer to inspect the first couple of bytes of
   44354         ** the potential journal header.
   44355         */
   44356         i64 iNextHdrOffset;
   44357         u8 aMagic[8];
   44358         u8 zHeader[sizeof(aJournalMagic)+4];
   44359 
   44360         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   44361         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
   44362 
   44363         iNextHdrOffset = journalHdrOffset(pPager);
   44364         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
   44365         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
   44366           static const u8 zerobyte = 0;
   44367           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
   44368         }
   44369         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   44370           return rc;
   44371         }
   44372 
   44373         /* Write the nRec value into the journal file header. If in
   44374         ** full-synchronous mode, sync the journal first. This ensures that
   44375         ** all data has really hit the disk before nRec is updated to mark
   44376         ** it as a candidate for rollback.
   44377         **
   44378         ** This is not required if the persistent media supports the
   44379         ** SAFE_APPEND property. Because in this case it is not possible
   44380         ** for garbage data to be appended to the file, the nRec field
   44381         ** is populated with 0xFFFFFFFF when the journal header is written
   44382         ** and never needs to be updated.
   44383         */
   44384         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   44385           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   44386           IOTRACE(("JSYNC %p\n", pPager))
   44387           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
   44388           if( rc!=SQLITE_OK ) return rc;
   44389         }
   44390         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
   44391         rc = sqlite3OsWrite(
   44392             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
   44393         );
   44394         if( rc!=SQLITE_OK ) return rc;
   44395       }
   44396       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   44397         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   44398         IOTRACE(("JSYNC %p\n", pPager))
   44399         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
   44400           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
   44401         );
   44402         if( rc!=SQLITE_OK ) return rc;
   44403       }
   44404 
   44405       pPager->journalHdr = pPager->journalOff;
   44406       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   44407         pPager->nRec = 0;
   44408         rc = writeJournalHdr(pPager);
   44409         if( rc!=SQLITE_OK ) return rc;
   44410       }
   44411     }else{
   44412       pPager->journalHdr = pPager->journalOff;
   44413     }
   44414   }
   44415 
   44416   /* Unless the pager is in noSync mode, the journal file was just
   44417   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
   44418   ** all pages.
   44419   */
   44420   sqlite3PcacheClearSyncFlags(pPager->pPCache);
   44421   pPager->eState = PAGER_WRITER_DBMOD;
   44422   assert( assert_pager_state(pPager) );
   44423   return SQLITE_OK;
   44424 }
   44425 
   44426 /*
   44427 ** The argument is the first in a linked list of dirty pages connected
   44428 ** by the PgHdr.pDirty pointer. This function writes each one of the
   44429 ** in-memory pages in the list to the database file. The argument may
   44430 ** be NULL, representing an empty list. In this case this function is
   44431 ** a no-op.
   44432 **
   44433 ** The pager must hold at least a RESERVED lock when this function
   44434 ** is called. Before writing anything to the database file, this lock
   44435 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
   44436 ** SQLITE_BUSY is returned and no data is written to the database file.
   44437 **
   44438 ** If the pager is a temp-file pager and the actual file-system file
   44439 ** is not yet open, it is created and opened before any data is
   44440 ** written out.
   44441 **
   44442 ** Once the lock has been upgraded and, if necessary, the file opened,
   44443 ** the pages are written out to the database file in list order. Writing
   44444 ** a page is skipped if it meets either of the following criteria:
   44445 **
   44446 **   * The page number is greater than Pager.dbSize, or
   44447 **   * The PGHDR_DONT_WRITE flag is set on the page.
   44448 **
   44449 ** If writing out a page causes the database file to grow, Pager.dbFileSize
   44450 ** is updated accordingly. If page 1 is written out, then the value cached
   44451 ** in Pager.dbFileVers[] is updated to match the new value stored in
   44452 ** the database file.
   44453 **
   44454 ** If everything is successful, SQLITE_OK is returned. If an IO error
   44455 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
   44456 ** be obtained, SQLITE_BUSY is returned.
   44457 */
   44458 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
   44459   int rc = SQLITE_OK;                  /* Return code */
   44460 
   44461   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
   44462   assert( !pagerUseWal(pPager) );
   44463   assert( pPager->eState==PAGER_WRITER_DBMOD );
   44464   assert( pPager->eLock==EXCLUSIVE_LOCK );
   44465 
   44466   /* If the file is a temp-file has not yet been opened, open it now. It
   44467   ** is not possible for rc to be other than SQLITE_OK if this branch
   44468   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
   44469   */
   44470   if( !isOpen(pPager->fd) ){
   44471     assert( pPager->tempFile && rc==SQLITE_OK );
   44472     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
   44473   }
   44474 
   44475   /* Before the first write, give the VFS a hint of what the final
   44476   ** file size will be.
   44477   */
   44478   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
   44479   if( rc==SQLITE_OK
   44480    && pPager->dbHintSize<pPager->dbSize
   44481    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
   44482   ){
   44483     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
   44484     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
   44485     pPager->dbHintSize = pPager->dbSize;
   44486   }
   44487 
   44488   while( rc==SQLITE_OK && pList ){
   44489     Pgno pgno = pList->pgno;
   44490 
   44491     /* If there are dirty pages in the page cache with page numbers greater
   44492     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
   44493     ** make the file smaller (presumably by auto-vacuum code). Do not write
   44494     ** any such pages to the file.
   44495     **
   44496     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
   44497     ** set (set by sqlite3PagerDontWrite()).
   44498     */
   44499     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
   44500       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
   44501       char *pData;                                   /* Data to write */
   44502 
   44503       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
   44504       if( pList->pgno==1 ) pager_write_changecounter(pList);
   44505 
   44506       /* Encode the database */
   44507       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
   44508 
   44509       /* Write out the page data. */
   44510       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
   44511 
   44512       /* If page 1 was just written, update Pager.dbFileVers to match
   44513       ** the value now stored in the database file. If writing this
   44514       ** page caused the database file to grow, update dbFileSize.
   44515       */
   44516       if( pgno==1 ){
   44517         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
   44518       }
   44519       if( pgno>pPager->dbFileSize ){
   44520         pPager->dbFileSize = pgno;
   44521       }
   44522       pPager->aStat[PAGER_STAT_WRITE]++;
   44523 
   44524       /* Update any backup objects copying the contents of this pager. */
   44525       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
   44526 
   44527       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
   44528                    PAGERID(pPager), pgno, pager_pagehash(pList)));
   44529       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
   44530       PAGER_INCR(sqlite3_pager_writedb_count);
   44531     }else{
   44532       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
   44533     }
   44534     pager_set_pagehash(pList);
   44535     pList = pList->pDirty;
   44536   }
   44537 
   44538   return rc;
   44539 }
   44540 
   44541 /*
   44542 ** Ensure that the sub-journal file is open. If it is already open, this
   44543 ** function is a no-op.
   44544 **
   44545 ** SQLITE_OK is returned if everything goes according to plan. An
   44546 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
   44547 ** fails.
   44548 */
   44549 static int openSubJournal(Pager *pPager){
   44550   int rc = SQLITE_OK;
   44551   if( !isOpen(pPager->sjfd) ){
   44552     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
   44553       sqlite3MemJournalOpen(pPager->sjfd);
   44554     }else{
   44555       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
   44556     }
   44557   }
   44558   return rc;
   44559 }
   44560 
   44561 /*
   44562 ** Append a record of the current state of page pPg to the sub-journal.
   44563 ** It is the callers responsibility to use subjRequiresPage() to check
   44564 ** that it is really required before calling this function.
   44565 **
   44566 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
   44567 ** for all open savepoints before returning.
   44568 **
   44569 ** This function returns SQLITE_OK if everything is successful, an IO
   44570 ** error code if the attempt to write to the sub-journal fails, or
   44571 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
   44572 ** bitvec.
   44573 */
   44574 static int subjournalPage(PgHdr *pPg){
   44575   int rc = SQLITE_OK;
   44576   Pager *pPager = pPg->pPager;
   44577   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   44578 
   44579     /* Open the sub-journal, if it has not already been opened */
   44580     assert( pPager->useJournal );
   44581     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
   44582     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
   44583     assert( pagerUseWal(pPager)
   44584          || pageInJournal(pPager, pPg)
   44585          || pPg->pgno>pPager->dbOrigSize
   44586     );
   44587     rc = openSubJournal(pPager);
   44588 
   44589     /* If the sub-journal was opened successfully (or was already open),
   44590     ** write the journal record into the file.  */
   44591     if( rc==SQLITE_OK ){
   44592       void *pData = pPg->pData;
   44593       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
   44594       char *pData2;
   44595 
   44596       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   44597       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
   44598       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
   44599       if( rc==SQLITE_OK ){
   44600         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
   44601       }
   44602     }
   44603   }
   44604   if( rc==SQLITE_OK ){
   44605     pPager->nSubRec++;
   44606     assert( pPager->nSavepoint>0 );
   44607     rc = addToSavepointBitvecs(pPager, pPg->pgno);
   44608   }
   44609   return rc;
   44610 }
   44611 
   44612 /*
   44613 ** This function is called by the pcache layer when it has reached some
   44614 ** soft memory limit. The first argument is a pointer to a Pager object
   44615 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
   44616 ** database). The second argument is a reference to a page that is
   44617 ** currently dirty but has no outstanding references. The page
   44618 ** is always associated with the Pager object passed as the first
   44619 ** argument.
   44620 **
   44621 ** The job of this function is to make pPg clean by writing its contents
   44622 ** out to the database file, if possible. This may involve syncing the
   44623 ** journal file.
   44624 **
   44625 ** If successful, sqlite3PcacheMakeClean() is called on the page and
   44626 ** SQLITE_OK returned. If an IO error occurs while trying to make the
   44627 ** page clean, the IO error code is returned. If the page cannot be
   44628 ** made clean for some other reason, but no error occurs, then SQLITE_OK
   44629 ** is returned by sqlite3PcacheMakeClean() is not called.
   44630 */
   44631 static int pagerStress(void *p, PgHdr *pPg){
   44632   Pager *pPager = (Pager *)p;
   44633   int rc = SQLITE_OK;
   44634 
   44635   assert( pPg->pPager==pPager );
   44636   assert( pPg->flags&PGHDR_DIRTY );
   44637 
   44638   /* The doNotSpill NOSYNC bit is set during times when doing a sync of
   44639   ** journal (and adding a new header) is not allowed.  This occurs
   44640   ** during calls to sqlite3PagerWrite() while trying to journal multiple
   44641   ** pages belonging to the same sector.
   44642   **
   44643   ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
   44644   ** regardless of whether or not a sync is required.  This is set during
   44645   ** a rollback or by user request, respectively.
   44646   **
   44647   ** Spilling is also prohibited when in an error state since that could
   44648   ** lead to database corruption.   In the current implementaton it
   44649   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
   44650   ** while in the error state, hence it is impossible for this routine to
   44651   ** be called in the error state.  Nevertheless, we include a NEVER()
   44652   ** test for the error state as a safeguard against future changes.
   44653   */
   44654   if( NEVER(pPager->errCode) ) return SQLITE_OK;
   44655   testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
   44656   testcase( pPager->doNotSpill & SPILLFLAG_OFF );
   44657   testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
   44658   if( pPager->doNotSpill
   44659    && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
   44660       || (pPg->flags & PGHDR_NEED_SYNC)!=0)
   44661   ){
   44662     return SQLITE_OK;
   44663   }
   44664 
   44665   pPg->pDirty = 0;
   44666   if( pagerUseWal(pPager) ){
   44667     /* Write a single frame for this page to the log. */
   44668     if( subjRequiresPage(pPg) ){
   44669       rc = subjournalPage(pPg);
   44670     }
   44671     if( rc==SQLITE_OK ){
   44672       rc = pagerWalFrames(pPager, pPg, 0, 0);
   44673     }
   44674   }else{
   44675 
   44676     /* Sync the journal file if required. */
   44677     if( pPg->flags&PGHDR_NEED_SYNC
   44678      || pPager->eState==PAGER_WRITER_CACHEMOD
   44679     ){
   44680       rc = syncJournal(pPager, 1);
   44681     }
   44682 
   44683     /* If the page number of this page is larger than the current size of
   44684     ** the database image, it may need to be written to the sub-journal.
   44685     ** This is because the call to pager_write_pagelist() below will not
   44686     ** actually write data to the file in this case.
   44687     **
   44688     ** Consider the following sequence of events:
   44689     **
   44690     **   BEGIN;
   44691     **     <journal page X>
   44692     **     <modify page X>
   44693     **     SAVEPOINT sp;
   44694     **       <shrink database file to Y pages>
   44695     **       pagerStress(page X)
   44696     **     ROLLBACK TO sp;
   44697     **
   44698     ** If (X>Y), then when pagerStress is called page X will not be written
   44699     ** out to the database file, but will be dropped from the cache. Then,
   44700     ** following the "ROLLBACK TO sp" statement, reading page X will read
   44701     ** data from the database file. This will be the copy of page X as it
   44702     ** was when the transaction started, not as it was when "SAVEPOINT sp"
   44703     ** was executed.
   44704     **
   44705     ** The solution is to write the current data for page X into the
   44706     ** sub-journal file now (if it is not already there), so that it will
   44707     ** be restored to its current value when the "ROLLBACK TO sp" is
   44708     ** executed.
   44709     */
   44710     if( NEVER(
   44711         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
   44712     ) ){
   44713       rc = subjournalPage(pPg);
   44714     }
   44715 
   44716     /* Write the contents of the page out to the database file. */
   44717     if( rc==SQLITE_OK ){
   44718       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
   44719       rc = pager_write_pagelist(pPager, pPg);
   44720     }
   44721   }
   44722 
   44723   /* Mark the page as clean. */
   44724   if( rc==SQLITE_OK ){
   44725     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
   44726     sqlite3PcacheMakeClean(pPg);
   44727   }
   44728 
   44729   return pager_error(pPager, rc);
   44730 }
   44731 
   44732 
   44733 /*
   44734 ** Allocate and initialize a new Pager object and put a pointer to it
   44735 ** in *ppPager. The pager should eventually be freed by passing it
   44736 ** to sqlite3PagerClose().
   44737 **
   44738 ** The zFilename argument is the path to the database file to open.
   44739 ** If zFilename is NULL then a randomly-named temporary file is created
   44740 ** and used as the file to be cached. Temporary files are be deleted
   44741 ** automatically when they are closed. If zFilename is ":memory:" then
   44742 ** all information is held in cache. It is never written to disk.
   44743 ** This can be used to implement an in-memory database.
   44744 **
   44745 ** The nExtra parameter specifies the number of bytes of space allocated
   44746 ** along with each page reference. This space is available to the user
   44747 ** via the sqlite3PagerGetExtra() API.
   44748 **
   44749 ** The flags argument is used to specify properties that affect the
   44750 ** operation of the pager. It should be passed some bitwise combination
   44751 ** of the PAGER_* flags.
   44752 **
   44753 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
   44754 ** of the xOpen() method of the supplied VFS when opening files.
   44755 **
   44756 ** If the pager object is allocated and the specified file opened
   44757 ** successfully, SQLITE_OK is returned and *ppPager set to point to
   44758 ** the new pager object. If an error occurs, *ppPager is set to NULL
   44759 ** and error code returned. This function may return SQLITE_NOMEM
   44760 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
   44761 ** various SQLITE_IO_XXX errors.
   44762 */
   44763 SQLITE_PRIVATE int sqlite3PagerOpen(
   44764   sqlite3_vfs *pVfs,       /* The virtual file system to use */
   44765   Pager **ppPager,         /* OUT: Return the Pager structure here */
   44766   const char *zFilename,   /* Name of the database file to open */
   44767   int nExtra,              /* Extra bytes append to each in-memory page */
   44768   int flags,               /* flags controlling this file */
   44769   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
   44770   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
   44771 ){
   44772   u8 *pPtr;
   44773   Pager *pPager = 0;       /* Pager object to allocate and return */
   44774   int rc = SQLITE_OK;      /* Return code */
   44775   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
   44776   int memDb = 0;           /* True if this is an in-memory file */
   44777   int readOnly = 0;        /* True if this is a read-only file */
   44778   int journalFileSize;     /* Bytes to allocate for each journal fd */
   44779   char *zPathname = 0;     /* Full path to database file */
   44780   int nPathname = 0;       /* Number of bytes in zPathname */
   44781   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
   44782   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
   44783   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
   44784   const char *zUri = 0;    /* URI args to copy */
   44785   int nUri = 0;            /* Number of bytes of URI args at *zUri */
   44786 
   44787   /* Figure out how much space is required for each journal file-handle
   44788   ** (there are two of them, the main journal and the sub-journal). This
   44789   ** is the maximum space required for an in-memory journal file handle
   44790   ** and a regular journal file-handle. Note that a "regular journal-handle"
   44791   ** may be a wrapper capable of caching the first portion of the journal
   44792   ** file in memory to implement the atomic-write optimization (see
   44793   ** source file journal.c).
   44794   */
   44795   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
   44796     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
   44797   }else{
   44798     journalFileSize = ROUND8(sqlite3MemJournalSize());
   44799   }
   44800 
   44801   /* Set the output variable to NULL in case an error occurs. */
   44802   *ppPager = 0;
   44803 
   44804 #ifndef SQLITE_OMIT_MEMORYDB
   44805   if( flags & PAGER_MEMORY ){
   44806     memDb = 1;
   44807     if( zFilename && zFilename[0] ){
   44808       zPathname = sqlite3DbStrDup(0, zFilename);
   44809       if( zPathname==0  ) return SQLITE_NOMEM;
   44810       nPathname = sqlite3Strlen30(zPathname);
   44811       zFilename = 0;
   44812     }
   44813   }
   44814 #endif
   44815 
   44816   /* Compute and store the full pathname in an allocated buffer pointed
   44817   ** to by zPathname, length nPathname. Or, if this is a temporary file,
   44818   ** leave both nPathname and zPathname set to 0.
   44819   */
   44820   if( zFilename && zFilename[0] ){
   44821     const char *z;
   44822     nPathname = pVfs->mxPathname+1;
   44823     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
   44824     if( zPathname==0 ){
   44825       return SQLITE_NOMEM;
   44826     }
   44827     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
   44828     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
   44829     nPathname = sqlite3Strlen30(zPathname);
   44830     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
   44831     while( *z ){
   44832       z += sqlite3Strlen30(z)+1;
   44833       z += sqlite3Strlen30(z)+1;
   44834     }
   44835     nUri = (int)(&z[1] - zUri);
   44836     assert( nUri>=0 );
   44837     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
   44838       /* This branch is taken when the journal path required by
   44839       ** the database being opened will be more than pVfs->mxPathname
   44840       ** bytes in length. This means the database cannot be opened,
   44841       ** as it will not be possible to open the journal file or even
   44842       ** check for a hot-journal before reading.
   44843       */
   44844       rc = SQLITE_CANTOPEN_BKPT;
   44845     }
   44846     if( rc!=SQLITE_OK ){
   44847       sqlite3DbFree(0, zPathname);
   44848       return rc;
   44849     }
   44850   }
   44851 
   44852   /* Allocate memory for the Pager structure, PCache object, the
   44853   ** three file descriptors, the database file name and the journal
   44854   ** file name. The layout in memory is as follows:
   44855   **
   44856   **     Pager object                    (sizeof(Pager) bytes)
   44857   **     PCache object                   (sqlite3PcacheSize() bytes)
   44858   **     Database file handle            (pVfs->szOsFile bytes)
   44859   **     Sub-journal file handle         (journalFileSize bytes)
   44860   **     Main journal file handle        (journalFileSize bytes)
   44861   **     Database file name              (nPathname+1 bytes)
   44862   **     Journal file name               (nPathname+8+1 bytes)
   44863   */
   44864   pPtr = (u8 *)sqlite3MallocZero(
   44865     ROUND8(sizeof(*pPager)) +      /* Pager structure */
   44866     ROUND8(pcacheSize) +           /* PCache object */
   44867     ROUND8(pVfs->szOsFile) +       /* The main db file */
   44868     journalFileSize * 2 +          /* The two journal files */
   44869     nPathname + 1 + nUri +         /* zFilename */
   44870     nPathname + 8 + 2              /* zJournal */
   44871 #ifndef SQLITE_OMIT_WAL
   44872     + nPathname + 4 + 2            /* zWal */
   44873 #endif
   44874   );
   44875   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
   44876   if( !pPtr ){
   44877     sqlite3DbFree(0, zPathname);
   44878     return SQLITE_NOMEM;
   44879   }
   44880   pPager =              (Pager*)(pPtr);
   44881   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
   44882   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
   44883   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
   44884   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
   44885   pPager->zFilename =    (char*)(pPtr += journalFileSize);
   44886   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
   44887 
   44888   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
   44889   if( zPathname ){
   44890     assert( nPathname>0 );
   44891     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
   44892     memcpy(pPager->zFilename, zPathname, nPathname);
   44893     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
   44894     memcpy(pPager->zJournal, zPathname, nPathname);
   44895     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
   44896     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
   44897 #ifndef SQLITE_OMIT_WAL
   44898     pPager->zWal = &pPager->zJournal[nPathname+8+1];
   44899     memcpy(pPager->zWal, zPathname, nPathname);
   44900     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
   44901     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
   44902 #endif
   44903     sqlite3DbFree(0, zPathname);
   44904   }
   44905   pPager->pVfs = pVfs;
   44906   pPager->vfsFlags = vfsFlags;
   44907 
   44908   /* Open the pager file.
   44909   */
   44910   if( zFilename && zFilename[0] ){
   44911     int fout = 0;                    /* VFS flags returned by xOpen() */
   44912     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
   44913     assert( !memDb );
   44914     readOnly = (fout&SQLITE_OPEN_READONLY);
   44915 
   44916     /* If the file was successfully opened for read/write access,
   44917     ** choose a default page size in case we have to create the
   44918     ** database file. The default page size is the maximum of:
   44919     **
   44920     **    + SQLITE_DEFAULT_PAGE_SIZE,
   44921     **    + The value returned by sqlite3OsSectorSize()
   44922     **    + The largest page size that can be written atomically.
   44923     */
   44924     if( rc==SQLITE_OK ){
   44925       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   44926       if( !readOnly ){
   44927         setSectorSize(pPager);
   44928         assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
   44929         if( szPageDflt<pPager->sectorSize ){
   44930           if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
   44931             szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
   44932           }else{
   44933             szPageDflt = (u32)pPager->sectorSize;
   44934           }
   44935         }
   44936 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   44937         {
   44938           int ii;
   44939           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   44940           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   44941           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
   44942           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
   44943             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
   44944               szPageDflt = ii;
   44945             }
   44946           }
   44947         }
   44948 #endif
   44949       }
   44950       pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
   44951       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
   44952        || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
   44953           vfsFlags |= SQLITE_OPEN_READONLY;
   44954           goto act_like_temp_file;
   44955       }
   44956     }
   44957   }else{
   44958     /* If a temporary file is requested, it is not opened immediately.
   44959     ** In this case we accept the default page size and delay actually
   44960     ** opening the file until the first call to OsWrite().
   44961     **
   44962     ** This branch is also run for an in-memory database. An in-memory
   44963     ** database is the same as a temp-file that is never written out to
   44964     ** disk and uses an in-memory rollback journal.
   44965     **
   44966     ** This branch also runs for files marked as immutable.
   44967     */
   44968 act_like_temp_file:
   44969     tempFile = 1;
   44970     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
   44971     pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE locking mode */
   44972     pPager->noLock = 1;                /* Do no locking */
   44973     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
   44974   }
   44975 
   44976   /* The following call to PagerSetPagesize() serves to set the value of
   44977   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
   44978   */
   44979   if( rc==SQLITE_OK ){
   44980     assert( pPager->memDb==0 );
   44981     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
   44982     testcase( rc!=SQLITE_OK );
   44983   }
   44984 
   44985   /* If an error occurred in either of the blocks above, free the
   44986   ** Pager structure and close the file.
   44987   */
   44988   if( rc!=SQLITE_OK ){
   44989     assert( !pPager->pTmpSpace );
   44990     sqlite3OsClose(pPager->fd);
   44991     sqlite3_free(pPager);
   44992     return rc;
   44993   }
   44994 
   44995   /* Initialize the PCache object. */
   44996   assert( nExtra<1000 );
   44997   nExtra = ROUND8(nExtra);
   44998   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
   44999                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
   45000 
   45001   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
   45002   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
   45003 
   45004   pPager->useJournal = (u8)useJournal;
   45005   /* pPager->stmtOpen = 0; */
   45006   /* pPager->stmtInUse = 0; */
   45007   /* pPager->nRef = 0; */
   45008   /* pPager->stmtSize = 0; */
   45009   /* pPager->stmtJSize = 0; */
   45010   /* pPager->nPage = 0; */
   45011   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
   45012   /* pPager->state = PAGER_UNLOCK; */
   45013   /* pPager->errMask = 0; */
   45014   pPager->tempFile = (u8)tempFile;
   45015   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
   45016           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
   45017   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
   45018   pPager->exclusiveMode = (u8)tempFile;
   45019   pPager->changeCountDone = pPager->tempFile;
   45020   pPager->memDb = (u8)memDb;
   45021   pPager->readOnly = (u8)readOnly;
   45022   assert( useJournal || pPager->tempFile );
   45023   pPager->noSync = pPager->tempFile;
   45024   if( pPager->noSync ){
   45025     assert( pPager->fullSync==0 );
   45026     assert( pPager->syncFlags==0 );
   45027     assert( pPager->walSyncFlags==0 );
   45028     assert( pPager->ckptSyncFlags==0 );
   45029   }else{
   45030     pPager->fullSync = 1;
   45031     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   45032     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
   45033     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   45034   }
   45035   /* pPager->pFirst = 0; */
   45036   /* pPager->pFirstSynced = 0; */
   45037   /* pPager->pLast = 0; */
   45038   pPager->nExtra = (u16)nExtra;
   45039   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
   45040   assert( isOpen(pPager->fd) || tempFile );
   45041   setSectorSize(pPager);
   45042   if( !useJournal ){
   45043     pPager->journalMode = PAGER_JOURNALMODE_OFF;
   45044   }else if( memDb ){
   45045     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
   45046   }
   45047   /* pPager->xBusyHandler = 0; */
   45048   /* pPager->pBusyHandlerArg = 0; */
   45049   pPager->xReiniter = xReinit;
   45050   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
   45051   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
   45052 
   45053   *ppPager = pPager;
   45054   return SQLITE_OK;
   45055 }
   45056 
   45057 
   45058 /* Verify that the database file has not be deleted or renamed out from
   45059 ** under the pager.  Return SQLITE_OK if the database is still were it ought
   45060 ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
   45061 ** code from sqlite3OsAccess()) if the database has gone missing.
   45062 */
   45063 static int databaseIsUnmoved(Pager *pPager){
   45064   int bHasMoved = 0;
   45065   int rc;
   45066 
   45067   if( pPager->tempFile ) return SQLITE_OK;
   45068   if( pPager->dbSize==0 ) return SQLITE_OK;
   45069   assert( pPager->zFilename && pPager->zFilename[0] );
   45070   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
   45071   if( rc==SQLITE_NOTFOUND ){
   45072     /* If the HAS_MOVED file-control is unimplemented, assume that the file
   45073     ** has not been moved.  That is the historical behavior of SQLite: prior to
   45074     ** version 3.8.3, it never checked */
   45075     rc = SQLITE_OK;
   45076   }else if( rc==SQLITE_OK && bHasMoved ){
   45077     rc = SQLITE_READONLY_DBMOVED;
   45078   }
   45079   return rc;
   45080 }
   45081 
   45082 
   45083 /*
   45084 ** This function is called after transitioning from PAGER_UNLOCK to
   45085 ** PAGER_SHARED state. It tests if there is a hot journal present in
   45086 ** the file-system for the given pager. A hot journal is one that
   45087 ** needs to be played back. According to this function, a hot-journal
   45088 ** file exists if the following criteria are met:
   45089 **
   45090 **   * The journal file exists in the file system, and
   45091 **   * No process holds a RESERVED or greater lock on the database file, and
   45092 **   * The database file itself is greater than 0 bytes in size, and
   45093 **   * The first byte of the journal file exists and is not 0x00.
   45094 **
   45095 ** If the current size of the database file is 0 but a journal file
   45096 ** exists, that is probably an old journal left over from a prior
   45097 ** database with the same name. In this case the journal file is
   45098 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
   45099 ** is returned.
   45100 **
   45101 ** This routine does not check if there is a master journal filename
   45102 ** at the end of the file. If there is, and that master journal file
   45103 ** does not exist, then the journal file is not really hot. In this
   45104 ** case this routine will return a false-positive. The pager_playback()
   45105 ** routine will discover that the journal file is not really hot and
   45106 ** will not roll it back.
   45107 **
   45108 ** If a hot-journal file is found to exist, *pExists is set to 1 and
   45109 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
   45110 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
   45111 ** to determine whether or not a hot-journal file exists, the IO error
   45112 ** code is returned and the value of *pExists is undefined.
   45113 */
   45114 static int hasHotJournal(Pager *pPager, int *pExists){
   45115   sqlite3_vfs * const pVfs = pPager->pVfs;
   45116   int rc = SQLITE_OK;           /* Return code */
   45117   int exists = 1;               /* True if a journal file is present */
   45118   int jrnlOpen = !!isOpen(pPager->jfd);
   45119 
   45120   assert( pPager->useJournal );
   45121   assert( isOpen(pPager->fd) );
   45122   assert( pPager->eState==PAGER_OPEN );
   45123 
   45124   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
   45125     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
   45126   ));
   45127 
   45128   *pExists = 0;
   45129   if( !jrnlOpen ){
   45130     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
   45131   }
   45132   if( rc==SQLITE_OK && exists ){
   45133     int locked = 0;             /* True if some process holds a RESERVED lock */
   45134 
   45135     /* Race condition here:  Another process might have been holding the
   45136     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
   45137     ** call above, but then delete the journal and drop the lock before
   45138     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
   45139     ** is the case, this routine might think there is a hot journal when
   45140     ** in fact there is none.  This results in a false-positive which will
   45141     ** be dealt with by the playback routine.  Ticket #3883.
   45142     */
   45143     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
   45144     if( rc==SQLITE_OK && !locked ){
   45145       Pgno nPage;                 /* Number of pages in database file */
   45146 
   45147       rc = pagerPagecount(pPager, &nPage);
   45148       if( rc==SQLITE_OK ){
   45149         /* If the database is zero pages in size, that means that either (1) the
   45150         ** journal is a remnant from a prior database with the same name where
   45151         ** the database file but not the journal was deleted, or (2) the initial
   45152         ** transaction that populates a new database is being rolled back.
   45153         ** In either case, the journal file can be deleted.  However, take care
   45154         ** not to delete the journal file if it is already open due to
   45155         ** journal_mode=PERSIST.
   45156         */
   45157         if( nPage==0 && !jrnlOpen ){
   45158           sqlite3BeginBenignMalloc();
   45159           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
   45160             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
   45161             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
   45162           }
   45163           sqlite3EndBenignMalloc();
   45164         }else{
   45165           /* The journal file exists and no other connection has a reserved
   45166           ** or greater lock on the database file. Now check that there is
   45167           ** at least one non-zero bytes at the start of the journal file.
   45168           ** If there is, then we consider this journal to be hot. If not,
   45169           ** it can be ignored.
   45170           */
   45171           if( !jrnlOpen ){
   45172             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
   45173             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
   45174           }
   45175           if( rc==SQLITE_OK ){
   45176             u8 first = 0;
   45177             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
   45178             if( rc==SQLITE_IOERR_SHORT_READ ){
   45179               rc = SQLITE_OK;
   45180             }
   45181             if( !jrnlOpen ){
   45182               sqlite3OsClose(pPager->jfd);
   45183             }
   45184             *pExists = (first!=0);
   45185           }else if( rc==SQLITE_CANTOPEN ){
   45186             /* If we cannot open the rollback journal file in order to see if
   45187             ** its has a zero header, that might be due to an I/O error, or
   45188             ** it might be due to the race condition described above and in
   45189             ** ticket #3883.  Either way, assume that the journal is hot.
   45190             ** This might be a false positive.  But if it is, then the
   45191             ** automatic journal playback and recovery mechanism will deal
   45192             ** with it under an EXCLUSIVE lock where we do not need to
   45193             ** worry so much with race conditions.
   45194             */
   45195             *pExists = 1;
   45196             rc = SQLITE_OK;
   45197           }
   45198         }
   45199       }
   45200     }
   45201   }
   45202 
   45203   return rc;
   45204 }
   45205 
   45206 /*
   45207 ** This function is called to obtain a shared lock on the database file.
   45208 ** It is illegal to call sqlite3PagerAcquire() until after this function
   45209 ** has been successfully called. If a shared-lock is already held when
   45210 ** this function is called, it is a no-op.
   45211 **
   45212 ** The following operations are also performed by this function.
   45213 **
   45214 **   1) If the pager is currently in PAGER_OPEN state (no lock held
   45215 **      on the database file), then an attempt is made to obtain a
   45216 **      SHARED lock on the database file. Immediately after obtaining
   45217 **      the SHARED lock, the file-system is checked for a hot-journal,
   45218 **      which is played back if present. Following any hot-journal
   45219 **      rollback, the contents of the cache are validated by checking
   45220 **      the 'change-counter' field of the database file header and
   45221 **      discarded if they are found to be invalid.
   45222 **
   45223 **   2) If the pager is running in exclusive-mode, and there are currently
   45224 **      no outstanding references to any pages, and is in the error state,
   45225 **      then an attempt is made to clear the error state by discarding
   45226 **      the contents of the page cache and rolling back any open journal
   45227 **      file.
   45228 **
   45229 ** If everything is successful, SQLITE_OK is returned. If an IO error
   45230 ** occurs while locking the database, checking for a hot-journal file or
   45231 ** rolling back a journal file, the IO error code is returned.
   45232 */
   45233 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
   45234   int rc = SQLITE_OK;                /* Return code */
   45235 
   45236   /* This routine is only called from b-tree and only when there are no
   45237   ** outstanding pages. This implies that the pager state should either
   45238   ** be OPEN or READER. READER is only possible if the pager is or was in
   45239   ** exclusive access mode.
   45240   */
   45241   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   45242   assert( assert_pager_state(pPager) );
   45243   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   45244   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
   45245 
   45246   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
   45247     int bHotJournal = 1;          /* True if there exists a hot journal-file */
   45248 
   45249     assert( !MEMDB );
   45250 
   45251     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
   45252     if( rc!=SQLITE_OK ){
   45253       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
   45254       goto failed;
   45255     }
   45256 
   45257     /* If a journal file exists, and there is no RESERVED lock on the
   45258     ** database file, then it either needs to be played back or deleted.
   45259     */
   45260     if( pPager->eLock<=SHARED_LOCK ){
   45261       rc = hasHotJournal(pPager, &bHotJournal);
   45262     }
   45263     if( rc!=SQLITE_OK ){
   45264       goto failed;
   45265     }
   45266     if( bHotJournal ){
   45267       if( pPager->readOnly ){
   45268         rc = SQLITE_READONLY_ROLLBACK;
   45269         goto failed;
   45270       }
   45271 
   45272       /* Get an EXCLUSIVE lock on the database file. At this point it is
   45273       ** important that a RESERVED lock is not obtained on the way to the
   45274       ** EXCLUSIVE lock. If it were, another process might open the
   45275       ** database file, detect the RESERVED lock, and conclude that the
   45276       ** database is safe to read while this process is still rolling the
   45277       ** hot-journal back.
   45278       **
   45279       ** Because the intermediate RESERVED lock is not requested, any
   45280       ** other process attempting to access the database file will get to
   45281       ** this point in the code and fail to obtain its own EXCLUSIVE lock
   45282       ** on the database file.
   45283       **
   45284       ** Unless the pager is in locking_mode=exclusive mode, the lock is
   45285       ** downgraded to SHARED_LOCK before this function returns.
   45286       */
   45287       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   45288       if( rc!=SQLITE_OK ){
   45289         goto failed;
   45290       }
   45291 
   45292       /* If it is not already open and the file exists on disk, open the
   45293       ** journal for read/write access. Write access is required because
   45294       ** in exclusive-access mode the file descriptor will be kept open
   45295       ** and possibly used for a transaction later on. Also, write-access
   45296       ** is usually required to finalize the journal in journal_mode=persist
   45297       ** mode (and also for journal_mode=truncate on some systems).
   45298       **
   45299       ** If the journal does not exist, it usually means that some
   45300       ** other connection managed to get in and roll it back before
   45301       ** this connection obtained the exclusive lock above. Or, it
   45302       ** may mean that the pager was in the error-state when this
   45303       ** function was called and the journal file does not exist.
   45304       */
   45305       if( !isOpen(pPager->jfd) ){
   45306         sqlite3_vfs * const pVfs = pPager->pVfs;
   45307         int bExists;              /* True if journal file exists */
   45308         rc = sqlite3OsAccess(
   45309             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
   45310         if( rc==SQLITE_OK && bExists ){
   45311           int fout = 0;
   45312           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
   45313           assert( !pPager->tempFile );
   45314           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
   45315           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   45316           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
   45317             rc = SQLITE_CANTOPEN_BKPT;
   45318             sqlite3OsClose(pPager->jfd);
   45319           }
   45320         }
   45321       }
   45322 
   45323       /* Playback and delete the journal.  Drop the database write
   45324       ** lock and reacquire the read lock. Purge the cache before
   45325       ** playing back the hot-journal so that we don't end up with
   45326       ** an inconsistent cache.  Sync the hot journal before playing
   45327       ** it back since the process that crashed and left the hot journal
   45328       ** probably did not sync it and we are required to always sync
   45329       ** the journal before playing it back.
   45330       */
   45331       if( isOpen(pPager->jfd) ){
   45332         assert( rc==SQLITE_OK );
   45333         rc = pagerSyncHotJournal(pPager);
   45334         if( rc==SQLITE_OK ){
   45335           rc = pager_playback(pPager, 1);
   45336           pPager->eState = PAGER_OPEN;
   45337         }
   45338       }else if( !pPager->exclusiveMode ){
   45339         pagerUnlockDb(pPager, SHARED_LOCK);
   45340       }
   45341 
   45342       if( rc!=SQLITE_OK ){
   45343         /* This branch is taken if an error occurs while trying to open
   45344         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
   45345         ** pager_unlock() routine will be called before returning to unlock
   45346         ** the file. If the unlock attempt fails, then Pager.eLock must be
   45347         ** set to UNKNOWN_LOCK (see the comment above the #define for
   45348         ** UNKNOWN_LOCK above for an explanation).
   45349         **
   45350         ** In order to get pager_unlock() to do this, set Pager.eState to
   45351         ** PAGER_ERROR now. This is not actually counted as a transition
   45352         ** to ERROR state in the state diagram at the top of this file,
   45353         ** since we know that the same call to pager_unlock() will very
   45354         ** shortly transition the pager object to the OPEN state. Calling
   45355         ** assert_pager_state() would fail now, as it should not be possible
   45356         ** to be in ERROR state when there are zero outstanding page
   45357         ** references.
   45358         */
   45359         pager_error(pPager, rc);
   45360         goto failed;
   45361       }
   45362 
   45363       assert( pPager->eState==PAGER_OPEN );
   45364       assert( (pPager->eLock==SHARED_LOCK)
   45365            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
   45366       );
   45367     }
   45368 
   45369     if( !pPager->tempFile && (
   45370         pPager->pBackup
   45371      || sqlite3PcachePagecount(pPager->pPCache)>0
   45372      || USEFETCH(pPager)
   45373     )){
   45374       /* The shared-lock has just been acquired on the database file
   45375       ** and there are already pages in the cache (from a previous
   45376       ** read or write transaction).  Check to see if the database
   45377       ** has been modified.  If the database has changed, flush the
   45378       ** cache.
   45379       **
   45380       ** Database changes is detected by looking at 15 bytes beginning
   45381       ** at offset 24 into the file.  The first 4 of these 16 bytes are
   45382       ** a 32-bit counter that is incremented with each change.  The
   45383       ** other bytes change randomly with each file change when
   45384       ** a codec is in use.
   45385       **
   45386       ** There is a vanishingly small chance that a change will not be
   45387       ** detected.  The chance of an undetected change is so small that
   45388       ** it can be neglected.
   45389       */
   45390       Pgno nPage = 0;
   45391       char dbFileVers[sizeof(pPager->dbFileVers)];
   45392 
   45393       rc = pagerPagecount(pPager, &nPage);
   45394       if( rc ) goto failed;
   45395 
   45396       if( nPage>0 ){
   45397         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
   45398         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
   45399         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   45400           goto failed;
   45401         }
   45402       }else{
   45403         memset(dbFileVers, 0, sizeof(dbFileVers));
   45404       }
   45405 
   45406       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
   45407         pager_reset(pPager);
   45408 
   45409         /* Unmap the database file. It is possible that external processes
   45410         ** may have truncated the database file and then extended it back
   45411         ** to its original size while this process was not holding a lock.
   45412         ** In this case there may exist a Pager.pMap mapping that appears
   45413         ** to be the right size but is not actually valid. Avoid this
   45414         ** possibility by unmapping the db here. */
   45415         if( USEFETCH(pPager) ){
   45416           sqlite3OsUnfetch(pPager->fd, 0, 0);
   45417         }
   45418       }
   45419     }
   45420 
   45421     /* If there is a WAL file in the file-system, open this database in WAL
   45422     ** mode. Otherwise, the following function call is a no-op.
   45423     */
   45424     rc = pagerOpenWalIfPresent(pPager);
   45425 #ifndef SQLITE_OMIT_WAL
   45426     assert( pPager->pWal==0 || rc==SQLITE_OK );
   45427 #endif
   45428   }
   45429 
   45430   if( pagerUseWal(pPager) ){
   45431     assert( rc==SQLITE_OK );
   45432     rc = pagerBeginReadTransaction(pPager);
   45433   }
   45434 
   45435   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
   45436     rc = pagerPagecount(pPager, &pPager->dbSize);
   45437   }
   45438 
   45439  failed:
   45440   if( rc!=SQLITE_OK ){
   45441     assert( !MEMDB );
   45442     pager_unlock(pPager);
   45443     assert( pPager->eState==PAGER_OPEN );
   45444   }else{
   45445     pPager->eState = PAGER_READER;
   45446   }
   45447   return rc;
   45448 }
   45449 
   45450 /*
   45451 ** If the reference count has reached zero, rollback any active
   45452 ** transaction and unlock the pager.
   45453 **
   45454 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
   45455 ** the rollback journal, the unlock is not performed and there is
   45456 ** nothing to rollback, so this routine is a no-op.
   45457 */
   45458 static void pagerUnlockIfUnused(Pager *pPager){
   45459   if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
   45460     pagerUnlockAndRollback(pPager);
   45461   }
   45462 }
   45463 
   45464 /*
   45465 ** Acquire a reference to page number pgno in pager pPager (a page
   45466 ** reference has type DbPage*). If the requested reference is
   45467 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
   45468 **
   45469 ** If the requested page is already in the cache, it is returned.
   45470 ** Otherwise, a new page object is allocated and populated with data
   45471 ** read from the database file. In some cases, the pcache module may
   45472 ** choose not to allocate a new page object and may reuse an existing
   45473 ** object with no outstanding references.
   45474 **
   45475 ** The extra data appended to a page is always initialized to zeros the
   45476 ** first time a page is loaded into memory. If the page requested is
   45477 ** already in the cache when this function is called, then the extra
   45478 ** data is left as it was when the page object was last used.
   45479 **
   45480 ** If the database image is smaller than the requested page or if a
   45481 ** non-zero value is passed as the noContent parameter and the
   45482 ** requested page is not already stored in the cache, then no
   45483 ** actual disk read occurs. In this case the memory image of the
   45484 ** page is initialized to all zeros.
   45485 **
   45486 ** If noContent is true, it means that we do not care about the contents
   45487 ** of the page. This occurs in two scenarios:
   45488 **
   45489 **   a) When reading a free-list leaf page from the database, and
   45490 **
   45491 **   b) When a savepoint is being rolled back and we need to load
   45492 **      a new page into the cache to be filled with the data read
   45493 **      from the savepoint journal.
   45494 **
   45495 ** If noContent is true, then the data returned is zeroed instead of
   45496 ** being read from the database. Additionally, the bits corresponding
   45497 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
   45498 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
   45499 ** savepoints are set. This means if the page is made writable at any
   45500 ** point in the future, using a call to sqlite3PagerWrite(), its contents
   45501 ** will not be journaled. This saves IO.
   45502 **
   45503 ** The acquisition might fail for several reasons.  In all cases,
   45504 ** an appropriate error code is returned and *ppPage is set to NULL.
   45505 **
   45506 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
   45507 ** to find a page in the in-memory cache first.  If the page is not already
   45508 ** in memory, this routine goes to disk to read it in whereas Lookup()
   45509 ** just returns 0.  This routine acquires a read-lock the first time it
   45510 ** has to go to disk, and could also playback an old journal if necessary.
   45511 ** Since Lookup() never goes to disk, it never has to deal with locks
   45512 ** or journal files.
   45513 */
   45514 SQLITE_PRIVATE int sqlite3PagerAcquire(
   45515   Pager *pPager,      /* The pager open on the database file */
   45516   Pgno pgno,          /* Page number to fetch */
   45517   DbPage **ppPage,    /* Write a pointer to the page here */
   45518   int flags           /* PAGER_GET_XXX flags */
   45519 ){
   45520   int rc = SQLITE_OK;
   45521   PgHdr *pPg = 0;
   45522   u32 iFrame = 0;                 /* Frame to read from WAL file */
   45523   const int noContent = (flags & PAGER_GET_NOCONTENT);
   45524 
   45525   /* It is acceptable to use a read-only (mmap) page for any page except
   45526   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
   45527   ** flag was specified by the caller. And so long as the db is not a
   45528   ** temporary or in-memory database.  */
   45529   const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
   45530    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
   45531 #ifdef SQLITE_HAS_CODEC
   45532    && pPager->xCodec==0
   45533 #endif
   45534   );
   45535 
   45536   assert( pPager->eState>=PAGER_READER );
   45537   assert( assert_pager_state(pPager) );
   45538   assert( noContent==0 || bMmapOk==0 );
   45539 
   45540   if( pgno==0 ){
   45541     return SQLITE_CORRUPT_BKPT;
   45542   }
   45543 
   45544   /* If the pager is in the error state, return an error immediately.
   45545   ** Otherwise, request the page from the PCache layer. */
   45546   if( pPager->errCode!=SQLITE_OK ){
   45547     rc = pPager->errCode;
   45548   }else{
   45549 
   45550     if( bMmapOk && pagerUseWal(pPager) ){
   45551       rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
   45552       if( rc!=SQLITE_OK ) goto pager_acquire_err;
   45553     }
   45554 
   45555     if( bMmapOk && iFrame==0 ){
   45556       void *pData = 0;
   45557 
   45558       rc = sqlite3OsFetch(pPager->fd,
   45559           (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
   45560       );
   45561 
   45562       if( rc==SQLITE_OK && pData ){
   45563         if( pPager->eState>PAGER_READER ){
   45564           (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
   45565         }
   45566         if( pPg==0 ){
   45567           rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
   45568         }else{
   45569           sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
   45570         }
   45571         if( pPg ){
   45572           assert( rc==SQLITE_OK );
   45573           *ppPage = pPg;
   45574           return SQLITE_OK;
   45575         }
   45576       }
   45577       if( rc!=SQLITE_OK ){
   45578         goto pager_acquire_err;
   45579       }
   45580     }
   45581 
   45582     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
   45583   }
   45584 
   45585   if( rc!=SQLITE_OK ){
   45586     /* Either the call to sqlite3PcacheFetch() returned an error or the
   45587     ** pager was already in the error-state when this function was called.
   45588     ** Set pPg to 0 and jump to the exception handler.  */
   45589     pPg = 0;
   45590     goto pager_acquire_err;
   45591   }
   45592   assert( (*ppPage)->pgno==pgno );
   45593   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
   45594 
   45595   if( (*ppPage)->pPager && !noContent ){
   45596     /* In this case the pcache already contains an initialized copy of
   45597     ** the page. Return without further ado.  */
   45598     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
   45599     pPager->aStat[PAGER_STAT_HIT]++;
   45600     return SQLITE_OK;
   45601 
   45602   }else{
   45603     /* The pager cache has created a new page. Its content needs to
   45604     ** be initialized.  */
   45605 
   45606     pPg = *ppPage;
   45607     pPg->pPager = pPager;
   45608 
   45609     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
   45610     ** number greater than this, or the unused locking-page, is requested. */
   45611     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
   45612       rc = SQLITE_CORRUPT_BKPT;
   45613       goto pager_acquire_err;
   45614     }
   45615 
   45616     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
   45617       if( pgno>pPager->mxPgno ){
   45618         rc = SQLITE_FULL;
   45619         goto pager_acquire_err;
   45620       }
   45621       if( noContent ){
   45622         /* Failure to set the bits in the InJournal bit-vectors is benign.
   45623         ** It merely means that we might do some extra work to journal a
   45624         ** page that does not need to be journaled.  Nevertheless, be sure
   45625         ** to test the case where a malloc error occurs while trying to set
   45626         ** a bit in a bit vector.
   45627         */
   45628         sqlite3BeginBenignMalloc();
   45629         if( pgno<=pPager->dbOrigSize ){
   45630           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
   45631           testcase( rc==SQLITE_NOMEM );
   45632         }
   45633         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
   45634         testcase( rc==SQLITE_NOMEM );
   45635         sqlite3EndBenignMalloc();
   45636       }
   45637       memset(pPg->pData, 0, pPager->pageSize);
   45638       IOTRACE(("ZERO %p %d\n", pPager, pgno));
   45639     }else{
   45640       if( pagerUseWal(pPager) && bMmapOk==0 ){
   45641         rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
   45642         if( rc!=SQLITE_OK ) goto pager_acquire_err;
   45643       }
   45644       assert( pPg->pPager==pPager );
   45645       pPager->aStat[PAGER_STAT_MISS]++;
   45646       rc = readDbPage(pPg, iFrame);
   45647       if( rc!=SQLITE_OK ){
   45648         goto pager_acquire_err;
   45649       }
   45650     }
   45651     pager_set_pagehash(pPg);
   45652   }
   45653 
   45654   return SQLITE_OK;
   45655 
   45656 pager_acquire_err:
   45657   assert( rc!=SQLITE_OK );
   45658   if( pPg ){
   45659     sqlite3PcacheDrop(pPg);
   45660   }
   45661   pagerUnlockIfUnused(pPager);
   45662 
   45663   *ppPage = 0;
   45664   return rc;
   45665 }
   45666 
   45667 /*
   45668 ** Acquire a page if it is already in the in-memory cache.  Do
   45669 ** not read the page from disk.  Return a pointer to the page,
   45670 ** or 0 if the page is not in cache.
   45671 **
   45672 ** See also sqlite3PagerGet().  The difference between this routine
   45673 ** and sqlite3PagerGet() is that _get() will go to the disk and read
   45674 ** in the page if the page is not already in cache.  This routine
   45675 ** returns NULL if the page is not in cache or if a disk I/O error
   45676 ** has ever happened.
   45677 */
   45678 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
   45679   PgHdr *pPg = 0;
   45680   assert( pPager!=0 );
   45681   assert( pgno!=0 );
   45682   assert( pPager->pPCache!=0 );
   45683   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
   45684   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
   45685   return pPg;
   45686 }
   45687 
   45688 /*
   45689 ** Release a page reference.
   45690 **
   45691 ** If the number of references to the page drop to zero, then the
   45692 ** page is added to the LRU list.  When all references to all pages
   45693 ** are released, a rollback occurs and the lock on the database is
   45694 ** removed.
   45695 */
   45696 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
   45697   Pager *pPager;
   45698   assert( pPg!=0 );
   45699   pPager = pPg->pPager;
   45700   if( pPg->flags & PGHDR_MMAP ){
   45701     pagerReleaseMapPage(pPg);
   45702   }else{
   45703     sqlite3PcacheRelease(pPg);
   45704   }
   45705   pagerUnlockIfUnused(pPager);
   45706 }
   45707 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
   45708   if( pPg ) sqlite3PagerUnrefNotNull(pPg);
   45709 }
   45710 
   45711 /*
   45712 ** This function is called at the start of every write transaction.
   45713 ** There must already be a RESERVED or EXCLUSIVE lock on the database
   45714 ** file when this routine is called.
   45715 **
   45716 ** Open the journal file for pager pPager and write a journal header
   45717 ** to the start of it. If there are active savepoints, open the sub-journal
   45718 ** as well. This function is only used when the journal file is being
   45719 ** opened to write a rollback log for a transaction. It is not used
   45720 ** when opening a hot journal file to roll it back.
   45721 **
   45722 ** If the journal file is already open (as it may be in exclusive mode),
   45723 ** then this function just writes a journal header to the start of the
   45724 ** already open file.
   45725 **
   45726 ** Whether or not the journal file is opened by this function, the
   45727 ** Pager.pInJournal bitvec structure is allocated.
   45728 **
   45729 ** Return SQLITE_OK if everything is successful. Otherwise, return
   45730 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
   45731 ** an IO error code if opening or writing the journal file fails.
   45732 */
   45733 static int pager_open_journal(Pager *pPager){
   45734   int rc = SQLITE_OK;                        /* Return code */
   45735   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
   45736 
   45737   assert( pPager->eState==PAGER_WRITER_LOCKED );
   45738   assert( assert_pager_state(pPager) );
   45739   assert( pPager->pInJournal==0 );
   45740 
   45741   /* If already in the error state, this function is a no-op.  But on
   45742   ** the other hand, this routine is never called if we are already in
   45743   ** an error state. */
   45744   if( NEVER(pPager->errCode) ) return pPager->errCode;
   45745 
   45746   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   45747     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
   45748     if( pPager->pInJournal==0 ){
   45749       return SQLITE_NOMEM;
   45750     }
   45751 
   45752     /* Open the journal file if it is not already open. */
   45753     if( !isOpen(pPager->jfd) ){
   45754       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
   45755         sqlite3MemJournalOpen(pPager->jfd);
   45756       }else{
   45757         const int flags =                   /* VFS flags to open journal file */
   45758           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   45759           (pPager->tempFile ?
   45760             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
   45761             (SQLITE_OPEN_MAIN_JOURNAL)
   45762           );
   45763 
   45764         /* Verify that the database still has the same name as it did when
   45765         ** it was originally opened. */
   45766         rc = databaseIsUnmoved(pPager);
   45767         if( rc==SQLITE_OK ){
   45768 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   45769           rc = sqlite3JournalOpen(
   45770               pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
   45771           );
   45772 #else
   45773           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
   45774 #endif
   45775         }
   45776       }
   45777       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   45778     }
   45779 
   45780 
   45781     /* Write the first journal header to the journal file and open
   45782     ** the sub-journal if necessary.
   45783     */
   45784     if( rc==SQLITE_OK ){
   45785       /* TODO: Check if all of these are really required. */
   45786       pPager->nRec = 0;
   45787       pPager->journalOff = 0;
   45788       pPager->setMaster = 0;
   45789       pPager->journalHdr = 0;
   45790       rc = writeJournalHdr(pPager);
   45791     }
   45792   }
   45793 
   45794   if( rc!=SQLITE_OK ){
   45795     sqlite3BitvecDestroy(pPager->pInJournal);
   45796     pPager->pInJournal = 0;
   45797   }else{
   45798     assert( pPager->eState==PAGER_WRITER_LOCKED );
   45799     pPager->eState = PAGER_WRITER_CACHEMOD;
   45800   }
   45801 
   45802   return rc;
   45803 }
   45804 
   45805 /*
   45806 ** Begin a write-transaction on the specified pager object. If a
   45807 ** write-transaction has already been opened, this function is a no-op.
   45808 **
   45809 ** If the exFlag argument is false, then acquire at least a RESERVED
   45810 ** lock on the database file. If exFlag is true, then acquire at least
   45811 ** an EXCLUSIVE lock. If such a lock is already held, no locking
   45812 ** functions need be called.
   45813 **
   45814 ** If the subjInMemory argument is non-zero, then any sub-journal opened
   45815 ** within this transaction will be opened as an in-memory file. This
   45816 ** has no effect if the sub-journal is already opened (as it may be when
   45817 ** running in exclusive mode) or if the transaction does not require a
   45818 ** sub-journal. If the subjInMemory argument is zero, then any required
   45819 ** sub-journal is implemented in-memory if pPager is an in-memory database,
   45820 ** or using a temporary file otherwise.
   45821 */
   45822 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
   45823   int rc = SQLITE_OK;
   45824 
   45825   if( pPager->errCode ) return pPager->errCode;
   45826   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
   45827   pPager->subjInMemory = (u8)subjInMemory;
   45828 
   45829   if( ALWAYS(pPager->eState==PAGER_READER) ){
   45830     assert( pPager->pInJournal==0 );
   45831 
   45832     if( pagerUseWal(pPager) ){
   45833       /* If the pager is configured to use locking_mode=exclusive, and an
   45834       ** exclusive lock on the database is not already held, obtain it now.
   45835       */
   45836       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
   45837         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   45838         if( rc!=SQLITE_OK ){
   45839           return rc;
   45840         }
   45841         sqlite3WalExclusiveMode(pPager->pWal, 1);
   45842       }
   45843 
   45844       /* Grab the write lock on the log file. If successful, upgrade to
   45845       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
   45846       ** The busy-handler is not invoked if another connection already
   45847       ** holds the write-lock. If possible, the upper layer will call it.
   45848       */
   45849       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
   45850     }else{
   45851       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
   45852       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
   45853       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
   45854       ** lock, but not when obtaining the RESERVED lock.
   45855       */
   45856       rc = pagerLockDb(pPager, RESERVED_LOCK);
   45857       if( rc==SQLITE_OK && exFlag ){
   45858         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   45859       }
   45860     }
   45861 
   45862     if( rc==SQLITE_OK ){
   45863       /* Change to WRITER_LOCKED state.
   45864       **
   45865       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
   45866       ** when it has an open transaction, but never to DBMOD or FINISHED.
   45867       ** This is because in those states the code to roll back savepoint
   45868       ** transactions may copy data from the sub-journal into the database
   45869       ** file as well as into the page cache. Which would be incorrect in
   45870       ** WAL mode.
   45871       */
   45872       pPager->eState = PAGER_WRITER_LOCKED;
   45873       pPager->dbHintSize = pPager->dbSize;
   45874       pPager->dbFileSize = pPager->dbSize;
   45875       pPager->dbOrigSize = pPager->dbSize;
   45876       pPager->journalOff = 0;
   45877     }
   45878 
   45879     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
   45880     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
   45881     assert( assert_pager_state(pPager) );
   45882   }
   45883 
   45884   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
   45885   return rc;
   45886 }
   45887 
   45888 /*
   45889 ** Mark a single data page as writeable. The page is written into the
   45890 ** main journal or sub-journal as required. If the page is written into
   45891 ** one of the journals, the corresponding bit is set in the
   45892 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
   45893 ** of any open savepoints as appropriate.
   45894 */
   45895 static int pager_write(PgHdr *pPg){
   45896   Pager *pPager = pPg->pPager;
   45897   int rc = SQLITE_OK;
   45898   int inJournal;
   45899 
   45900   /* This routine is not called unless a write-transaction has already
   45901   ** been started. The journal file may or may not be open at this point.
   45902   ** It is never called in the ERROR state.
   45903   */
   45904   assert( pPager->eState==PAGER_WRITER_LOCKED
   45905        || pPager->eState==PAGER_WRITER_CACHEMOD
   45906        || pPager->eState==PAGER_WRITER_DBMOD
   45907   );
   45908   assert( assert_pager_state(pPager) );
   45909   assert( pPager->errCode==0 );
   45910   assert( pPager->readOnly==0 );
   45911 
   45912   CHECK_PAGE(pPg);
   45913 
   45914   /* The journal file needs to be opened. Higher level routines have already
   45915   ** obtained the necessary locks to begin the write-transaction, but the
   45916   ** rollback journal might not yet be open. Open it now if this is the case.
   45917   **
   45918   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
   45919   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
   45920   ** an error might occur and the pager would end up in WRITER_LOCKED state
   45921   ** with pages marked as dirty in the cache.
   45922   */
   45923   if( pPager->eState==PAGER_WRITER_LOCKED ){
   45924     rc = pager_open_journal(pPager);
   45925     if( rc!=SQLITE_OK ) return rc;
   45926   }
   45927   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   45928   assert( assert_pager_state(pPager) );
   45929 
   45930   /* Mark the page as dirty.  If the page has already been written
   45931   ** to the journal then we can return right away.
   45932   */
   45933   sqlite3PcacheMakeDirty(pPg);
   45934   inJournal = pageInJournal(pPager, pPg);
   45935   if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
   45936     assert( !pagerUseWal(pPager) );
   45937   }else{
   45938 
   45939     /* The transaction journal now exists and we have a RESERVED or an
   45940     ** EXCLUSIVE lock on the main database file.  Write the current page to
   45941     ** the transaction journal if it is not there already.
   45942     */
   45943     if( !inJournal && !pagerUseWal(pPager) ){
   45944       assert( pagerUseWal(pPager)==0 );
   45945       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
   45946         u32 cksum;
   45947         char *pData2;
   45948         i64 iOff = pPager->journalOff;
   45949 
   45950         /* We should never write to the journal file the page that
   45951         ** contains the database locks.  The following assert verifies
   45952         ** that we do not. */
   45953         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
   45954 
   45955         assert( pPager->journalHdr<=pPager->journalOff );
   45956         CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   45957         cksum = pager_cksum(pPager, (u8*)pData2);
   45958 
   45959         /* Even if an IO or diskfull error occurs while journalling the
   45960         ** page in the block above, set the need-sync flag for the page.
   45961         ** Otherwise, when the transaction is rolled back, the logic in
   45962         ** playback_one_page() will think that the page needs to be restored
   45963         ** in the database file. And if an IO error occurs while doing so,
   45964         ** then corruption may follow.
   45965         */
   45966         pPg->flags |= PGHDR_NEED_SYNC;
   45967 
   45968         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
   45969         if( rc!=SQLITE_OK ) return rc;
   45970         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
   45971         if( rc!=SQLITE_OK ) return rc;
   45972         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
   45973         if( rc!=SQLITE_OK ) return rc;
   45974 
   45975         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
   45976                  pPager->journalOff, pPager->pageSize));
   45977         PAGER_INCR(sqlite3_pager_writej_count);
   45978         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
   45979              PAGERID(pPager), pPg->pgno,
   45980              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
   45981 
   45982         pPager->journalOff += 8 + pPager->pageSize;
   45983         pPager->nRec++;
   45984         assert( pPager->pInJournal!=0 );
   45985         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
   45986         testcase( rc==SQLITE_NOMEM );
   45987         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   45988         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
   45989         if( rc!=SQLITE_OK ){
   45990           assert( rc==SQLITE_NOMEM );
   45991           return rc;
   45992         }
   45993       }else{
   45994         if( pPager->eState!=PAGER_WRITER_DBMOD ){
   45995           pPg->flags |= PGHDR_NEED_SYNC;
   45996         }
   45997         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
   45998                 PAGERID(pPager), pPg->pgno,
   45999                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
   46000       }
   46001     }
   46002 
   46003     /* If the statement journal is open and the page is not in it,
   46004     ** then write the current page to the statement journal.  Note that
   46005     ** the statement journal format differs from the standard journal format
   46006     ** in that it omits the checksums and the header.
   46007     */
   46008     if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
   46009       rc = subjournalPage(pPg);
   46010     }
   46011   }
   46012 
   46013   /* Update the database size and return.
   46014   */
   46015   if( pPager->dbSize<pPg->pgno ){
   46016     pPager->dbSize = pPg->pgno;
   46017   }
   46018   return rc;
   46019 }
   46020 
   46021 /*
   46022 ** Mark a data page as writeable. This routine must be called before
   46023 ** making changes to a page. The caller must check the return value
   46024 ** of this function and be careful not to change any page data unless
   46025 ** this routine returns SQLITE_OK.
   46026 **
   46027 ** The difference between this function and pager_write() is that this
   46028 ** function also deals with the special case where 2 or more pages
   46029 ** fit on a single disk sector. In this case all co-resident pages
   46030 ** must have been written to the journal file before returning.
   46031 **
   46032 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
   46033 ** as appropriate. Otherwise, SQLITE_OK.
   46034 */
   46035 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
   46036   int rc = SQLITE_OK;
   46037 
   46038   PgHdr *pPg = pDbPage;
   46039   Pager *pPager = pPg->pPager;
   46040 
   46041   assert( (pPg->flags & PGHDR_MMAP)==0 );
   46042   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   46043   assert( pPager->eState!=PAGER_ERROR );
   46044   assert( assert_pager_state(pPager) );
   46045 
   46046   if( pPager->sectorSize > (u32)pPager->pageSize ){
   46047     Pgno nPageCount;          /* Total number of pages in database file */
   46048     Pgno pg1;                 /* First page of the sector pPg is located on. */
   46049     int nPage = 0;            /* Number of pages starting at pg1 to journal */
   46050     int ii;                   /* Loop counter */
   46051     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
   46052     Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
   46053 
   46054     /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
   46055     ** a journal header to be written between the pages journaled by
   46056     ** this function.
   46057     */
   46058     assert( !MEMDB );
   46059     assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
   46060     pPager->doNotSpill |= SPILLFLAG_NOSYNC;
   46061 
   46062     /* This trick assumes that both the page-size and sector-size are
   46063     ** an integer power of 2. It sets variable pg1 to the identifier
   46064     ** of the first page of the sector pPg is located on.
   46065     */
   46066     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
   46067 
   46068     nPageCount = pPager->dbSize;
   46069     if( pPg->pgno>nPageCount ){
   46070       nPage = (pPg->pgno - pg1)+1;
   46071     }else if( (pg1+nPagePerSector-1)>nPageCount ){
   46072       nPage = nPageCount+1-pg1;
   46073     }else{
   46074       nPage = nPagePerSector;
   46075     }
   46076     assert(nPage>0);
   46077     assert(pg1<=pPg->pgno);
   46078     assert((pg1+nPage)>pPg->pgno);
   46079 
   46080     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
   46081       Pgno pg = pg1+ii;
   46082       PgHdr *pPage;
   46083       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
   46084         if( pg!=PAGER_MJ_PGNO(pPager) ){
   46085           rc = sqlite3PagerGet(pPager, pg, &pPage);
   46086           if( rc==SQLITE_OK ){
   46087             rc = pager_write(pPage);
   46088             if( pPage->flags&PGHDR_NEED_SYNC ){
   46089               needSync = 1;
   46090             }
   46091             sqlite3PagerUnrefNotNull(pPage);
   46092           }
   46093         }
   46094       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
   46095         if( pPage->flags&PGHDR_NEED_SYNC ){
   46096           needSync = 1;
   46097         }
   46098         sqlite3PagerUnrefNotNull(pPage);
   46099       }
   46100     }
   46101 
   46102     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
   46103     ** starting at pg1, then it needs to be set for all of them. Because
   46104     ** writing to any of these nPage pages may damage the others, the
   46105     ** journal file must contain sync()ed copies of all of them
   46106     ** before any of them can be written out to the database file.
   46107     */
   46108     if( rc==SQLITE_OK && needSync ){
   46109       assert( !MEMDB );
   46110       for(ii=0; ii<nPage; ii++){
   46111         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
   46112         if( pPage ){
   46113           pPage->flags |= PGHDR_NEED_SYNC;
   46114           sqlite3PagerUnrefNotNull(pPage);
   46115         }
   46116       }
   46117     }
   46118 
   46119     assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
   46120     pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
   46121   }else{
   46122     rc = pager_write(pDbPage);
   46123   }
   46124   return rc;
   46125 }
   46126 
   46127 /*
   46128 ** Return TRUE if the page given in the argument was previously passed
   46129 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
   46130 ** to change the content of the page.
   46131 */
   46132 #ifndef NDEBUG
   46133 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
   46134   return pPg->flags&PGHDR_DIRTY;
   46135 }
   46136 #endif
   46137 
   46138 /*
   46139 ** A call to this routine tells the pager that it is not necessary to
   46140 ** write the information on page pPg back to the disk, even though
   46141 ** that page might be marked as dirty.  This happens, for example, when
   46142 ** the page has been added as a leaf of the freelist and so its
   46143 ** content no longer matters.
   46144 **
   46145 ** The overlying software layer calls this routine when all of the data
   46146 ** on the given page is unused. The pager marks the page as clean so
   46147 ** that it does not get written to disk.
   46148 **
   46149 ** Tests show that this optimization can quadruple the speed of large
   46150 ** DELETE operations.
   46151 */
   46152 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
   46153   Pager *pPager = pPg->pPager;
   46154   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
   46155     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
   46156     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
   46157     pPg->flags |= PGHDR_DONT_WRITE;
   46158     pager_set_pagehash(pPg);
   46159   }
   46160 }
   46161 
   46162 /*
   46163 ** This routine is called to increment the value of the database file
   46164 ** change-counter, stored as a 4-byte big-endian integer starting at
   46165 ** byte offset 24 of the pager file.  The secondary change counter at
   46166 ** 92 is also updated, as is the SQLite version number at offset 96.
   46167 **
   46168 ** But this only happens if the pPager->changeCountDone flag is false.
   46169 ** To avoid excess churning of page 1, the update only happens once.
   46170 ** See also the pager_write_changecounter() routine that does an
   46171 ** unconditional update of the change counters.
   46172 **
   46173 ** If the isDirectMode flag is zero, then this is done by calling
   46174 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
   46175 ** page data. In this case the file will be updated when the current
   46176 ** transaction is committed.
   46177 **
   46178 ** The isDirectMode flag may only be non-zero if the library was compiled
   46179 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
   46180 ** if isDirect is non-zero, then the database file is updated directly
   46181 ** by writing an updated version of page 1 using a call to the
   46182 ** sqlite3OsWrite() function.
   46183 */
   46184 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
   46185   int rc = SQLITE_OK;
   46186 
   46187   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   46188        || pPager->eState==PAGER_WRITER_DBMOD
   46189   );
   46190   assert( assert_pager_state(pPager) );
   46191 
   46192   /* Declare and initialize constant integer 'isDirect'. If the
   46193   ** atomic-write optimization is enabled in this build, then isDirect
   46194   ** is initialized to the value passed as the isDirectMode parameter
   46195   ** to this function. Otherwise, it is always set to zero.
   46196   **
   46197   ** The idea is that if the atomic-write optimization is not
   46198   ** enabled at compile time, the compiler can omit the tests of
   46199   ** 'isDirect' below, as well as the block enclosed in the
   46200   ** "if( isDirect )" condition.
   46201   */
   46202 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
   46203 # define DIRECT_MODE 0
   46204   assert( isDirectMode==0 );
   46205   UNUSED_PARAMETER(isDirectMode);
   46206 #else
   46207 # define DIRECT_MODE isDirectMode
   46208 #endif
   46209 
   46210   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
   46211     PgHdr *pPgHdr;                /* Reference to page 1 */
   46212 
   46213     assert( !pPager->tempFile && isOpen(pPager->fd) );
   46214 
   46215     /* Open page 1 of the file for writing. */
   46216     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
   46217     assert( pPgHdr==0 || rc==SQLITE_OK );
   46218 
   46219     /* If page one was fetched successfully, and this function is not
   46220     ** operating in direct-mode, make page 1 writable.  When not in
   46221     ** direct mode, page 1 is always held in cache and hence the PagerGet()
   46222     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
   46223     */
   46224     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
   46225       rc = sqlite3PagerWrite(pPgHdr);
   46226     }
   46227 
   46228     if( rc==SQLITE_OK ){
   46229       /* Actually do the update of the change counter */
   46230       pager_write_changecounter(pPgHdr);
   46231 
   46232       /* If running in direct mode, write the contents of page 1 to the file. */
   46233       if( DIRECT_MODE ){
   46234         const void *zBuf;
   46235         assert( pPager->dbFileSize>0 );
   46236         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
   46237         if( rc==SQLITE_OK ){
   46238           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
   46239           pPager->aStat[PAGER_STAT_WRITE]++;
   46240         }
   46241         if( rc==SQLITE_OK ){
   46242           /* Update the pager's copy of the change-counter. Otherwise, the
   46243           ** next time a read transaction is opened the cache will be
   46244           ** flushed (as the change-counter values will not match).  */
   46245           const void *pCopy = (const void *)&((const char *)zBuf)[24];
   46246           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
   46247           pPager->changeCountDone = 1;
   46248         }
   46249       }else{
   46250         pPager->changeCountDone = 1;
   46251       }
   46252     }
   46253 
   46254     /* Release the page reference. */
   46255     sqlite3PagerUnref(pPgHdr);
   46256   }
   46257   return rc;
   46258 }
   46259 
   46260 /*
   46261 ** Sync the database file to disk. This is a no-op for in-memory databases
   46262 ** or pages with the Pager.noSync flag set.
   46263 **
   46264 ** If successful, or if called on a pager for which it is a no-op, this
   46265 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
   46266 */
   46267 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
   46268   int rc = SQLITE_OK;
   46269 
   46270   if( isOpen(pPager->fd) ){
   46271     void *pArg = (void*)zMaster;
   46272     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
   46273     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   46274   }
   46275   if( rc==SQLITE_OK && !pPager->noSync ){
   46276     assert( !MEMDB );
   46277     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
   46278   }
   46279   return rc;
   46280 }
   46281 
   46282 /*
   46283 ** This function may only be called while a write-transaction is active in
   46284 ** rollback. If the connection is in WAL mode, this call is a no-op.
   46285 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
   46286 ** the database file, an attempt is made to obtain one.
   46287 **
   46288 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
   46289 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
   46290 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
   46291 ** returned.
   46292 */
   46293 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
   46294   int rc = SQLITE_OK;
   46295   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   46296        || pPager->eState==PAGER_WRITER_DBMOD
   46297        || pPager->eState==PAGER_WRITER_LOCKED
   46298   );
   46299   assert( assert_pager_state(pPager) );
   46300   if( 0==pagerUseWal(pPager) ){
   46301     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   46302   }
   46303   return rc;
   46304 }
   46305 
   46306 /*
   46307 ** Sync the database file for the pager pPager. zMaster points to the name
   46308 ** of a master journal file that should be written into the individual
   46309 ** journal file. zMaster may be NULL, which is interpreted as no master
   46310 ** journal (a single database transaction).
   46311 **
   46312 ** This routine ensures that:
   46313 **
   46314 **   * The database file change-counter is updated,
   46315 **   * the journal is synced (unless the atomic-write optimization is used),
   46316 **   * all dirty pages are written to the database file,
   46317 **   * the database file is truncated (if required), and
   46318 **   * the database file synced.
   46319 **
   46320 ** The only thing that remains to commit the transaction is to finalize
   46321 ** (delete, truncate or zero the first part of) the journal file (or
   46322 ** delete the master journal file if specified).
   46323 **
   46324 ** Note that if zMaster==NULL, this does not overwrite a previous value
   46325 ** passed to an sqlite3PagerCommitPhaseOne() call.
   46326 **
   46327 ** If the final parameter - noSync - is true, then the database file itself
   46328 ** is not synced. The caller must call sqlite3PagerSync() directly to
   46329 ** sync the database file before calling CommitPhaseTwo() to delete the
   46330 ** journal file in this case.
   46331 */
   46332 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   46333   Pager *pPager,                  /* Pager object */
   46334   const char *zMaster,            /* If not NULL, the master journal name */
   46335   int noSync                      /* True to omit the xSync on the db file */
   46336 ){
   46337   int rc = SQLITE_OK;             /* Return code */
   46338 
   46339   assert( pPager->eState==PAGER_WRITER_LOCKED
   46340        || pPager->eState==PAGER_WRITER_CACHEMOD
   46341        || pPager->eState==PAGER_WRITER_DBMOD
   46342        || pPager->eState==PAGER_ERROR
   46343   );
   46344   assert( assert_pager_state(pPager) );
   46345 
   46346   /* If a prior error occurred, report that error again. */
   46347   if( NEVER(pPager->errCode) ) return pPager->errCode;
   46348 
   46349   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
   46350       pPager->zFilename, zMaster, pPager->dbSize));
   46351 
   46352   /* If no database changes have been made, return early. */
   46353   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
   46354 
   46355   if( MEMDB ){
   46356     /* If this is an in-memory db, or no pages have been written to, or this
   46357     ** function has already been called, it is mostly a no-op.  However, any
   46358     ** backup in progress needs to be restarted.
   46359     */
   46360     sqlite3BackupRestart(pPager->pBackup);
   46361   }else{
   46362     if( pagerUseWal(pPager) ){
   46363       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
   46364       PgHdr *pPageOne = 0;
   46365       if( pList==0 ){
   46366         /* Must have at least one page for the WAL commit flag.
   46367         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
   46368         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
   46369         pList = pPageOne;
   46370         pList->pDirty = 0;
   46371       }
   46372       assert( rc==SQLITE_OK );
   46373       if( ALWAYS(pList) ){
   46374         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
   46375       }
   46376       sqlite3PagerUnref(pPageOne);
   46377       if( rc==SQLITE_OK ){
   46378         sqlite3PcacheCleanAll(pPager->pPCache);
   46379       }
   46380     }else{
   46381       /* The following block updates the change-counter. Exactly how it
   46382       ** does this depends on whether or not the atomic-update optimization
   46383       ** was enabled at compile time, and if this transaction meets the
   46384       ** runtime criteria to use the operation:
   46385       **
   46386       **    * The file-system supports the atomic-write property for
   46387       **      blocks of size page-size, and
   46388       **    * This commit is not part of a multi-file transaction, and
   46389       **    * Exactly one page has been modified and store in the journal file.
   46390       **
   46391       ** If the optimization was not enabled at compile time, then the
   46392       ** pager_incr_changecounter() function is called to update the change
   46393       ** counter in 'indirect-mode'. If the optimization is compiled in but
   46394       ** is not applicable to this transaction, call sqlite3JournalCreate()
   46395       ** to make sure the journal file has actually been created, then call
   46396       ** pager_incr_changecounter() to update the change-counter in indirect
   46397       ** mode.
   46398       **
   46399       ** Otherwise, if the optimization is both enabled and applicable,
   46400       ** then call pager_incr_changecounter() to update the change-counter
   46401       ** in 'direct' mode. In this case the journal file will never be
   46402       ** created for this transaction.
   46403       */
   46404   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   46405       PgHdr *pPg;
   46406       assert( isOpen(pPager->jfd)
   46407            || pPager->journalMode==PAGER_JOURNALMODE_OFF
   46408            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   46409       );
   46410       if( !zMaster && isOpen(pPager->jfd)
   46411        && pPager->journalOff==jrnlBufferSize(pPager)
   46412        && pPager->dbSize>=pPager->dbOrigSize
   46413        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
   46414       ){
   46415         /* Update the db file change counter via the direct-write method. The
   46416         ** following call will modify the in-memory representation of page 1
   46417         ** to include the updated change counter and then write page 1
   46418         ** directly to the database file. Because of the atomic-write
   46419         ** property of the host file-system, this is safe.
   46420         */
   46421         rc = pager_incr_changecounter(pPager, 1);
   46422       }else{
   46423         rc = sqlite3JournalCreate(pPager->jfd);
   46424         if( rc==SQLITE_OK ){
   46425           rc = pager_incr_changecounter(pPager, 0);
   46426         }
   46427       }
   46428   #else
   46429       rc = pager_incr_changecounter(pPager, 0);
   46430   #endif
   46431       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   46432 
   46433       /* Write the master journal name into the journal file. If a master
   46434       ** journal file name has already been written to the journal file,
   46435       ** or if zMaster is NULL (no master journal), then this call is a no-op.
   46436       */
   46437       rc = writeMasterJournal(pPager, zMaster);
   46438       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   46439 
   46440       /* Sync the journal file and write all dirty pages to the database.
   46441       ** If the atomic-update optimization is being used, this sync will not
   46442       ** create the journal file or perform any real IO.
   46443       **
   46444       ** Because the change-counter page was just modified, unless the
   46445       ** atomic-update optimization is used it is almost certain that the
   46446       ** journal requires a sync here. However, in locking_mode=exclusive
   46447       ** on a system under memory pressure it is just possible that this is
   46448       ** not the case. In this case it is likely enough that the redundant
   46449       ** xSync() call will be changed to a no-op by the OS anyhow.
   46450       */
   46451       rc = syncJournal(pPager, 0);
   46452       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   46453 
   46454       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
   46455       if( rc!=SQLITE_OK ){
   46456         assert( rc!=SQLITE_IOERR_BLOCKED );
   46457         goto commit_phase_one_exit;
   46458       }
   46459       sqlite3PcacheCleanAll(pPager->pPCache);
   46460 
   46461       /* If the file on disk is smaller than the database image, use
   46462       ** pager_truncate to grow the file here. This can happen if the database
   46463       ** image was extended as part of the current transaction and then the
   46464       ** last page in the db image moved to the free-list. In this case the
   46465       ** last page is never written out to disk, leaving the database file
   46466       ** undersized. Fix this now if it is the case.  */
   46467       if( pPager->dbSize>pPager->dbFileSize ){
   46468         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
   46469         assert( pPager->eState==PAGER_WRITER_DBMOD );
   46470         rc = pager_truncate(pPager, nNew);
   46471         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   46472       }
   46473 
   46474       /* Finally, sync the database file. */
   46475       if( !noSync ){
   46476         rc = sqlite3PagerSync(pPager, zMaster);
   46477       }
   46478       IOTRACE(("DBSYNC %p\n", pPager))
   46479     }
   46480   }
   46481 
   46482 commit_phase_one_exit:
   46483   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
   46484     pPager->eState = PAGER_WRITER_FINISHED;
   46485   }
   46486   return rc;
   46487 }
   46488 
   46489 
   46490 /*
   46491 ** When this function is called, the database file has been completely
   46492 ** updated to reflect the changes made by the current transaction and
   46493 ** synced to disk. The journal file still exists in the file-system
   46494 ** though, and if a failure occurs at this point it will eventually
   46495 ** be used as a hot-journal and the current transaction rolled back.
   46496 **
   46497 ** This function finalizes the journal file, either by deleting,
   46498 ** truncating or partially zeroing it, so that it cannot be used
   46499 ** for hot-journal rollback. Once this is done the transaction is
   46500 ** irrevocably committed.
   46501 **
   46502 ** If an error occurs, an IO error code is returned and the pager
   46503 ** moves into the error state. Otherwise, SQLITE_OK is returned.
   46504 */
   46505 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   46506   int rc = SQLITE_OK;                  /* Return code */
   46507 
   46508   /* This routine should not be called if a prior error has occurred.
   46509   ** But if (due to a coding error elsewhere in the system) it does get
   46510   ** called, just return the same error code without doing anything. */
   46511   if( NEVER(pPager->errCode) ) return pPager->errCode;
   46512 
   46513   assert( pPager->eState==PAGER_WRITER_LOCKED
   46514        || pPager->eState==PAGER_WRITER_FINISHED
   46515        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
   46516   );
   46517   assert( assert_pager_state(pPager) );
   46518 
   46519   /* An optimization. If the database was not actually modified during
   46520   ** this transaction, the pager is running in exclusive-mode and is
   46521   ** using persistent journals, then this function is a no-op.
   46522   **
   46523   ** The start of the journal file currently contains a single journal
   46524   ** header with the nRec field set to 0. If such a journal is used as
   46525   ** a hot-journal during hot-journal rollback, 0 changes will be made
   46526   ** to the database file. So there is no need to zero the journal
   46527   ** header. Since the pager is in exclusive mode, there is no need
   46528   ** to drop any locks either.
   46529   */
   46530   if( pPager->eState==PAGER_WRITER_LOCKED
   46531    && pPager->exclusiveMode
   46532    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   46533   ){
   46534     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
   46535     pPager->eState = PAGER_READER;
   46536     return SQLITE_OK;
   46537   }
   46538 
   46539   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
   46540   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
   46541   return pager_error(pPager, rc);
   46542 }
   46543 
   46544 /*
   46545 ** If a write transaction is open, then all changes made within the
   46546 ** transaction are reverted and the current write-transaction is closed.
   46547 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
   46548 ** state if an error occurs.
   46549 **
   46550 ** If the pager is already in PAGER_ERROR state when this function is called,
   46551 ** it returns Pager.errCode immediately. No work is performed in this case.
   46552 **
   46553 ** Otherwise, in rollback mode, this function performs two functions:
   46554 **
   46555 **   1) It rolls back the journal file, restoring all database file and
   46556 **      in-memory cache pages to the state they were in when the transaction
   46557 **      was opened, and
   46558 **
   46559 **   2) It finalizes the journal file, so that it is not used for hot
   46560 **      rollback at any point in the future.
   46561 **
   46562 ** Finalization of the journal file (task 2) is only performed if the
   46563 ** rollback is successful.
   46564 **
   46565 ** In WAL mode, all cache-entries containing data modified within the
   46566 ** current transaction are either expelled from the cache or reverted to
   46567 ** their pre-transaction state by re-reading data from the database or
   46568 ** WAL files. The WAL transaction is then closed.
   46569 */
   46570 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   46571   int rc = SQLITE_OK;                  /* Return code */
   46572   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
   46573 
   46574   /* PagerRollback() is a no-op if called in READER or OPEN state. If
   46575   ** the pager is already in the ERROR state, the rollback is not
   46576   ** attempted here. Instead, the error code is returned to the caller.
   46577   */
   46578   assert( assert_pager_state(pPager) );
   46579   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
   46580   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
   46581 
   46582   if( pagerUseWal(pPager) ){
   46583     int rc2;
   46584     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
   46585     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
   46586     if( rc==SQLITE_OK ) rc = rc2;
   46587   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
   46588     int eState = pPager->eState;
   46589     rc = pager_end_transaction(pPager, 0, 0);
   46590     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
   46591       /* This can happen using journal_mode=off. Move the pager to the error
   46592       ** state to indicate that the contents of the cache may not be trusted.
   46593       ** Any active readers will get SQLITE_ABORT.
   46594       */
   46595       pPager->errCode = SQLITE_ABORT;
   46596       pPager->eState = PAGER_ERROR;
   46597       return rc;
   46598     }
   46599   }else{
   46600     rc = pager_playback(pPager, 0);
   46601   }
   46602 
   46603   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
   46604   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
   46605           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
   46606           || rc==SQLITE_CANTOPEN
   46607   );
   46608 
   46609   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
   46610   ** cache. So call pager_error() on the way out to make any error persistent.
   46611   */
   46612   return pager_error(pPager, rc);
   46613 }
   46614 
   46615 /*
   46616 ** Return TRUE if the database file is opened read-only.  Return FALSE
   46617 ** if the database is (in theory) writable.
   46618 */
   46619 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
   46620   return pPager->readOnly;
   46621 }
   46622 
   46623 /*
   46624 ** Return the number of references to the pager.
   46625 */
   46626 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
   46627   return sqlite3PcacheRefCount(pPager->pPCache);
   46628 }
   46629 
   46630 /*
   46631 ** Return the approximate number of bytes of memory currently
   46632 ** used by the pager and its associated cache.
   46633 */
   46634 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
   46635   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
   46636                                      + 5*sizeof(void*);
   46637   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
   46638            + sqlite3MallocSize(pPager)
   46639            + pPager->pageSize;
   46640 }
   46641 
   46642 /*
   46643 ** Return the number of references to the specified page.
   46644 */
   46645 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
   46646   return sqlite3PcachePageRefcount(pPage);
   46647 }
   46648 
   46649 #ifdef SQLITE_TEST
   46650 /*
   46651 ** This routine is used for testing and analysis only.
   46652 */
   46653 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
   46654   static int a[11];
   46655   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
   46656   a[1] = sqlite3PcachePagecount(pPager->pPCache);
   46657   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
   46658   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
   46659   a[4] = pPager->eState;
   46660   a[5] = pPager->errCode;
   46661   a[6] = pPager->aStat[PAGER_STAT_HIT];
   46662   a[7] = pPager->aStat[PAGER_STAT_MISS];
   46663   a[8] = 0;  /* Used to be pPager->nOvfl */
   46664   a[9] = pPager->nRead;
   46665   a[10] = pPager->aStat[PAGER_STAT_WRITE];
   46666   return a;
   46667 }
   46668 #endif
   46669 
   46670 /*
   46671 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
   46672 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
   46673 ** current cache hit or miss count, according to the value of eStat. If the
   46674 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
   46675 ** returning.
   46676 */
   46677 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
   46678 
   46679   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
   46680        || eStat==SQLITE_DBSTATUS_CACHE_MISS
   46681        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
   46682   );
   46683 
   46684   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
   46685   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
   46686   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
   46687 
   46688   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
   46689   if( reset ){
   46690     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
   46691   }
   46692 }
   46693 
   46694 /*
   46695 ** Return true if this is an in-memory pager.
   46696 */
   46697 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
   46698   return MEMDB;
   46699 }
   46700 
   46701 /*
   46702 ** Check that there are at least nSavepoint savepoints open. If there are
   46703 ** currently less than nSavepoints open, then open one or more savepoints
   46704 ** to make up the difference. If the number of savepoints is already
   46705 ** equal to nSavepoint, then this function is a no-op.
   46706 **
   46707 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
   46708 ** occurs while opening the sub-journal file, then an IO error code is
   46709 ** returned. Otherwise, SQLITE_OK.
   46710 */
   46711 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
   46712   int rc = SQLITE_OK;                       /* Return code */
   46713   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
   46714 
   46715   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   46716   assert( assert_pager_state(pPager) );
   46717 
   46718   if( nSavepoint>nCurrent && pPager->useJournal ){
   46719     int ii;                                 /* Iterator variable */
   46720     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
   46721 
   46722     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
   46723     ** if the allocation fails. Otherwise, zero the new portion in case a
   46724     ** malloc failure occurs while populating it in the for(...) loop below.
   46725     */
   46726     aNew = (PagerSavepoint *)sqlite3Realloc(
   46727         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
   46728     );
   46729     if( !aNew ){
   46730       return SQLITE_NOMEM;
   46731     }
   46732     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
   46733     pPager->aSavepoint = aNew;
   46734 
   46735     /* Populate the PagerSavepoint structures just allocated. */
   46736     for(ii=nCurrent; ii<nSavepoint; ii++){
   46737       aNew[ii].nOrig = pPager->dbSize;
   46738       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
   46739         aNew[ii].iOffset = pPager->journalOff;
   46740       }else{
   46741         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
   46742       }
   46743       aNew[ii].iSubRec = pPager->nSubRec;
   46744       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
   46745       if( !aNew[ii].pInSavepoint ){
   46746         return SQLITE_NOMEM;
   46747       }
   46748       if( pagerUseWal(pPager) ){
   46749         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
   46750       }
   46751       pPager->nSavepoint = ii+1;
   46752     }
   46753     assert( pPager->nSavepoint==nSavepoint );
   46754     assertTruncateConstraint(pPager);
   46755   }
   46756 
   46757   return rc;
   46758 }
   46759 
   46760 /*
   46761 ** This function is called to rollback or release (commit) a savepoint.
   46762 ** The savepoint to release or rollback need not be the most recently
   46763 ** created savepoint.
   46764 **
   46765 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
   46766 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
   46767 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
   46768 ** that have occurred since the specified savepoint was created.
   46769 **
   46770 ** The savepoint to rollback or release is identified by parameter
   46771 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
   46772 ** (the first created). A value of (Pager.nSavepoint-1) means operate
   46773 ** on the most recently created savepoint. If iSavepoint is greater than
   46774 ** (Pager.nSavepoint-1), then this function is a no-op.
   46775 **
   46776 ** If a negative value is passed to this function, then the current
   46777 ** transaction is rolled back. This is different to calling
   46778 ** sqlite3PagerRollback() because this function does not terminate
   46779 ** the transaction or unlock the database, it just restores the
   46780 ** contents of the database to its original state.
   46781 **
   46782 ** In any case, all savepoints with an index greater than iSavepoint
   46783 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
   46784 ** then savepoint iSavepoint is also destroyed.
   46785 **
   46786 ** This function may return SQLITE_NOMEM if a memory allocation fails,
   46787 ** or an IO error code if an IO error occurs while rolling back a
   46788 ** savepoint. If no errors occur, SQLITE_OK is returned.
   46789 */
   46790 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
   46791   int rc = pPager->errCode;       /* Return code */
   46792 
   46793   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   46794   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
   46795 
   46796   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
   46797     int ii;            /* Iterator variable */
   46798     int nNew;          /* Number of remaining savepoints after this op. */
   46799 
   46800     /* Figure out how many savepoints will still be active after this
   46801     ** operation. Store this value in nNew. Then free resources associated
   46802     ** with any savepoints that are destroyed by this operation.
   46803     */
   46804     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
   46805     for(ii=nNew; ii<pPager->nSavepoint; ii++){
   46806       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   46807     }
   46808     pPager->nSavepoint = nNew;
   46809 
   46810     /* If this is a release of the outermost savepoint, truncate
   46811     ** the sub-journal to zero bytes in size. */
   46812     if( op==SAVEPOINT_RELEASE ){
   46813       if( nNew==0 && isOpen(pPager->sjfd) ){
   46814         /* Only truncate if it is an in-memory sub-journal. */
   46815         if( sqlite3IsMemJournal(pPager->sjfd) ){
   46816           rc = sqlite3OsTruncate(pPager->sjfd, 0);
   46817           assert( rc==SQLITE_OK );
   46818         }
   46819         pPager->nSubRec = 0;
   46820       }
   46821     }
   46822     /* Else this is a rollback operation, playback the specified savepoint.
   46823     ** If this is a temp-file, it is possible that the journal file has
   46824     ** not yet been opened. In this case there have been no changes to
   46825     ** the database file, so the playback operation can be skipped.
   46826     */
   46827     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
   46828       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
   46829       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
   46830       assert(rc!=SQLITE_DONE);
   46831     }
   46832   }
   46833 
   46834   return rc;
   46835 }
   46836 
   46837 /*
   46838 ** Return the full pathname of the database file.
   46839 **
   46840 ** Except, if the pager is in-memory only, then return an empty string if
   46841 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
   46842 ** used to report the filename to the user, for compatibility with legacy
   46843 ** behavior.  But when the Btree needs to know the filename for matching to
   46844 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
   46845 ** participate in shared-cache.
   46846 */
   46847 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
   46848   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
   46849 }
   46850 
   46851 /*
   46852 ** Return the VFS structure for the pager.
   46853 */
   46854 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
   46855   return pPager->pVfs;
   46856 }
   46857 
   46858 /*
   46859 ** Return the file handle for the database file associated
   46860 ** with the pager.  This might return NULL if the file has
   46861 ** not yet been opened.
   46862 */
   46863 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
   46864   return pPager->fd;
   46865 }
   46866 
   46867 /*
   46868 ** Return the full pathname of the journal file.
   46869 */
   46870 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
   46871   return pPager->zJournal;
   46872 }
   46873 
   46874 /*
   46875 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
   46876 ** if fsync()s are executed normally.
   46877 */
   46878 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
   46879   return pPager->noSync;
   46880 }
   46881 
   46882 #ifdef SQLITE_HAS_CODEC
   46883 /*
   46884 ** Set or retrieve the codec for this pager
   46885 */
   46886 SQLITE_PRIVATE void sqlite3PagerSetCodec(
   46887   Pager *pPager,
   46888   void *(*xCodec)(void*,void*,Pgno,int),
   46889   void (*xCodecSizeChng)(void*,int,int),
   46890   void (*xCodecFree)(void*),
   46891   void *pCodec
   46892 ){
   46893   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   46894   pPager->xCodec = pPager->memDb ? 0 : xCodec;
   46895   pPager->xCodecSizeChng = xCodecSizeChng;
   46896   pPager->xCodecFree = xCodecFree;
   46897   pPager->pCodec = pCodec;
   46898   pagerReportSize(pPager);
   46899 }
   46900 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
   46901   return pPager->pCodec;
   46902 }
   46903 
   46904 /*
   46905 ** This function is called by the wal module when writing page content
   46906 ** into the log file.
   46907 **
   46908 ** This function returns a pointer to a buffer containing the encrypted
   46909 ** page content. If a malloc fails, this function may return NULL.
   46910 */
   46911 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
   46912   void *aData = 0;
   46913   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
   46914   return aData;
   46915 }
   46916 
   46917 /*
   46918 ** Return the current pager state
   46919 */
   46920 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
   46921   return pPager->eState;
   46922 }
   46923 #endif /* SQLITE_HAS_CODEC */
   46924 
   46925 #ifndef SQLITE_OMIT_AUTOVACUUM
   46926 /*
   46927 ** Move the page pPg to location pgno in the file.
   46928 **
   46929 ** There must be no references to the page previously located at
   46930 ** pgno (which we call pPgOld) though that page is allowed to be
   46931 ** in cache.  If the page previously located at pgno is not already
   46932 ** in the rollback journal, it is not put there by by this routine.
   46933 **
   46934 ** References to the page pPg remain valid. Updating any
   46935 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
   46936 ** allocated along with the page) is the responsibility of the caller.
   46937 **
   46938 ** A transaction must be active when this routine is called. It used to be
   46939 ** required that a statement transaction was not active, but this restriction
   46940 ** has been removed (CREATE INDEX needs to move a page when a statement
   46941 ** transaction is active).
   46942 **
   46943 ** If the fourth argument, isCommit, is non-zero, then this page is being
   46944 ** moved as part of a database reorganization just before the transaction
   46945 ** is being committed. In this case, it is guaranteed that the database page
   46946 ** pPg refers to will not be written to again within this transaction.
   46947 **
   46948 ** This function may return SQLITE_NOMEM or an IO error code if an error
   46949 ** occurs. Otherwise, it returns SQLITE_OK.
   46950 */
   46951 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
   46952   PgHdr *pPgOld;               /* The page being overwritten. */
   46953   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
   46954   int rc;                      /* Return code */
   46955   Pgno origPgno;               /* The original page number */
   46956 
   46957   assert( pPg->nRef>0 );
   46958   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   46959        || pPager->eState==PAGER_WRITER_DBMOD
   46960   );
   46961   assert( assert_pager_state(pPager) );
   46962 
   46963   /* In order to be able to rollback, an in-memory database must journal
   46964   ** the page we are moving from.
   46965   */
   46966   if( MEMDB ){
   46967     rc = sqlite3PagerWrite(pPg);
   46968     if( rc ) return rc;
   46969   }
   46970 
   46971   /* If the page being moved is dirty and has not been saved by the latest
   46972   ** savepoint, then save the current contents of the page into the
   46973   ** sub-journal now. This is required to handle the following scenario:
   46974   **
   46975   **   BEGIN;
   46976   **     <journal page X, then modify it in memory>
   46977   **     SAVEPOINT one;
   46978   **       <Move page X to location Y>
   46979   **     ROLLBACK TO one;
   46980   **
   46981   ** If page X were not written to the sub-journal here, it would not
   46982   ** be possible to restore its contents when the "ROLLBACK TO one"
   46983   ** statement were is processed.
   46984   **
   46985   ** subjournalPage() may need to allocate space to store pPg->pgno into
   46986   ** one or more savepoint bitvecs. This is the reason this function
   46987   ** may return SQLITE_NOMEM.
   46988   */
   46989   if( pPg->flags&PGHDR_DIRTY
   46990    && subjRequiresPage(pPg)
   46991    && SQLITE_OK!=(rc = subjournalPage(pPg))
   46992   ){
   46993     return rc;
   46994   }
   46995 
   46996   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
   46997       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
   46998   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
   46999 
   47000   /* If the journal needs to be sync()ed before page pPg->pgno can
   47001   ** be written to, store pPg->pgno in local variable needSyncPgno.
   47002   **
   47003   ** If the isCommit flag is set, there is no need to remember that
   47004   ** the journal needs to be sync()ed before database page pPg->pgno
   47005   ** can be written to. The caller has already promised not to write to it.
   47006   */
   47007   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
   47008     needSyncPgno = pPg->pgno;
   47009     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
   47010             pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
   47011     assert( pPg->flags&PGHDR_DIRTY );
   47012   }
   47013 
   47014   /* If the cache contains a page with page-number pgno, remove it
   47015   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
   47016   ** page pgno before the 'move' operation, it needs to be retained
   47017   ** for the page moved there.
   47018   */
   47019   pPg->flags &= ~PGHDR_NEED_SYNC;
   47020   pPgOld = pager_lookup(pPager, pgno);
   47021   assert( !pPgOld || pPgOld->nRef==1 );
   47022   if( pPgOld ){
   47023     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
   47024     if( MEMDB ){
   47025       /* Do not discard pages from an in-memory database since we might
   47026       ** need to rollback later.  Just move the page out of the way. */
   47027       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
   47028     }else{
   47029       sqlite3PcacheDrop(pPgOld);
   47030     }
   47031   }
   47032 
   47033   origPgno = pPg->pgno;
   47034   sqlite3PcacheMove(pPg, pgno);
   47035   sqlite3PcacheMakeDirty(pPg);
   47036 
   47037   /* For an in-memory database, make sure the original page continues
   47038   ** to exist, in case the transaction needs to roll back.  Use pPgOld
   47039   ** as the original page since it has already been allocated.
   47040   */
   47041   if( MEMDB ){
   47042     assert( pPgOld );
   47043     sqlite3PcacheMove(pPgOld, origPgno);
   47044     sqlite3PagerUnrefNotNull(pPgOld);
   47045   }
   47046 
   47047   if( needSyncPgno ){
   47048     /* If needSyncPgno is non-zero, then the journal file needs to be
   47049     ** sync()ed before any data is written to database file page needSyncPgno.
   47050     ** Currently, no such page exists in the page-cache and the
   47051     ** "is journaled" bitvec flag has been set. This needs to be remedied by
   47052     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
   47053     ** flag.
   47054     **
   47055     ** If the attempt to load the page into the page-cache fails, (due
   47056     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
   47057     ** array. Otherwise, if the page is loaded and written again in
   47058     ** this transaction, it may be written to the database file before
   47059     ** it is synced into the journal file. This way, it may end up in
   47060     ** the journal file twice, but that is not a problem.
   47061     */
   47062     PgHdr *pPgHdr;
   47063     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
   47064     if( rc!=SQLITE_OK ){
   47065       if( needSyncPgno<=pPager->dbOrigSize ){
   47066         assert( pPager->pTmpSpace!=0 );
   47067         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
   47068       }
   47069       return rc;
   47070     }
   47071     pPgHdr->flags |= PGHDR_NEED_SYNC;
   47072     sqlite3PcacheMakeDirty(pPgHdr);
   47073     sqlite3PagerUnrefNotNull(pPgHdr);
   47074   }
   47075 
   47076   return SQLITE_OK;
   47077 }
   47078 #endif
   47079 
   47080 /*
   47081 ** Return a pointer to the data for the specified page.
   47082 */
   47083 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
   47084   assert( pPg->nRef>0 || pPg->pPager->memDb );
   47085   return pPg->pData;
   47086 }
   47087 
   47088 /*
   47089 ** Return a pointer to the Pager.nExtra bytes of "extra" space
   47090 ** allocated along with the specified page.
   47091 */
   47092 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
   47093   return pPg->pExtra;
   47094 }
   47095 
   47096 /*
   47097 ** Get/set the locking-mode for this pager. Parameter eMode must be one
   47098 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
   47099 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
   47100 ** the locking-mode is set to the value specified.
   47101 **
   47102 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
   47103 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
   47104 ** locking-mode.
   47105 */
   47106 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
   47107   assert( eMode==PAGER_LOCKINGMODE_QUERY
   47108             || eMode==PAGER_LOCKINGMODE_NORMAL
   47109             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   47110   assert( PAGER_LOCKINGMODE_QUERY<0 );
   47111   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
   47112   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
   47113   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
   47114     pPager->exclusiveMode = (u8)eMode;
   47115   }
   47116   return (int)pPager->exclusiveMode;
   47117 }
   47118 
   47119 /*
   47120 ** Set the journal-mode for this pager. Parameter eMode must be one of:
   47121 **
   47122 **    PAGER_JOURNALMODE_DELETE
   47123 **    PAGER_JOURNALMODE_TRUNCATE
   47124 **    PAGER_JOURNALMODE_PERSIST
   47125 **    PAGER_JOURNALMODE_OFF
   47126 **    PAGER_JOURNALMODE_MEMORY
   47127 **    PAGER_JOURNALMODE_WAL
   47128 **
   47129 ** The journalmode is set to the value specified if the change is allowed.
   47130 ** The change may be disallowed for the following reasons:
   47131 **
   47132 **   *  An in-memory database can only have its journal_mode set to _OFF
   47133 **      or _MEMORY.
   47134 **
   47135 **   *  Temporary databases cannot have _WAL journalmode.
   47136 **
   47137 ** The returned indicate the current (possibly updated) journal-mode.
   47138 */
   47139 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
   47140   u8 eOld = pPager->journalMode;    /* Prior journalmode */
   47141 
   47142 #ifdef SQLITE_DEBUG
   47143   /* The print_pager_state() routine is intended to be used by the debugger
   47144   ** only.  We invoke it once here to suppress a compiler warning. */
   47145   print_pager_state(pPager);
   47146 #endif
   47147 
   47148 
   47149   /* The eMode parameter is always valid */
   47150   assert(      eMode==PAGER_JOURNALMODE_DELETE
   47151             || eMode==PAGER_JOURNALMODE_TRUNCATE
   47152             || eMode==PAGER_JOURNALMODE_PERSIST
   47153             || eMode==PAGER_JOURNALMODE_OFF
   47154             || eMode==PAGER_JOURNALMODE_WAL
   47155             || eMode==PAGER_JOURNALMODE_MEMORY );
   47156 
   47157   /* This routine is only called from the OP_JournalMode opcode, and
   47158   ** the logic there will never allow a temporary file to be changed
   47159   ** to WAL mode.
   47160   */
   47161   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
   47162 
   47163   /* Do allow the journalmode of an in-memory database to be set to
   47164   ** anything other than MEMORY or OFF
   47165   */
   47166   if( MEMDB ){
   47167     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
   47168     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
   47169       eMode = eOld;
   47170     }
   47171   }
   47172 
   47173   if( eMode!=eOld ){
   47174 
   47175     /* Change the journal mode. */
   47176     assert( pPager->eState!=PAGER_ERROR );
   47177     pPager->journalMode = (u8)eMode;
   47178 
   47179     /* When transistioning from TRUNCATE or PERSIST to any other journal
   47180     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
   47181     ** delete the journal file.
   47182     */
   47183     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   47184     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
   47185     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
   47186     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
   47187     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
   47188     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
   47189 
   47190     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
   47191     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
   47192 
   47193       /* In this case we would like to delete the journal file. If it is
   47194       ** not possible, then that is not a problem. Deleting the journal file
   47195       ** here is an optimization only.
   47196       **
   47197       ** Before deleting the journal file, obtain a RESERVED lock on the
   47198       ** database file. This ensures that the journal file is not deleted
   47199       ** while it is in use by some other client.
   47200       */
   47201       sqlite3OsClose(pPager->jfd);
   47202       if( pPager->eLock>=RESERVED_LOCK ){
   47203         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   47204       }else{
   47205         int rc = SQLITE_OK;
   47206         int state = pPager->eState;
   47207         assert( state==PAGER_OPEN || state==PAGER_READER );
   47208         if( state==PAGER_OPEN ){
   47209           rc = sqlite3PagerSharedLock(pPager);
   47210         }
   47211         if( pPager->eState==PAGER_READER ){
   47212           assert( rc==SQLITE_OK );
   47213           rc = pagerLockDb(pPager, RESERVED_LOCK);
   47214         }
   47215         if( rc==SQLITE_OK ){
   47216           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   47217         }
   47218         if( rc==SQLITE_OK && state==PAGER_READER ){
   47219           pagerUnlockDb(pPager, SHARED_LOCK);
   47220         }else if( state==PAGER_OPEN ){
   47221           pager_unlock(pPager);
   47222         }
   47223         assert( state==pPager->eState );
   47224       }
   47225     }
   47226   }
   47227 
   47228   /* Return the new journal mode */
   47229   return (int)pPager->journalMode;
   47230 }
   47231 
   47232 /*
   47233 ** Return the current journal mode.
   47234 */
   47235 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
   47236   return (int)pPager->journalMode;
   47237 }
   47238 
   47239 /*
   47240 ** Return TRUE if the pager is in a state where it is OK to change the
   47241 ** journalmode.  Journalmode changes can only happen when the database
   47242 ** is unmodified.
   47243 */
   47244 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
   47245   assert( assert_pager_state(pPager) );
   47246   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
   47247   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
   47248   return 1;
   47249 }
   47250 
   47251 /*
   47252 ** Get/set the size-limit used for persistent journal files.
   47253 **
   47254 ** Setting the size limit to -1 means no limit is enforced.
   47255 ** An attempt to set a limit smaller than -1 is a no-op.
   47256 */
   47257 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
   47258   if( iLimit>=-1 ){
   47259     pPager->journalSizeLimit = iLimit;
   47260     sqlite3WalLimit(pPager->pWal, iLimit);
   47261   }
   47262   return pPager->journalSizeLimit;
   47263 }
   47264 
   47265 /*
   47266 ** Return a pointer to the pPager->pBackup variable. The backup module
   47267 ** in backup.c maintains the content of this variable. This module
   47268 ** uses it opaquely as an argument to sqlite3BackupRestart() and
   47269 ** sqlite3BackupUpdate() only.
   47270 */
   47271 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
   47272   return &pPager->pBackup;
   47273 }
   47274 
   47275 #ifndef SQLITE_OMIT_VACUUM
   47276 /*
   47277 ** Unless this is an in-memory or temporary database, clear the pager cache.
   47278 */
   47279 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
   47280   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
   47281 }
   47282 #endif
   47283 
   47284 #ifndef SQLITE_OMIT_WAL
   47285 /*
   47286 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
   47287 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
   47288 ** or wal_blocking_checkpoint() API functions.
   47289 **
   47290 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   47291 */
   47292 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
   47293   int rc = SQLITE_OK;
   47294   if( pPager->pWal ){
   47295     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
   47296         pPager->xBusyHandler, pPager->pBusyHandlerArg,
   47297         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
   47298         pnLog, pnCkpt
   47299     );
   47300   }
   47301   return rc;
   47302 }
   47303 
   47304 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
   47305   return sqlite3WalCallback(pPager->pWal);
   47306 }
   47307 
   47308 /*
   47309 ** Return true if the underlying VFS for the given pager supports the
   47310 ** primitives necessary for write-ahead logging.
   47311 */
   47312 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
   47313   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
   47314   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
   47315 }
   47316 
   47317 /*
   47318 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
   47319 ** is obtained instead, immediately release it.
   47320 */
   47321 static int pagerExclusiveLock(Pager *pPager){
   47322   int rc;                         /* Return code */
   47323 
   47324   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   47325   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   47326   if( rc!=SQLITE_OK ){
   47327     /* If the attempt to grab the exclusive lock failed, release the
   47328     ** pending lock that may have been obtained instead.  */
   47329     pagerUnlockDb(pPager, SHARED_LOCK);
   47330   }
   47331 
   47332   return rc;
   47333 }
   47334 
   47335 /*
   47336 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
   47337 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
   47338 ** lock on the database file and use heap-memory to store the wal-index
   47339 ** in. Otherwise, use the normal shared-memory.
   47340 */
   47341 static int pagerOpenWal(Pager *pPager){
   47342   int rc = SQLITE_OK;
   47343 
   47344   assert( pPager->pWal==0 && pPager->tempFile==0 );
   47345   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   47346 
   47347   /* If the pager is already in exclusive-mode, the WAL module will use
   47348   ** heap-memory for the wal-index instead of the VFS shared-memory
   47349   ** implementation. Take the exclusive lock now, before opening the WAL
   47350   ** file, to make sure this is safe.
   47351   */
   47352   if( pPager->exclusiveMode ){
   47353     rc = pagerExclusiveLock(pPager);
   47354   }
   47355 
   47356   /* Open the connection to the log file. If this operation fails,
   47357   ** (e.g. due to malloc() failure), return an error code.
   47358   */
   47359   if( rc==SQLITE_OK ){
   47360     rc = sqlite3WalOpen(pPager->pVfs,
   47361         pPager->fd, pPager->zWal, pPager->exclusiveMode,
   47362         pPager->journalSizeLimit, &pPager->pWal
   47363     );
   47364   }
   47365   pagerFixMaplimit(pPager);
   47366 
   47367   return rc;
   47368 }
   47369 
   47370 
   47371 /*
   47372 ** The caller must be holding a SHARED lock on the database file to call
   47373 ** this function.
   47374 **
   47375 ** If the pager passed as the first argument is open on a real database
   47376 ** file (not a temp file or an in-memory database), and the WAL file
   47377 ** is not already open, make an attempt to open it now. If successful,
   47378 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
   47379 ** not support the xShmXXX() methods, return an error code. *pbOpen is
   47380 ** not modified in either case.
   47381 **
   47382 ** If the pager is open on a temp-file (or in-memory database), or if
   47383 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
   47384 ** without doing anything.
   47385 */
   47386 SQLITE_PRIVATE int sqlite3PagerOpenWal(
   47387   Pager *pPager,                  /* Pager object */
   47388   int *pbOpen                     /* OUT: Set to true if call is a no-op */
   47389 ){
   47390   int rc = SQLITE_OK;             /* Return code */
   47391 
   47392   assert( assert_pager_state(pPager) );
   47393   assert( pPager->eState==PAGER_OPEN   || pbOpen );
   47394   assert( pPager->eState==PAGER_READER || !pbOpen );
   47395   assert( pbOpen==0 || *pbOpen==0 );
   47396   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
   47397 
   47398   if( !pPager->tempFile && !pPager->pWal ){
   47399     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
   47400 
   47401     /* Close any rollback journal previously open */
   47402     sqlite3OsClose(pPager->jfd);
   47403 
   47404     rc = pagerOpenWal(pPager);
   47405     if( rc==SQLITE_OK ){
   47406       pPager->journalMode = PAGER_JOURNALMODE_WAL;
   47407       pPager->eState = PAGER_OPEN;
   47408     }
   47409   }else{
   47410     *pbOpen = 1;
   47411   }
   47412 
   47413   return rc;
   47414 }
   47415 
   47416 /*
   47417 ** This function is called to close the connection to the log file prior
   47418 ** to switching from WAL to rollback mode.
   47419 **
   47420 ** Before closing the log file, this function attempts to take an
   47421 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
   47422 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
   47423 ** If successful, the EXCLUSIVE lock is not released before returning.
   47424 */
   47425 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
   47426   int rc = SQLITE_OK;
   47427 
   47428   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
   47429 
   47430   /* If the log file is not already open, but does exist in the file-system,
   47431   ** it may need to be checkpointed before the connection can switch to
   47432   ** rollback mode. Open it now so this can happen.
   47433   */
   47434   if( !pPager->pWal ){
   47435     int logexists = 0;
   47436     rc = pagerLockDb(pPager, SHARED_LOCK);
   47437     if( rc==SQLITE_OK ){
   47438       rc = sqlite3OsAccess(
   47439           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
   47440       );
   47441     }
   47442     if( rc==SQLITE_OK && logexists ){
   47443       rc = pagerOpenWal(pPager);
   47444     }
   47445   }
   47446 
   47447   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
   47448   ** the database file, the log and log-summary files will be deleted.
   47449   */
   47450   if( rc==SQLITE_OK && pPager->pWal ){
   47451     rc = pagerExclusiveLock(pPager);
   47452     if( rc==SQLITE_OK ){
   47453       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
   47454                            pPager->pageSize, (u8*)pPager->pTmpSpace);
   47455       pPager->pWal = 0;
   47456       pagerFixMaplimit(pPager);
   47457     }
   47458   }
   47459   return rc;
   47460 }
   47461 
   47462 #endif /* !SQLITE_OMIT_WAL */
   47463 
   47464 #ifdef SQLITE_ENABLE_ZIPVFS
   47465 /*
   47466 ** A read-lock must be held on the pager when this function is called. If
   47467 ** the pager is in WAL mode and the WAL file currently contains one or more
   47468 ** frames, return the size in bytes of the page images stored within the
   47469 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
   47470 ** is empty, return 0.
   47471 */
   47472 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
   47473   assert( pPager->eState==PAGER_READER );
   47474   return sqlite3WalFramesize(pPager->pWal);
   47475 }
   47476 #endif
   47477 
   47478 #endif /* SQLITE_OMIT_DISKIO */
   47479 
   47480 /************** End of pager.c ***********************************************/
   47481 /************** Begin file wal.c *********************************************/
   47482 /*
   47483 ** 2010 February 1
   47484 **
   47485 ** The author disclaims copyright to this source code.  In place of
   47486 ** a legal notice, here is a blessing:
   47487 **
   47488 **    May you do good and not evil.
   47489 **    May you find forgiveness for yourself and forgive others.
   47490 **    May you share freely, never taking more than you give.
   47491 **
   47492 *************************************************************************
   47493 **
   47494 ** This file contains the implementation of a write-ahead log (WAL) used in
   47495 ** "journal_mode=WAL" mode.
   47496 **
   47497 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
   47498 **
   47499 ** A WAL file consists of a header followed by zero or more "frames".
   47500 ** Each frame records the revised content of a single page from the
   47501 ** database file.  All changes to the database are recorded by writing
   47502 ** frames into the WAL.  Transactions commit when a frame is written that
   47503 ** contains a commit marker.  A single WAL can and usually does record
   47504 ** multiple transactions.  Periodically, the content of the WAL is
   47505 ** transferred back into the database file in an operation called a
   47506 ** "checkpoint".
   47507 **
   47508 ** A single WAL file can be used multiple times.  In other words, the
   47509 ** WAL can fill up with frames and then be checkpointed and then new
   47510 ** frames can overwrite the old ones.  A WAL always grows from beginning
   47511 ** toward the end.  Checksums and counters attached to each frame are
   47512 ** used to determine which frames within the WAL are valid and which
   47513 ** are leftovers from prior checkpoints.
   47514 **
   47515 ** The WAL header is 32 bytes in size and consists of the following eight
   47516 ** big-endian 32-bit unsigned integer values:
   47517 **
   47518 **     0: Magic number.  0x377f0682 or 0x377f0683
   47519 **     4: File format version.  Currently 3007000
   47520 **     8: Database page size.  Example: 1024
   47521 **    12: Checkpoint sequence number
   47522 **    16: Salt-1, random integer incremented with each checkpoint
   47523 **    20: Salt-2, a different random integer changing with each ckpt
   47524 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
   47525 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
   47526 **
   47527 ** Immediately following the wal-header are zero or more frames. Each
   47528 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
   47529 ** of page data. The frame-header is six big-endian 32-bit unsigned
   47530 ** integer values, as follows:
   47531 **
   47532 **     0: Page number.
   47533 **     4: For commit records, the size of the database image in pages
   47534 **        after the commit. For all other records, zero.
   47535 **     8: Salt-1 (copied from the header)
   47536 **    12: Salt-2 (copied from the header)
   47537 **    16: Checksum-1.
   47538 **    20: Checksum-2.
   47539 **
   47540 ** A frame is considered valid if and only if the following conditions are
   47541 ** true:
   47542 **
   47543 **    (1) The salt-1 and salt-2 values in the frame-header match
   47544 **        salt values in the wal-header
   47545 **
   47546 **    (2) The checksum values in the final 8 bytes of the frame-header
   47547 **        exactly match the checksum computed consecutively on the
   47548 **        WAL header and the first 8 bytes and the content of all frames
   47549 **        up to and including the current frame.
   47550 **
   47551 ** The checksum is computed using 32-bit big-endian integers if the
   47552 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
   47553 ** is computed using little-endian if the magic number is 0x377f0682.
   47554 ** The checksum values are always stored in the frame header in a
   47555 ** big-endian format regardless of which byte order is used to compute
   47556 ** the checksum.  The checksum is computed by interpreting the input as
   47557 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
   47558 ** algorithm used for the checksum is as follows:
   47559 **
   47560 **   for i from 0 to n-1 step 2:
   47561 **     s0 += x[i] + s1;
   47562 **     s1 += x[i+1] + s0;
   47563 **   endfor
   47564 **
   47565 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
   47566 ** in reverse order (the largest fibonacci weight occurs on the first element
   47567 ** of the sequence being summed.)  The s1 value spans all 32-bit
   47568 ** terms of the sequence whereas s0 omits the final term.
   47569 **
   47570 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
   47571 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
   47572 ** The VFS.xSync operations serve as write barriers - all writes launched
   47573 ** before the xSync must complete before any write that launches after the
   47574 ** xSync begins.
   47575 **
   47576 ** After each checkpoint, the salt-1 value is incremented and the salt-2
   47577 ** value is randomized.  This prevents old and new frames in the WAL from
   47578 ** being considered valid at the same time and being checkpointing together
   47579 ** following a crash.
   47580 **
   47581 ** READER ALGORITHM
   47582 **
   47583 ** To read a page from the database (call it page number P), a reader
   47584 ** first checks the WAL to see if it contains page P.  If so, then the
   47585 ** last valid instance of page P that is a followed by a commit frame
   47586 ** or is a commit frame itself becomes the value read.  If the WAL
   47587 ** contains no copies of page P that are valid and which are a commit
   47588 ** frame or are followed by a commit frame, then page P is read from
   47589 ** the database file.
   47590 **
   47591 ** To start a read transaction, the reader records the index of the last
   47592 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
   47593 ** for all subsequent read operations.  New transactions can be appended
   47594 ** to the WAL, but as long as the reader uses its original mxFrame value
   47595 ** and ignores the newly appended content, it will see a consistent snapshot
   47596 ** of the database from a single point in time.  This technique allows
   47597 ** multiple concurrent readers to view different versions of the database
   47598 ** content simultaneously.
   47599 **
   47600 ** The reader algorithm in the previous paragraphs works correctly, but
   47601 ** because frames for page P can appear anywhere within the WAL, the
   47602 ** reader has to scan the entire WAL looking for page P frames.  If the
   47603 ** WAL is large (multiple megabytes is typical) that scan can be slow,
   47604 ** and read performance suffers.  To overcome this problem, a separate
   47605 ** data structure called the wal-index is maintained to expedite the
   47606 ** search for frames of a particular page.
   47607 **
   47608 ** WAL-INDEX FORMAT
   47609 **
   47610 ** Conceptually, the wal-index is shared memory, though VFS implementations
   47611 ** might choose to implement the wal-index using a mmapped file.  Because
   47612 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
   47613 ** on a network filesystem.  All users of the database must be able to
   47614 ** share memory.
   47615 **
   47616 ** The wal-index is transient.  After a crash, the wal-index can (and should
   47617 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
   47618 ** to either truncate or zero the header of the wal-index when the last
   47619 ** connection to it closes.  Because the wal-index is transient, it can
   47620 ** use an architecture-specific format; it does not have to be cross-platform.
   47621 ** Hence, unlike the database and WAL file formats which store all values
   47622 ** as big endian, the wal-index can store multi-byte values in the native
   47623 ** byte order of the host computer.
   47624 **
   47625 ** The purpose of the wal-index is to answer this question quickly:  Given
   47626 ** a page number P and a maximum frame index M, return the index of the
   47627 ** last frame in the wal before frame M for page P in the WAL, or return
   47628 ** NULL if there are no frames for page P in the WAL prior to M.
   47629 **
   47630 ** The wal-index consists of a header region, followed by an one or
   47631 ** more index blocks.
   47632 **
   47633 ** The wal-index header contains the total number of frames within the WAL
   47634 ** in the mxFrame field.
   47635 **
   47636 ** Each index block except for the first contains information on
   47637 ** HASHTABLE_NPAGE frames. The first index block contains information on
   47638 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
   47639 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
   47640 ** first index block are the same size as all other index blocks in the
   47641 ** wal-index.
   47642 **
   47643 ** Each index block contains two sections, a page-mapping that contains the
   47644 ** database page number associated with each wal frame, and a hash-table
   47645 ** that allows readers to query an index block for a specific page number.
   47646 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
   47647 ** for the first index block) 32-bit page numbers. The first entry in the
   47648 ** first index-block contains the database page number corresponding to the
   47649 ** first frame in the WAL file. The first entry in the second index block
   47650 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
   47651 ** the log, and so on.
   47652 **
   47653 ** The last index block in a wal-index usually contains less than the full
   47654 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
   47655 ** depending on the contents of the WAL file. This does not change the
   47656 ** allocated size of the page-mapping array - the page-mapping array merely
   47657 ** contains unused entries.
   47658 **
   47659 ** Even without using the hash table, the last frame for page P
   47660 ** can be found by scanning the page-mapping sections of each index block
   47661 ** starting with the last index block and moving toward the first, and
   47662 ** within each index block, starting at the end and moving toward the
   47663 ** beginning.  The first entry that equals P corresponds to the frame
   47664 ** holding the content for that page.
   47665 **
   47666 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
   47667 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
   47668 ** hash table for each page number in the mapping section, so the hash
   47669 ** table is never more than half full.  The expected number of collisions
   47670 ** prior to finding a match is 1.  Each entry of the hash table is an
   47671 ** 1-based index of an entry in the mapping section of the same
   47672 ** index block.   Let K be the 1-based index of the largest entry in
   47673 ** the mapping section.  (For index blocks other than the last, K will
   47674 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
   47675 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
   47676 ** contain a value of 0.
   47677 **
   47678 ** To look for page P in the hash table, first compute a hash iKey on
   47679 ** P as follows:
   47680 **
   47681 **      iKey = (P * 383) % HASHTABLE_NSLOT
   47682 **
   47683 ** Then start scanning entries of the hash table, starting with iKey
   47684 ** (wrapping around to the beginning when the end of the hash table is
   47685 ** reached) until an unused hash slot is found. Let the first unused slot
   47686 ** be at index iUnused.  (iUnused might be less than iKey if there was
   47687 ** wrap-around.) Because the hash table is never more than half full,
   47688 ** the search is guaranteed to eventually hit an unused entry.  Let
   47689 ** iMax be the value between iKey and iUnused, closest to iUnused,
   47690 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
   47691 ** no hash slot such that aHash[i]==p) then page P is not in the
   47692 ** current index block.  Otherwise the iMax-th mapping entry of the
   47693 ** current index block corresponds to the last entry that references
   47694 ** page P.
   47695 **
   47696 ** A hash search begins with the last index block and moves toward the
   47697 ** first index block, looking for entries corresponding to page P.  On
   47698 ** average, only two or three slots in each index block need to be
   47699 ** examined in order to either find the last entry for page P, or to
   47700 ** establish that no such entry exists in the block.  Each index block
   47701 ** holds over 4000 entries.  So two or three index blocks are sufficient
   47702 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
   47703 ** comparisons (on average) suffice to either locate a frame in the
   47704 ** WAL or to establish that the frame does not exist in the WAL.  This
   47705 ** is much faster than scanning the entire 10MB WAL.
   47706 **
   47707 ** Note that entries are added in order of increasing K.  Hence, one
   47708 ** reader might be using some value K0 and a second reader that started
   47709 ** at a later time (after additional transactions were added to the WAL
   47710 ** and to the wal-index) might be using a different value K1, where K1>K0.
   47711 ** Both readers can use the same hash table and mapping section to get
   47712 ** the correct result.  There may be entries in the hash table with
   47713 ** K>K0 but to the first reader, those entries will appear to be unused
   47714 ** slots in the hash table and so the first reader will get an answer as
   47715 ** if no values greater than K0 had ever been inserted into the hash table
   47716 ** in the first place - which is what reader one wants.  Meanwhile, the
   47717 ** second reader using K1 will see additional values that were inserted
   47718 ** later, which is exactly what reader two wants.
   47719 **
   47720 ** When a rollback occurs, the value of K is decreased. Hash table entries
   47721 ** that correspond to frames greater than the new K value are removed
   47722 ** from the hash table at this point.
   47723 */
   47724 #ifndef SQLITE_OMIT_WAL
   47725 
   47726 
   47727 /*
   47728 ** Trace output macros
   47729 */
   47730 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   47731 SQLITE_PRIVATE int sqlite3WalTrace = 0;
   47732 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
   47733 #else
   47734 # define WALTRACE(X)
   47735 #endif
   47736 
   47737 /*
   47738 ** The maximum (and only) versions of the wal and wal-index formats
   47739 ** that may be interpreted by this version of SQLite.
   47740 **
   47741 ** If a client begins recovering a WAL file and finds that (a) the checksum
   47742 ** values in the wal-header are correct and (b) the version field is not
   47743 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
   47744 **
   47745 ** Similarly, if a client successfully reads a wal-index header (i.e. the
   47746 ** checksum test is successful) and finds that the version field is not
   47747 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
   47748 ** returns SQLITE_CANTOPEN.
   47749 */
   47750 #define WAL_MAX_VERSION      3007000
   47751 #define WALINDEX_MAX_VERSION 3007000
   47752 
   47753 /*
   47754 ** Indices of various locking bytes.   WAL_NREADER is the number
   47755 ** of available reader locks and should be at least 3.
   47756 */
   47757 #define WAL_WRITE_LOCK         0
   47758 #define WAL_ALL_BUT_WRITE      1
   47759 #define WAL_CKPT_LOCK          1
   47760 #define WAL_RECOVER_LOCK       2
   47761 #define WAL_READ_LOCK(I)       (3+(I))
   47762 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
   47763 
   47764 
   47765 /* Object declarations */
   47766 typedef struct WalIndexHdr WalIndexHdr;
   47767 typedef struct WalIterator WalIterator;
   47768 typedef struct WalCkptInfo WalCkptInfo;
   47769 
   47770 
   47771 /*
   47772 ** The following object holds a copy of the wal-index header content.
   47773 **
   47774 ** The actual header in the wal-index consists of two copies of this
   47775 ** object.
   47776 **
   47777 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
   47778 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
   47779 ** added in 3.7.1 when support for 64K pages was added.
   47780 */
   47781 struct WalIndexHdr {
   47782   u32 iVersion;                   /* Wal-index version */
   47783   u32 unused;                     /* Unused (padding) field */
   47784   u32 iChange;                    /* Counter incremented each transaction */
   47785   u8 isInit;                      /* 1 when initialized */
   47786   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
   47787   u16 szPage;                     /* Database page size in bytes. 1==64K */
   47788   u32 mxFrame;                    /* Index of last valid frame in the WAL */
   47789   u32 nPage;                      /* Size of database in pages */
   47790   u32 aFrameCksum[2];             /* Checksum of last frame in log */
   47791   u32 aSalt[2];                   /* Two salt values copied from WAL header */
   47792   u32 aCksum[2];                  /* Checksum over all prior fields */
   47793 };
   47794 
   47795 /*
   47796 ** A copy of the following object occurs in the wal-index immediately
   47797 ** following the second copy of the WalIndexHdr.  This object stores
   47798 ** information used by checkpoint.
   47799 **
   47800 ** nBackfill is the number of frames in the WAL that have been written
   47801 ** back into the database. (We call the act of moving content from WAL to
   47802 ** database "backfilling".)  The nBackfill number is never greater than
   47803 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
   47804 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
   47805 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
   47806 ** mxFrame back to zero when the WAL is reset.
   47807 **
   47808 ** There is one entry in aReadMark[] for each reader lock.  If a reader
   47809 ** holds read-lock K, then the value in aReadMark[K] is no greater than
   47810 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
   47811 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
   47812 ** a special case; its value is never used and it exists as a place-holder
   47813 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
   47814 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
   47815 ** directly from the database.
   47816 **
   47817 ** The value of aReadMark[K] may only be changed by a thread that
   47818 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
   47819 ** aReadMark[K] cannot changed while there is a reader is using that mark
   47820 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
   47821 **
   47822 ** The checkpointer may only transfer frames from WAL to database where
   47823 ** the frame numbers are less than or equal to every aReadMark[] that is
   47824 ** in use (that is, every aReadMark[j] for which there is a corresponding
   47825 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
   47826 ** largest value and will increase an unused aReadMark[] to mxFrame if there
   47827 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
   47828 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
   47829 ** in the WAL has been backfilled into the database) then new readers
   47830 ** will choose aReadMark[0] which has value 0 and hence such reader will
   47831 ** get all their all content directly from the database file and ignore
   47832 ** the WAL.
   47833 **
   47834 ** Writers normally append new frames to the end of the WAL.  However,
   47835 ** if nBackfill equals mxFrame (meaning that all WAL content has been
   47836 ** written back into the database) and if no readers are using the WAL
   47837 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
   47838 ** the writer will first "reset" the WAL back to the beginning and start
   47839 ** writing new content beginning at frame 1.
   47840 **
   47841 ** We assume that 32-bit loads are atomic and so no locks are needed in
   47842 ** order to read from any aReadMark[] entries.
   47843 */
   47844 struct WalCkptInfo {
   47845   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
   47846   u32 aReadMark[WAL_NREADER];     /* Reader marks */
   47847 };
   47848 #define READMARK_NOT_USED  0xffffffff
   47849 
   47850 
   47851 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
   47852 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
   47853 ** only support mandatory file-locks, we do not read or write data
   47854 ** from the region of the file on which locks are applied.
   47855 */
   47856 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
   47857 #define WALINDEX_LOCK_RESERVED 16
   47858 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
   47859 
   47860 /* Size of header before each frame in wal */
   47861 #define WAL_FRAME_HDRSIZE 24
   47862 
   47863 /* Size of write ahead log header, including checksum. */
   47864 /* #define WAL_HDRSIZE 24 */
   47865 #define WAL_HDRSIZE 32
   47866 
   47867 /* WAL magic value. Either this value, or the same value with the least
   47868 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
   47869 ** big-endian format in the first 4 bytes of a WAL file.
   47870 **
   47871 ** If the LSB is set, then the checksums for each frame within the WAL
   47872 ** file are calculated by treating all data as an array of 32-bit
   47873 ** big-endian words. Otherwise, they are calculated by interpreting
   47874 ** all data as 32-bit little-endian words.
   47875 */
   47876 #define WAL_MAGIC 0x377f0682
   47877 
   47878 /*
   47879 ** Return the offset of frame iFrame in the write-ahead log file,
   47880 ** assuming a database page size of szPage bytes. The offset returned
   47881 ** is to the start of the write-ahead log frame-header.
   47882 */
   47883 #define walFrameOffset(iFrame, szPage) (                               \
   47884   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
   47885 )
   47886 
   47887 /*
   47888 ** An open write-ahead log file is represented by an instance of the
   47889 ** following object.
   47890 */
   47891 struct Wal {
   47892   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
   47893   sqlite3_file *pDbFd;       /* File handle for the database file */
   47894   sqlite3_file *pWalFd;      /* File handle for WAL file */
   47895   u32 iCallback;             /* Value to pass to log callback (or 0) */
   47896   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
   47897   int nWiData;               /* Size of array apWiData */
   47898   int szFirstBlock;          /* Size of first block written to WAL file */
   47899   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
   47900   u32 szPage;                /* Database page size */
   47901   i16 readLock;              /* Which read lock is being held.  -1 for none */
   47902   u8 syncFlags;              /* Flags to use to sync header writes */
   47903   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
   47904   u8 writeLock;              /* True if in a write transaction */
   47905   u8 ckptLock;               /* True if holding a checkpoint lock */
   47906   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
   47907   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
   47908   u8 syncHeader;             /* Fsync the WAL header if true */
   47909   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
   47910   WalIndexHdr hdr;           /* Wal-index header for current transaction */
   47911   const char *zWalName;      /* Name of WAL file */
   47912   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
   47913 #ifdef SQLITE_DEBUG
   47914   u8 lockError;              /* True if a locking error has occurred */
   47915 #endif
   47916 };
   47917 
   47918 /*
   47919 ** Candidate values for Wal.exclusiveMode.
   47920 */
   47921 #define WAL_NORMAL_MODE     0
   47922 #define WAL_EXCLUSIVE_MODE  1
   47923 #define WAL_HEAPMEMORY_MODE 2
   47924 
   47925 /*
   47926 ** Possible values for WAL.readOnly
   47927 */
   47928 #define WAL_RDWR        0    /* Normal read/write connection */
   47929 #define WAL_RDONLY      1    /* The WAL file is readonly */
   47930 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
   47931 
   47932 /*
   47933 ** Each page of the wal-index mapping contains a hash-table made up of
   47934 ** an array of HASHTABLE_NSLOT elements of the following type.
   47935 */
   47936 typedef u16 ht_slot;
   47937 
   47938 /*
   47939 ** This structure is used to implement an iterator that loops through
   47940 ** all frames in the WAL in database page order. Where two or more frames
   47941 ** correspond to the same database page, the iterator visits only the
   47942 ** frame most recently written to the WAL (in other words, the frame with
   47943 ** the largest index).
   47944 **
   47945 ** The internals of this structure are only accessed by:
   47946 **
   47947 **   walIteratorInit() - Create a new iterator,
   47948 **   walIteratorNext() - Step an iterator,
   47949 **   walIteratorFree() - Free an iterator.
   47950 **
   47951 ** This functionality is used by the checkpoint code (see walCheckpoint()).
   47952 */
   47953 struct WalIterator {
   47954   int iPrior;                     /* Last result returned from the iterator */
   47955   int nSegment;                   /* Number of entries in aSegment[] */
   47956   struct WalSegment {
   47957     int iNext;                    /* Next slot in aIndex[] not yet returned */
   47958     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
   47959     u32 *aPgno;                   /* Array of page numbers. */
   47960     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
   47961     int iZero;                    /* Frame number associated with aPgno[0] */
   47962   } aSegment[1];                  /* One for every 32KB page in the wal-index */
   47963 };
   47964 
   47965 /*
   47966 ** Define the parameters of the hash tables in the wal-index file. There
   47967 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
   47968 ** wal-index.
   47969 **
   47970 ** Changing any of these constants will alter the wal-index format and
   47971 ** create incompatibilities.
   47972 */
   47973 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
   47974 #define HASHTABLE_HASH_1     383                  /* Should be prime */
   47975 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
   47976 
   47977 /*
   47978 ** The block of page numbers associated with the first hash-table in a
   47979 ** wal-index is smaller than usual. This is so that there is a complete
   47980 ** hash-table on each aligned 32KB page of the wal-index.
   47981 */
   47982 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
   47983 
   47984 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
   47985 #define WALINDEX_PGSZ   (                                         \
   47986     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
   47987 )
   47988 
   47989 /*
   47990 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
   47991 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
   47992 ** numbered from zero.
   47993 **
   47994 ** If this call is successful, *ppPage is set to point to the wal-index
   47995 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
   47996 ** then an SQLite error code is returned and *ppPage is set to 0.
   47997 */
   47998 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
   47999   int rc = SQLITE_OK;
   48000 
   48001   /* Enlarge the pWal->apWiData[] array if required */
   48002   if( pWal->nWiData<=iPage ){
   48003     int nByte = sizeof(u32*)*(iPage+1);
   48004     volatile u32 **apNew;
   48005     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
   48006     if( !apNew ){
   48007       *ppPage = 0;
   48008       return SQLITE_NOMEM;
   48009     }
   48010     memset((void*)&apNew[pWal->nWiData], 0,
   48011            sizeof(u32*)*(iPage+1-pWal->nWiData));
   48012     pWal->apWiData = apNew;
   48013     pWal->nWiData = iPage+1;
   48014   }
   48015 
   48016   /* Request a pointer to the required page from the VFS */
   48017   if( pWal->apWiData[iPage]==0 ){
   48018     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   48019       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
   48020       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
   48021     }else{
   48022       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
   48023           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
   48024       );
   48025       if( rc==SQLITE_READONLY ){
   48026         pWal->readOnly |= WAL_SHM_RDONLY;
   48027         rc = SQLITE_OK;
   48028       }
   48029     }
   48030   }
   48031 
   48032   *ppPage = pWal->apWiData[iPage];
   48033   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
   48034   return rc;
   48035 }
   48036 
   48037 /*
   48038 ** Return a pointer to the WalCkptInfo structure in the wal-index.
   48039 */
   48040 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
   48041   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   48042   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
   48043 }
   48044 
   48045 /*
   48046 ** Return a pointer to the WalIndexHdr structure in the wal-index.
   48047 */
   48048 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
   48049   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   48050   return (volatile WalIndexHdr*)pWal->apWiData[0];
   48051 }
   48052 
   48053 /*
   48054 ** The argument to this macro must be of type u32. On a little-endian
   48055 ** architecture, it returns the u32 value that results from interpreting
   48056 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
   48057 ** returns the value that would be produced by intepreting the 4 bytes
   48058 ** of the input value as a little-endian integer.
   48059 */
   48060 #define BYTESWAP32(x) ( \
   48061     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
   48062   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
   48063 )
   48064 
   48065 /*
   48066 ** Generate or extend an 8 byte checksum based on the data in
   48067 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
   48068 ** initial values of 0 and 0 if aIn==NULL).
   48069 **
   48070 ** The checksum is written back into aOut[] before returning.
   48071 **
   48072 ** nByte must be a positive multiple of 8.
   48073 */
   48074 static void walChecksumBytes(
   48075   int nativeCksum, /* True for native byte-order, false for non-native */
   48076   u8 *a,           /* Content to be checksummed */
   48077   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
   48078   const u32 *aIn,  /* Initial checksum value input */
   48079   u32 *aOut        /* OUT: Final checksum value output */
   48080 ){
   48081   u32 s1, s2;
   48082   u32 *aData = (u32 *)a;
   48083   u32 *aEnd = (u32 *)&a[nByte];
   48084 
   48085   if( aIn ){
   48086     s1 = aIn[0];
   48087     s2 = aIn[1];
   48088   }else{
   48089     s1 = s2 = 0;
   48090   }
   48091 
   48092   assert( nByte>=8 );
   48093   assert( (nByte&0x00000007)==0 );
   48094 
   48095   if( nativeCksum ){
   48096     do {
   48097       s1 += *aData++ + s2;
   48098       s2 += *aData++ + s1;
   48099     }while( aData<aEnd );
   48100   }else{
   48101     do {
   48102       s1 += BYTESWAP32(aData[0]) + s2;
   48103       s2 += BYTESWAP32(aData[1]) + s1;
   48104       aData += 2;
   48105     }while( aData<aEnd );
   48106   }
   48107 
   48108   aOut[0] = s1;
   48109   aOut[1] = s2;
   48110 }
   48111 
   48112 static void walShmBarrier(Wal *pWal){
   48113   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
   48114     sqlite3OsShmBarrier(pWal->pDbFd);
   48115   }
   48116 }
   48117 
   48118 /*
   48119 ** Write the header information in pWal->hdr into the wal-index.
   48120 **
   48121 ** The checksum on pWal->hdr is updated before it is written.
   48122 */
   48123 static void walIndexWriteHdr(Wal *pWal){
   48124   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
   48125   const int nCksum = offsetof(WalIndexHdr, aCksum);
   48126 
   48127   assert( pWal->writeLock );
   48128   pWal->hdr.isInit = 1;
   48129   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
   48130   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
   48131   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   48132   walShmBarrier(pWal);
   48133   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   48134 }
   48135 
   48136 /*
   48137 ** This function encodes a single frame header and writes it to a buffer
   48138 ** supplied by the caller. A frame-header is made up of a series of
   48139 ** 4-byte big-endian integers, as follows:
   48140 **
   48141 **     0: Page number.
   48142 **     4: For commit records, the size of the database image in pages
   48143 **        after the commit. For all other records, zero.
   48144 **     8: Salt-1 (copied from the wal-header)
   48145 **    12: Salt-2 (copied from the wal-header)
   48146 **    16: Checksum-1.
   48147 **    20: Checksum-2.
   48148 */
   48149 static void walEncodeFrame(
   48150   Wal *pWal,                      /* The write-ahead log */
   48151   u32 iPage,                      /* Database page number for frame */
   48152   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
   48153   u8 *aData,                      /* Pointer to page data */
   48154   u8 *aFrame                      /* OUT: Write encoded frame here */
   48155 ){
   48156   int nativeCksum;                /* True for native byte-order checksums */
   48157   u32 *aCksum = pWal->hdr.aFrameCksum;
   48158   assert( WAL_FRAME_HDRSIZE==24 );
   48159   sqlite3Put4byte(&aFrame[0], iPage);
   48160   sqlite3Put4byte(&aFrame[4], nTruncate);
   48161   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
   48162 
   48163   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   48164   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   48165   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   48166 
   48167   sqlite3Put4byte(&aFrame[16], aCksum[0]);
   48168   sqlite3Put4byte(&aFrame[20], aCksum[1]);
   48169 }
   48170 
   48171 /*
   48172 ** Check to see if the frame with header in aFrame[] and content
   48173 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
   48174 ** *pnTruncate and return true.  Return if the frame is not valid.
   48175 */
   48176 static int walDecodeFrame(
   48177   Wal *pWal,                      /* The write-ahead log */
   48178   u32 *piPage,                    /* OUT: Database page number for frame */
   48179   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
   48180   u8 *aData,                      /* Pointer to page data (for checksum) */
   48181   u8 *aFrame                      /* Frame data */
   48182 ){
   48183   int nativeCksum;                /* True for native byte-order checksums */
   48184   u32 *aCksum = pWal->hdr.aFrameCksum;
   48185   u32 pgno;                       /* Page number of the frame */
   48186   assert( WAL_FRAME_HDRSIZE==24 );
   48187 
   48188   /* A frame is only valid if the salt values in the frame-header
   48189   ** match the salt values in the wal-header.
   48190   */
   48191   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
   48192     return 0;
   48193   }
   48194 
   48195   /* A frame is only valid if the page number is creater than zero.
   48196   */
   48197   pgno = sqlite3Get4byte(&aFrame[0]);
   48198   if( pgno==0 ){
   48199     return 0;
   48200   }
   48201 
   48202   /* A frame is only valid if a checksum of the WAL header,
   48203   ** all prior frams, the first 16 bytes of this frame-header,
   48204   ** and the frame-data matches the checksum in the last 8
   48205   ** bytes of this frame-header.
   48206   */
   48207   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   48208   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   48209   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   48210   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
   48211    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
   48212   ){
   48213     /* Checksum failed. */
   48214     return 0;
   48215   }
   48216 
   48217   /* If we reach this point, the frame is valid.  Return the page number
   48218   ** and the new database size.
   48219   */
   48220   *piPage = pgno;
   48221   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
   48222   return 1;
   48223 }
   48224 
   48225 
   48226 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   48227 /*
   48228 ** Names of locks.  This routine is used to provide debugging output and is not
   48229 ** a part of an ordinary build.
   48230 */
   48231 static const char *walLockName(int lockIdx){
   48232   if( lockIdx==WAL_WRITE_LOCK ){
   48233     return "WRITE-LOCK";
   48234   }else if( lockIdx==WAL_CKPT_LOCK ){
   48235     return "CKPT-LOCK";
   48236   }else if( lockIdx==WAL_RECOVER_LOCK ){
   48237     return "RECOVER-LOCK";
   48238   }else{
   48239     static char zName[15];
   48240     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
   48241                      lockIdx-WAL_READ_LOCK(0));
   48242     return zName;
   48243   }
   48244 }
   48245 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
   48246 
   48247 
   48248 /*
   48249 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
   48250 ** A lock cannot be moved directly between shared and exclusive - it must go
   48251 ** through the unlocked state first.
   48252 **
   48253 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
   48254 */
   48255 static int walLockShared(Wal *pWal, int lockIdx){
   48256   int rc;
   48257   if( pWal->exclusiveMode ) return SQLITE_OK;
   48258   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   48259                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
   48260   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
   48261             walLockName(lockIdx), rc ? "failed" : "ok"));
   48262   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   48263   return rc;
   48264 }
   48265 static void walUnlockShared(Wal *pWal, int lockIdx){
   48266   if( pWal->exclusiveMode ) return;
   48267   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   48268                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
   48269   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
   48270 }
   48271 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
   48272   int rc;
   48273   if( pWal->exclusiveMode ) return SQLITE_OK;
   48274   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   48275                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
   48276   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
   48277             walLockName(lockIdx), n, rc ? "failed" : "ok"));
   48278   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   48279   return rc;
   48280 }
   48281 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
   48282   if( pWal->exclusiveMode ) return;
   48283   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   48284                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
   48285   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
   48286              walLockName(lockIdx), n));
   48287 }
   48288 
   48289 /*
   48290 ** Compute a hash on a page number.  The resulting hash value must land
   48291 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
   48292 ** the hash to the next value in the event of a collision.
   48293 */
   48294 static int walHash(u32 iPage){
   48295   assert( iPage>0 );
   48296   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
   48297   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
   48298 }
   48299 static int walNextHash(int iPriorHash){
   48300   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
   48301 }
   48302 
   48303 /*
   48304 ** Return pointers to the hash table and page number array stored on
   48305 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
   48306 ** numbered starting from 0.
   48307 **
   48308 ** Set output variable *paHash to point to the start of the hash table
   48309 ** in the wal-index file. Set *piZero to one less than the frame
   48310 ** number of the first frame indexed by this hash table. If a
   48311 ** slot in the hash table is set to N, it refers to frame number
   48312 ** (*piZero+N) in the log.
   48313 **
   48314 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
   48315 ** first frame indexed by the hash table, frame (*piZero+1).
   48316 */
   48317 static int walHashGet(
   48318   Wal *pWal,                      /* WAL handle */
   48319   int iHash,                      /* Find the iHash'th table */
   48320   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
   48321   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
   48322   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
   48323 ){
   48324   int rc;                         /* Return code */
   48325   volatile u32 *aPgno;
   48326 
   48327   rc = walIndexPage(pWal, iHash, &aPgno);
   48328   assert( rc==SQLITE_OK || iHash>0 );
   48329 
   48330   if( rc==SQLITE_OK ){
   48331     u32 iZero;
   48332     volatile ht_slot *aHash;
   48333 
   48334     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
   48335     if( iHash==0 ){
   48336       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
   48337       iZero = 0;
   48338     }else{
   48339       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
   48340     }
   48341 
   48342     *paPgno = &aPgno[-1];
   48343     *paHash = aHash;
   48344     *piZero = iZero;
   48345   }
   48346   return rc;
   48347 }
   48348 
   48349 /*
   48350 ** Return the number of the wal-index page that contains the hash-table
   48351 ** and page-number array that contain entries corresponding to WAL frame
   48352 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
   48353 ** are numbered starting from 0.
   48354 */
   48355 static int walFramePage(u32 iFrame){
   48356   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
   48357   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
   48358        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
   48359        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
   48360        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
   48361        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
   48362   );
   48363   return iHash;
   48364 }
   48365 
   48366 /*
   48367 ** Return the page number associated with frame iFrame in this WAL.
   48368 */
   48369 static u32 walFramePgno(Wal *pWal, u32 iFrame){
   48370   int iHash = walFramePage(iFrame);
   48371   if( iHash==0 ){
   48372     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
   48373   }
   48374   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
   48375 }
   48376 
   48377 /*
   48378 ** Remove entries from the hash table that point to WAL slots greater
   48379 ** than pWal->hdr.mxFrame.
   48380 **
   48381 ** This function is called whenever pWal->hdr.mxFrame is decreased due
   48382 ** to a rollback or savepoint.
   48383 **
   48384 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
   48385 ** updated.  Any later hash tables will be automatically cleared when
   48386 ** pWal->hdr.mxFrame advances to the point where those hash tables are
   48387 ** actually needed.
   48388 */
   48389 static void walCleanupHash(Wal *pWal){
   48390   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
   48391   volatile u32 *aPgno = 0;        /* Page number array for hash table */
   48392   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
   48393   int iLimit = 0;                 /* Zero values greater than this */
   48394   int nByte;                      /* Number of bytes to zero in aPgno[] */
   48395   int i;                          /* Used to iterate through aHash[] */
   48396 
   48397   assert( pWal->writeLock );
   48398   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
   48399   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
   48400   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
   48401 
   48402   if( pWal->hdr.mxFrame==0 ) return;
   48403 
   48404   /* Obtain pointers to the hash-table and page-number array containing
   48405   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
   48406   ** that the page said hash-table and array reside on is already mapped.
   48407   */
   48408   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
   48409   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
   48410   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
   48411 
   48412   /* Zero all hash-table entries that correspond to frame numbers greater
   48413   ** than pWal->hdr.mxFrame.
   48414   */
   48415   iLimit = pWal->hdr.mxFrame - iZero;
   48416   assert( iLimit>0 );
   48417   for(i=0; i<HASHTABLE_NSLOT; i++){
   48418     if( aHash[i]>iLimit ){
   48419       aHash[i] = 0;
   48420     }
   48421   }
   48422 
   48423   /* Zero the entries in the aPgno array that correspond to frames with
   48424   ** frame numbers greater than pWal->hdr.mxFrame.
   48425   */
   48426   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
   48427   memset((void *)&aPgno[iLimit+1], 0, nByte);
   48428 
   48429 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   48430   /* Verify that the every entry in the mapping region is still reachable
   48431   ** via the hash table even after the cleanup.
   48432   */
   48433   if( iLimit ){
   48434     int i;           /* Loop counter */
   48435     int iKey;        /* Hash key */
   48436     for(i=1; i<=iLimit; i++){
   48437       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   48438         if( aHash[iKey]==i ) break;
   48439       }
   48440       assert( aHash[iKey]==i );
   48441     }
   48442   }
   48443 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   48444 }
   48445 
   48446 
   48447 /*
   48448 ** Set an entry in the wal-index that will map database page number
   48449 ** pPage into WAL frame iFrame.
   48450 */
   48451 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
   48452   int rc;                         /* Return code */
   48453   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
   48454   volatile u32 *aPgno = 0;        /* Page number array */
   48455   volatile ht_slot *aHash = 0;    /* Hash table */
   48456 
   48457   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
   48458 
   48459   /* Assuming the wal-index file was successfully mapped, populate the
   48460   ** page number array and hash table entry.
   48461   */
   48462   if( rc==SQLITE_OK ){
   48463     int iKey;                     /* Hash table key */
   48464     int idx;                      /* Value to write to hash-table slot */
   48465     int nCollide;                 /* Number of hash collisions */
   48466 
   48467     idx = iFrame - iZero;
   48468     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
   48469 
   48470     /* If this is the first entry to be added to this hash-table, zero the
   48471     ** entire hash table and aPgno[] array before proceding.
   48472     */
   48473     if( idx==1 ){
   48474       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
   48475       memset((void*)&aPgno[1], 0, nByte);
   48476     }
   48477 
   48478     /* If the entry in aPgno[] is already set, then the previous writer
   48479     ** must have exited unexpectedly in the middle of a transaction (after
   48480     ** writing one or more dirty pages to the WAL to free up memory).
   48481     ** Remove the remnants of that writers uncommitted transaction from
   48482     ** the hash-table before writing any new entries.
   48483     */
   48484     if( aPgno[idx] ){
   48485       walCleanupHash(pWal);
   48486       assert( !aPgno[idx] );
   48487     }
   48488 
   48489     /* Write the aPgno[] array entry and the hash-table slot. */
   48490     nCollide = idx;
   48491     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
   48492       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
   48493     }
   48494     aPgno[idx] = iPage;
   48495     aHash[iKey] = (ht_slot)idx;
   48496 
   48497 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   48498     /* Verify that the number of entries in the hash table exactly equals
   48499     ** the number of entries in the mapping region.
   48500     */
   48501     {
   48502       int i;           /* Loop counter */
   48503       int nEntry = 0;  /* Number of entries in the hash table */
   48504       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
   48505       assert( nEntry==idx );
   48506     }
   48507 
   48508     /* Verify that the every entry in the mapping region is reachable
   48509     ** via the hash table.  This turns out to be a really, really expensive
   48510     ** thing to check, so only do this occasionally - not on every
   48511     ** iteration.
   48512     */
   48513     if( (idx&0x3ff)==0 ){
   48514       int i;           /* Loop counter */
   48515       for(i=1; i<=idx; i++){
   48516         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   48517           if( aHash[iKey]==i ) break;
   48518         }
   48519         assert( aHash[iKey]==i );
   48520       }
   48521     }
   48522 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   48523   }
   48524 
   48525 
   48526   return rc;
   48527 }
   48528 
   48529 
   48530 /*
   48531 ** Recover the wal-index by reading the write-ahead log file.
   48532 **
   48533 ** This routine first tries to establish an exclusive lock on the
   48534 ** wal-index to prevent other threads/processes from doing anything
   48535 ** with the WAL or wal-index while recovery is running.  The
   48536 ** WAL_RECOVER_LOCK is also held so that other threads will know
   48537 ** that this thread is running recovery.  If unable to establish
   48538 ** the necessary locks, this routine returns SQLITE_BUSY.
   48539 */
   48540 static int walIndexRecover(Wal *pWal){
   48541   int rc;                         /* Return Code */
   48542   i64 nSize;                      /* Size of log file */
   48543   u32 aFrameCksum[2] = {0, 0};
   48544   int iLock;                      /* Lock offset to lock for checkpoint */
   48545   int nLock;                      /* Number of locks to hold */
   48546 
   48547   /* Obtain an exclusive lock on all byte in the locking range not already
   48548   ** locked by the caller. The caller is guaranteed to have locked the
   48549   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
   48550   ** If successful, the same bytes that are locked here are unlocked before
   48551   ** this function returns.
   48552   */
   48553   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
   48554   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
   48555   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
   48556   assert( pWal->writeLock );
   48557   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
   48558   nLock = SQLITE_SHM_NLOCK - iLock;
   48559   rc = walLockExclusive(pWal, iLock, nLock);
   48560   if( rc ){
   48561     return rc;
   48562   }
   48563   WALTRACE(("WAL%p: recovery begin...\n", pWal));
   48564 
   48565   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   48566 
   48567   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
   48568   if( rc!=SQLITE_OK ){
   48569     goto recovery_error;
   48570   }
   48571 
   48572   if( nSize>WAL_HDRSIZE ){
   48573     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
   48574     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
   48575     int szFrame;                  /* Number of bytes in buffer aFrame[] */
   48576     u8 *aData;                    /* Pointer to data part of aFrame buffer */
   48577     int iFrame;                   /* Index of last frame read */
   48578     i64 iOffset;                  /* Next offset to read from log file */
   48579     int szPage;                   /* Page size according to the log */
   48580     u32 magic;                    /* Magic value read from WAL header */
   48581     u32 version;                  /* Magic value read from WAL header */
   48582     int isValid;                  /* True if this frame is valid */
   48583 
   48584     /* Read in the WAL header. */
   48585     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
   48586     if( rc!=SQLITE_OK ){
   48587       goto recovery_error;
   48588     }
   48589 
   48590     /* If the database page size is not a power of two, or is greater than
   48591     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
   48592     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
   48593     ** WAL file.
   48594     */
   48595     magic = sqlite3Get4byte(&aBuf[0]);
   48596     szPage = sqlite3Get4byte(&aBuf[8]);
   48597     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
   48598      || szPage&(szPage-1)
   48599      || szPage>SQLITE_MAX_PAGE_SIZE
   48600      || szPage<512
   48601     ){
   48602       goto finished;
   48603     }
   48604     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
   48605     pWal->szPage = szPage;
   48606     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
   48607     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
   48608 
   48609     /* Verify that the WAL header checksum is correct */
   48610     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
   48611         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
   48612     );
   48613     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
   48614      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
   48615     ){
   48616       goto finished;
   48617     }
   48618 
   48619     /* Verify that the version number on the WAL format is one that
   48620     ** are able to understand */
   48621     version = sqlite3Get4byte(&aBuf[4]);
   48622     if( version!=WAL_MAX_VERSION ){
   48623       rc = SQLITE_CANTOPEN_BKPT;
   48624       goto finished;
   48625     }
   48626 
   48627     /* Malloc a buffer to read frames into. */
   48628     szFrame = szPage + WAL_FRAME_HDRSIZE;
   48629     aFrame = (u8 *)sqlite3_malloc(szFrame);
   48630     if( !aFrame ){
   48631       rc = SQLITE_NOMEM;
   48632       goto recovery_error;
   48633     }
   48634     aData = &aFrame[WAL_FRAME_HDRSIZE];
   48635 
   48636     /* Read all frames from the log file. */
   48637     iFrame = 0;
   48638     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
   48639       u32 pgno;                   /* Database page number for frame */
   48640       u32 nTruncate;              /* dbsize field from frame header */
   48641 
   48642       /* Read and decode the next log frame. */
   48643       iFrame++;
   48644       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
   48645       if( rc!=SQLITE_OK ) break;
   48646       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
   48647       if( !isValid ) break;
   48648       rc = walIndexAppend(pWal, iFrame, pgno);
   48649       if( rc!=SQLITE_OK ) break;
   48650 
   48651       /* If nTruncate is non-zero, this is a commit record. */
   48652       if( nTruncate ){
   48653         pWal->hdr.mxFrame = iFrame;
   48654         pWal->hdr.nPage = nTruncate;
   48655         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   48656         testcase( szPage<=32768 );
   48657         testcase( szPage>=65536 );
   48658         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
   48659         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
   48660       }
   48661     }
   48662 
   48663     sqlite3_free(aFrame);
   48664   }
   48665 
   48666 finished:
   48667   if( rc==SQLITE_OK ){
   48668     volatile WalCkptInfo *pInfo;
   48669     int i;
   48670     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
   48671     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
   48672     walIndexWriteHdr(pWal);
   48673 
   48674     /* Reset the checkpoint-header. This is safe because this thread is
   48675     ** currently holding locks that exclude all other readers, writers and
   48676     ** checkpointers.
   48677     */
   48678     pInfo = walCkptInfo(pWal);
   48679     pInfo->nBackfill = 0;
   48680     pInfo->aReadMark[0] = 0;
   48681     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   48682     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
   48683 
   48684     /* If more than one frame was recovered from the log file, report an
   48685     ** event via sqlite3_log(). This is to help with identifying performance
   48686     ** problems caused by applications routinely shutting down without
   48687     ** checkpointing the log file.
   48688     */
   48689     if( pWal->hdr.nPage ){
   48690       sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
   48691           "recovered %d frames from WAL file %s",
   48692           pWal->hdr.mxFrame, pWal->zWalName
   48693       );
   48694     }
   48695   }
   48696 
   48697 recovery_error:
   48698   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
   48699   walUnlockExclusive(pWal, iLock, nLock);
   48700   return rc;
   48701 }
   48702 
   48703 /*
   48704 ** Close an open wal-index.
   48705 */
   48706 static void walIndexClose(Wal *pWal, int isDelete){
   48707   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   48708     int i;
   48709     for(i=0; i<pWal->nWiData; i++){
   48710       sqlite3_free((void *)pWal->apWiData[i]);
   48711       pWal->apWiData[i] = 0;
   48712     }
   48713   }else{
   48714     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
   48715   }
   48716 }
   48717 
   48718 /*
   48719 ** Open a connection to the WAL file zWalName. The database file must
   48720 ** already be opened on connection pDbFd. The buffer that zWalName points
   48721 ** to must remain valid for the lifetime of the returned Wal* handle.
   48722 **
   48723 ** A SHARED lock should be held on the database file when this function
   48724 ** is called. The purpose of this SHARED lock is to prevent any other
   48725 ** client from unlinking the WAL or wal-index file. If another process
   48726 ** were to do this just after this client opened one of these files, the
   48727 ** system would be badly broken.
   48728 **
   48729 ** If the log file is successfully opened, SQLITE_OK is returned and
   48730 ** *ppWal is set to point to a new WAL handle. If an error occurs,
   48731 ** an SQLite error code is returned and *ppWal is left unmodified.
   48732 */
   48733 SQLITE_PRIVATE int sqlite3WalOpen(
   48734   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
   48735   sqlite3_file *pDbFd,            /* The open database file */
   48736   const char *zWalName,           /* Name of the WAL file */
   48737   int bNoShm,                     /* True to run in heap-memory mode */
   48738   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
   48739   Wal **ppWal                     /* OUT: Allocated Wal handle */
   48740 ){
   48741   int rc;                         /* Return Code */
   48742   Wal *pRet;                      /* Object to allocate and return */
   48743   int flags;                      /* Flags passed to OsOpen() */
   48744 
   48745   assert( zWalName && zWalName[0] );
   48746   assert( pDbFd );
   48747 
   48748   /* In the amalgamation, the os_unix.c and os_win.c source files come before
   48749   ** this source file.  Verify that the #defines of the locking byte offsets
   48750   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
   48751   */
   48752 #ifdef WIN_SHM_BASE
   48753   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
   48754 #endif
   48755 #ifdef UNIX_SHM_BASE
   48756   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
   48757 #endif
   48758 
   48759 
   48760   /* Allocate an instance of struct Wal to return. */
   48761   *ppWal = 0;
   48762   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
   48763   if( !pRet ){
   48764     return SQLITE_NOMEM;
   48765   }
   48766 
   48767   pRet->pVfs = pVfs;
   48768   pRet->pWalFd = (sqlite3_file *)&pRet[1];
   48769   pRet->pDbFd = pDbFd;
   48770   pRet->readLock = -1;
   48771   pRet->mxWalSize = mxWalSize;
   48772   pRet->zWalName = zWalName;
   48773   pRet->syncHeader = 1;
   48774   pRet->padToSectorBoundary = 1;
   48775   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
   48776 
   48777   /* Open file handle on the write-ahead log file. */
   48778   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
   48779   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
   48780   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
   48781     pRet->readOnly = WAL_RDONLY;
   48782   }
   48783 
   48784   if( rc!=SQLITE_OK ){
   48785     walIndexClose(pRet, 0);
   48786     sqlite3OsClose(pRet->pWalFd);
   48787     sqlite3_free(pRet);
   48788   }else{
   48789     int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
   48790     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
   48791     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
   48792       pRet->padToSectorBoundary = 0;
   48793     }
   48794     *ppWal = pRet;
   48795     WALTRACE(("WAL%d: opened\n", pRet));
   48796   }
   48797   return rc;
   48798 }
   48799 
   48800 /*
   48801 ** Change the size to which the WAL file is trucated on each reset.
   48802 */
   48803 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
   48804   if( pWal ) pWal->mxWalSize = iLimit;
   48805 }
   48806 
   48807 /*
   48808 ** Find the smallest page number out of all pages held in the WAL that
   48809 ** has not been returned by any prior invocation of this method on the
   48810 ** same WalIterator object.   Write into *piFrame the frame index where
   48811 ** that page was last written into the WAL.  Write into *piPage the page
   48812 ** number.
   48813 **
   48814 ** Return 0 on success.  If there are no pages in the WAL with a page
   48815 ** number larger than *piPage, then return 1.
   48816 */
   48817 static int walIteratorNext(
   48818   WalIterator *p,               /* Iterator */
   48819   u32 *piPage,                  /* OUT: The page number of the next page */
   48820   u32 *piFrame                  /* OUT: Wal frame index of next page */
   48821 ){
   48822   u32 iMin;                     /* Result pgno must be greater than iMin */
   48823   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
   48824   int i;                        /* For looping through segments */
   48825 
   48826   iMin = p->iPrior;
   48827   assert( iMin<0xffffffff );
   48828   for(i=p->nSegment-1; i>=0; i--){
   48829     struct WalSegment *pSegment = &p->aSegment[i];
   48830     while( pSegment->iNext<pSegment->nEntry ){
   48831       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
   48832       if( iPg>iMin ){
   48833         if( iPg<iRet ){
   48834           iRet = iPg;
   48835           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
   48836         }
   48837         break;
   48838       }
   48839       pSegment->iNext++;
   48840     }
   48841   }
   48842 
   48843   *piPage = p->iPrior = iRet;
   48844   return (iRet==0xFFFFFFFF);
   48845 }
   48846 
   48847 /*
   48848 ** This function merges two sorted lists into a single sorted list.
   48849 **
   48850 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
   48851 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
   48852 ** is guaranteed for all J<K:
   48853 **
   48854 **        aContent[aLeft[J]] < aContent[aLeft[K]]
   48855 **        aContent[aRight[J]] < aContent[aRight[K]]
   48856 **
   48857 ** This routine overwrites aRight[] with a new (probably longer) sequence
   48858 ** of indices such that the aRight[] contains every index that appears in
   48859 ** either aLeft[] or the old aRight[] and such that the second condition
   48860 ** above is still met.
   48861 **
   48862 ** The aContent[aLeft[X]] values will be unique for all X.  And the
   48863 ** aContent[aRight[X]] values will be unique too.  But there might be
   48864 ** one or more combinations of X and Y such that
   48865 **
   48866 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
   48867 **
   48868 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
   48869 */
   48870 static void walMerge(
   48871   const u32 *aContent,            /* Pages in wal - keys for the sort */
   48872   ht_slot *aLeft,                 /* IN: Left hand input list */
   48873   int nLeft,                      /* IN: Elements in array *paLeft */
   48874   ht_slot **paRight,              /* IN/OUT: Right hand input list */
   48875   int *pnRight,                   /* IN/OUT: Elements in *paRight */
   48876   ht_slot *aTmp                   /* Temporary buffer */
   48877 ){
   48878   int iLeft = 0;                  /* Current index in aLeft */
   48879   int iRight = 0;                 /* Current index in aRight */
   48880   int iOut = 0;                   /* Current index in output buffer */
   48881   int nRight = *pnRight;
   48882   ht_slot *aRight = *paRight;
   48883 
   48884   assert( nLeft>0 && nRight>0 );
   48885   while( iRight<nRight || iLeft<nLeft ){
   48886     ht_slot logpage;
   48887     Pgno dbpage;
   48888 
   48889     if( (iLeft<nLeft)
   48890      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
   48891     ){
   48892       logpage = aLeft[iLeft++];
   48893     }else{
   48894       logpage = aRight[iRight++];
   48895     }
   48896     dbpage = aContent[logpage];
   48897 
   48898     aTmp[iOut++] = logpage;
   48899     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
   48900 
   48901     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
   48902     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
   48903   }
   48904 
   48905   *paRight = aLeft;
   48906   *pnRight = iOut;
   48907   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
   48908 }
   48909 
   48910 /*
   48911 ** Sort the elements in list aList using aContent[] as the sort key.
   48912 ** Remove elements with duplicate keys, preferring to keep the
   48913 ** larger aList[] values.
   48914 **
   48915 ** The aList[] entries are indices into aContent[].  The values in
   48916 ** aList[] are to be sorted so that for all J<K:
   48917 **
   48918 **      aContent[aList[J]] < aContent[aList[K]]
   48919 **
   48920 ** For any X and Y such that
   48921 **
   48922 **      aContent[aList[X]] == aContent[aList[Y]]
   48923 **
   48924 ** Keep the larger of the two values aList[X] and aList[Y] and discard
   48925 ** the smaller.
   48926 */
   48927 static void walMergesort(
   48928   const u32 *aContent,            /* Pages in wal */
   48929   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
   48930   ht_slot *aList,                 /* IN/OUT: List to sort */
   48931   int *pnList                     /* IN/OUT: Number of elements in aList[] */
   48932 ){
   48933   struct Sublist {
   48934     int nList;                    /* Number of elements in aList */
   48935     ht_slot *aList;               /* Pointer to sub-list content */
   48936   };
   48937 
   48938   const int nList = *pnList;      /* Size of input list */
   48939   int nMerge = 0;                 /* Number of elements in list aMerge */
   48940   ht_slot *aMerge = 0;            /* List to be merged */
   48941   int iList;                      /* Index into input list */
   48942   int iSub = 0;                   /* Index into aSub array */
   48943   struct Sublist aSub[13];        /* Array of sub-lists */
   48944 
   48945   memset(aSub, 0, sizeof(aSub));
   48946   assert( nList<=HASHTABLE_NPAGE && nList>0 );
   48947   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
   48948 
   48949   for(iList=0; iList<nList; iList++){
   48950     nMerge = 1;
   48951     aMerge = &aList[iList];
   48952     for(iSub=0; iList & (1<<iSub); iSub++){
   48953       struct Sublist *p = &aSub[iSub];
   48954       assert( p->aList && p->nList<=(1<<iSub) );
   48955       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
   48956       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   48957     }
   48958     aSub[iSub].aList = aMerge;
   48959     aSub[iSub].nList = nMerge;
   48960   }
   48961 
   48962   for(iSub++; iSub<ArraySize(aSub); iSub++){
   48963     if( nList & (1<<iSub) ){
   48964       struct Sublist *p = &aSub[iSub];
   48965       assert( p->nList<=(1<<iSub) );
   48966       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
   48967       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   48968     }
   48969   }
   48970   assert( aMerge==aList );
   48971   *pnList = nMerge;
   48972 
   48973 #ifdef SQLITE_DEBUG
   48974   {
   48975     int i;
   48976     for(i=1; i<*pnList; i++){
   48977       assert( aContent[aList[i]] > aContent[aList[i-1]] );
   48978     }
   48979   }
   48980 #endif
   48981 }
   48982 
   48983 /*
   48984 ** Free an iterator allocated by walIteratorInit().
   48985 */
   48986 static void walIteratorFree(WalIterator *p){
   48987   sqlite3ScratchFree(p);
   48988 }
   48989 
   48990 /*
   48991 ** Construct a WalInterator object that can be used to loop over all
   48992 ** pages in the WAL in ascending order. The caller must hold the checkpoint
   48993 ** lock.
   48994 **
   48995 ** On success, make *pp point to the newly allocated WalInterator object
   48996 ** return SQLITE_OK. Otherwise, return an error code. If this routine
   48997 ** returns an error, the value of *pp is undefined.
   48998 **
   48999 ** The calling routine should invoke walIteratorFree() to destroy the
   49000 ** WalIterator object when it has finished with it.
   49001 */
   49002 static int walIteratorInit(Wal *pWal, WalIterator **pp){
   49003   WalIterator *p;                 /* Return value */
   49004   int nSegment;                   /* Number of segments to merge */
   49005   u32 iLast;                      /* Last frame in log */
   49006   int nByte;                      /* Number of bytes to allocate */
   49007   int i;                          /* Iterator variable */
   49008   ht_slot *aTmp;                  /* Temp space used by merge-sort */
   49009   int rc = SQLITE_OK;             /* Return Code */
   49010 
   49011   /* This routine only runs while holding the checkpoint lock. And
   49012   ** it only runs if there is actually content in the log (mxFrame>0).
   49013   */
   49014   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
   49015   iLast = pWal->hdr.mxFrame;
   49016 
   49017   /* Allocate space for the WalIterator object. */
   49018   nSegment = walFramePage(iLast) + 1;
   49019   nByte = sizeof(WalIterator)
   49020         + (nSegment-1)*sizeof(struct WalSegment)
   49021         + iLast*sizeof(ht_slot);
   49022   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
   49023   if( !p ){
   49024     return SQLITE_NOMEM;
   49025   }
   49026   memset(p, 0, nByte);
   49027   p->nSegment = nSegment;
   49028 
   49029   /* Allocate temporary space used by the merge-sort routine. This block
   49030   ** of memory will be freed before this function returns.
   49031   */
   49032   aTmp = (ht_slot *)sqlite3ScratchMalloc(
   49033       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
   49034   );
   49035   if( !aTmp ){
   49036     rc = SQLITE_NOMEM;
   49037   }
   49038 
   49039   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
   49040     volatile ht_slot *aHash;
   49041     u32 iZero;
   49042     volatile u32 *aPgno;
   49043 
   49044     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
   49045     if( rc==SQLITE_OK ){
   49046       int j;                      /* Counter variable */
   49047       int nEntry;                 /* Number of entries in this segment */
   49048       ht_slot *aIndex;            /* Sorted index for this segment */
   49049 
   49050       aPgno++;
   49051       if( (i+1)==nSegment ){
   49052         nEntry = (int)(iLast - iZero);
   49053       }else{
   49054         nEntry = (int)((u32*)aHash - (u32*)aPgno);
   49055       }
   49056       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
   49057       iZero++;
   49058 
   49059       for(j=0; j<nEntry; j++){
   49060         aIndex[j] = (ht_slot)j;
   49061       }
   49062       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
   49063       p->aSegment[i].iZero = iZero;
   49064       p->aSegment[i].nEntry = nEntry;
   49065       p->aSegment[i].aIndex = aIndex;
   49066       p->aSegment[i].aPgno = (u32 *)aPgno;
   49067     }
   49068   }
   49069   sqlite3ScratchFree(aTmp);
   49070 
   49071   if( rc!=SQLITE_OK ){
   49072     walIteratorFree(p);
   49073   }
   49074   *pp = p;
   49075   return rc;
   49076 }
   49077 
   49078 /*
   49079 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
   49080 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
   49081 ** busy-handler function. Invoke it and retry the lock until either the
   49082 ** lock is successfully obtained or the busy-handler returns 0.
   49083 */
   49084 static int walBusyLock(
   49085   Wal *pWal,                      /* WAL connection */
   49086   int (*xBusy)(void*),            /* Function to call when busy */
   49087   void *pBusyArg,                 /* Context argument for xBusyHandler */
   49088   int lockIdx,                    /* Offset of first byte to lock */
   49089   int n                           /* Number of bytes to lock */
   49090 ){
   49091   int rc;
   49092   do {
   49093     rc = walLockExclusive(pWal, lockIdx, n);
   49094   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
   49095   return rc;
   49096 }
   49097 
   49098 /*
   49099 ** The cache of the wal-index header must be valid to call this function.
   49100 ** Return the page-size in bytes used by the database.
   49101 */
   49102 static int walPagesize(Wal *pWal){
   49103   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   49104 }
   49105 
   49106 /*
   49107 ** Copy as much content as we can from the WAL back into the database file
   49108 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
   49109 **
   49110 ** The amount of information copies from WAL to database might be limited
   49111 ** by active readers.  This routine will never overwrite a database page
   49112 ** that a concurrent reader might be using.
   49113 **
   49114 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
   49115 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
   49116 ** checkpoints are always run by a background thread or background
   49117 ** process, foreground threads will never block on a lengthy fsync call.
   49118 **
   49119 ** Fsync is called on the WAL before writing content out of the WAL and
   49120 ** into the database.  This ensures that if the new content is persistent
   49121 ** in the WAL and can be recovered following a power-loss or hard reset.
   49122 **
   49123 ** Fsync is also called on the database file if (and only if) the entire
   49124 ** WAL content is copied into the database file.  This second fsync makes
   49125 ** it safe to delete the WAL since the new content will persist in the
   49126 ** database file.
   49127 **
   49128 ** This routine uses and updates the nBackfill field of the wal-index header.
   49129 ** This is the only routine tha will increase the value of nBackfill.
   49130 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
   49131 ** its value.)
   49132 **
   49133 ** The caller must be holding sufficient locks to ensure that no other
   49134 ** checkpoint is running (in any other thread or process) at the same
   49135 ** time.
   49136 */
   49137 static int walCheckpoint(
   49138   Wal *pWal,                      /* Wal connection */
   49139   int eMode,                      /* One of PASSIVE, FULL or RESTART */
   49140   int (*xBusyCall)(void*),        /* Function to call when busy */
   49141   void *pBusyArg,                 /* Context argument for xBusyHandler */
   49142   int sync_flags,                 /* Flags for OsSync() (or 0) */
   49143   u8 *zBuf                        /* Temporary buffer to use */
   49144 ){
   49145   int rc;                         /* Return code */
   49146   int szPage;                     /* Database page-size */
   49147   WalIterator *pIter = 0;         /* Wal iterator context */
   49148   u32 iDbpage = 0;                /* Next database page to write */
   49149   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
   49150   u32 mxSafeFrame;                /* Max frame that can be backfilled */
   49151   u32 mxPage;                     /* Max database page to write */
   49152   int i;                          /* Loop counter */
   49153   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
   49154   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
   49155 
   49156   szPage = walPagesize(pWal);
   49157   testcase( szPage<=32768 );
   49158   testcase( szPage>=65536 );
   49159   pInfo = walCkptInfo(pWal);
   49160   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
   49161 
   49162   /* Allocate the iterator */
   49163   rc = walIteratorInit(pWal, &pIter);
   49164   if( rc!=SQLITE_OK ){
   49165     return rc;
   49166   }
   49167   assert( pIter );
   49168 
   49169   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
   49170 
   49171   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
   49172   ** safe to write into the database.  Frames beyond mxSafeFrame might
   49173   ** overwrite database pages that are in use by active readers and thus
   49174   ** cannot be backfilled from the WAL.
   49175   */
   49176   mxSafeFrame = pWal->hdr.mxFrame;
   49177   mxPage = pWal->hdr.nPage;
   49178   for(i=1; i<WAL_NREADER; i++){
   49179     u32 y = pInfo->aReadMark[i];
   49180     if( mxSafeFrame>y ){
   49181       assert( y<=pWal->hdr.mxFrame );
   49182       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
   49183       if( rc==SQLITE_OK ){
   49184         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
   49185         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   49186       }else if( rc==SQLITE_BUSY ){
   49187         mxSafeFrame = y;
   49188         xBusy = 0;
   49189       }else{
   49190         goto walcheckpoint_out;
   49191       }
   49192     }
   49193   }
   49194 
   49195   if( pInfo->nBackfill<mxSafeFrame
   49196    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
   49197   ){
   49198     i64 nSize;                    /* Current size of database file */
   49199     u32 nBackfill = pInfo->nBackfill;
   49200 
   49201     /* Sync the WAL to disk */
   49202     if( sync_flags ){
   49203       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
   49204     }
   49205 
   49206     /* If the database may grow as a result of this checkpoint, hint
   49207     ** about the eventual size of the db file to the VFS layer.
   49208     */
   49209     if( rc==SQLITE_OK ){
   49210       i64 nReq = ((i64)mxPage * szPage);
   49211       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
   49212       if( rc==SQLITE_OK && nSize<nReq ){
   49213         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
   49214       }
   49215     }
   49216 
   49217 
   49218     /* Iterate through the contents of the WAL, copying data to the db file. */
   49219     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
   49220       i64 iOffset;
   49221       assert( walFramePgno(pWal, iFrame)==iDbpage );
   49222       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
   49223       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
   49224       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
   49225       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
   49226       if( rc!=SQLITE_OK ) break;
   49227       iOffset = (iDbpage-1)*(i64)szPage;
   49228       testcase( IS_BIG_INT(iOffset) );
   49229       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
   49230       if( rc!=SQLITE_OK ) break;
   49231     }
   49232 
   49233     /* If work was actually accomplished... */
   49234     if( rc==SQLITE_OK ){
   49235       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
   49236         i64 szDb = pWal->hdr.nPage*(i64)szPage;
   49237         testcase( IS_BIG_INT(szDb) );
   49238         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
   49239         if( rc==SQLITE_OK && sync_flags ){
   49240           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
   49241         }
   49242       }
   49243       if( rc==SQLITE_OK ){
   49244         pInfo->nBackfill = mxSafeFrame;
   49245       }
   49246     }
   49247 
   49248     /* Release the reader lock held while backfilling */
   49249     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
   49250   }
   49251 
   49252   if( rc==SQLITE_BUSY ){
   49253     /* Reset the return code so as not to report a checkpoint failure
   49254     ** just because there are active readers.  */
   49255     rc = SQLITE_OK;
   49256   }
   49257 
   49258   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
   49259   ** file has been copied into the database file, then block until all
   49260   ** readers have finished using the wal file. This ensures that the next
   49261   ** process to write to the database restarts the wal file.
   49262   */
   49263   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   49264     assert( pWal->writeLock );
   49265     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
   49266       rc = SQLITE_BUSY;
   49267     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
   49268       assert( mxSafeFrame==pWal->hdr.mxFrame );
   49269       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
   49270       if( rc==SQLITE_OK ){
   49271         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   49272       }
   49273     }
   49274   }
   49275 
   49276  walcheckpoint_out:
   49277   walIteratorFree(pIter);
   49278   return rc;
   49279 }
   49280 
   49281 /*
   49282 ** If the WAL file is currently larger than nMax bytes in size, truncate
   49283 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
   49284 */
   49285 static void walLimitSize(Wal *pWal, i64 nMax){
   49286   i64 sz;
   49287   int rx;
   49288   sqlite3BeginBenignMalloc();
   49289   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
   49290   if( rx==SQLITE_OK && (sz > nMax ) ){
   49291     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
   49292   }
   49293   sqlite3EndBenignMalloc();
   49294   if( rx ){
   49295     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
   49296   }
   49297 }
   49298 
   49299 /*
   49300 ** Close a connection to a log file.
   49301 */
   49302 SQLITE_PRIVATE int sqlite3WalClose(
   49303   Wal *pWal,                      /* Wal to close */
   49304   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
   49305   int nBuf,
   49306   u8 *zBuf                        /* Buffer of at least nBuf bytes */
   49307 ){
   49308   int rc = SQLITE_OK;
   49309   if( pWal ){
   49310     int isDelete = 0;             /* True to unlink wal and wal-index files */
   49311 
   49312     /* If an EXCLUSIVE lock can be obtained on the database file (using the
   49313     ** ordinary, rollback-mode locking methods, this guarantees that the
   49314     ** connection associated with this log file is the only connection to
   49315     ** the database. In this case checkpoint the database and unlink both
   49316     ** the wal and wal-index files.
   49317     **
   49318     ** The EXCLUSIVE lock is not released before returning.
   49319     */
   49320     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
   49321     if( rc==SQLITE_OK ){
   49322       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
   49323         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
   49324       }
   49325       rc = sqlite3WalCheckpoint(
   49326           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
   49327       );
   49328       if( rc==SQLITE_OK ){
   49329         int bPersist = -1;
   49330         sqlite3OsFileControlHint(
   49331             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
   49332         );
   49333         if( bPersist!=1 ){
   49334           /* Try to delete the WAL file if the checkpoint completed and
   49335           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
   49336           ** mode (!bPersist) */
   49337           isDelete = 1;
   49338         }else if( pWal->mxWalSize>=0 ){
   49339           /* Try to truncate the WAL file to zero bytes if the checkpoint
   49340           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
   49341           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
   49342           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
   49343           ** to zero bytes as truncating to the journal_size_limit might
   49344           ** leave a corrupt WAL file on disk. */
   49345           walLimitSize(pWal, 0);
   49346         }
   49347       }
   49348     }
   49349 
   49350     walIndexClose(pWal, isDelete);
   49351     sqlite3OsClose(pWal->pWalFd);
   49352     if( isDelete ){
   49353       sqlite3BeginBenignMalloc();
   49354       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
   49355       sqlite3EndBenignMalloc();
   49356     }
   49357     WALTRACE(("WAL%p: closed\n", pWal));
   49358     sqlite3_free((void *)pWal->apWiData);
   49359     sqlite3_free(pWal);
   49360   }
   49361   return rc;
   49362 }
   49363 
   49364 /*
   49365 ** Try to read the wal-index header.  Return 0 on success and 1 if
   49366 ** there is a problem.
   49367 **
   49368 ** The wal-index is in shared memory.  Another thread or process might
   49369 ** be writing the header at the same time this procedure is trying to
   49370 ** read it, which might result in inconsistency.  A dirty read is detected
   49371 ** by verifying that both copies of the header are the same and also by
   49372 ** a checksum on the header.
   49373 **
   49374 ** If and only if the read is consistent and the header is different from
   49375 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
   49376 ** and *pChanged is set to 1.
   49377 **
   49378 ** If the checksum cannot be verified return non-zero. If the header
   49379 ** is read successfully and the checksum verified, return zero.
   49380 */
   49381 static int walIndexTryHdr(Wal *pWal, int *pChanged){
   49382   u32 aCksum[2];                  /* Checksum on the header content */
   49383   WalIndexHdr h1, h2;             /* Two copies of the header content */
   49384   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
   49385 
   49386   /* The first page of the wal-index must be mapped at this point. */
   49387   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   49388 
   49389   /* Read the header. This might happen concurrently with a write to the
   49390   ** same area of shared memory on a different CPU in a SMP,
   49391   ** meaning it is possible that an inconsistent snapshot is read
   49392   ** from the file. If this happens, return non-zero.
   49393   **
   49394   ** There are two copies of the header at the beginning of the wal-index.
   49395   ** When reading, read [0] first then [1].  Writes are in the reverse order.
   49396   ** Memory barriers are used to prevent the compiler or the hardware from
   49397   ** reordering the reads and writes.
   49398   */
   49399   aHdr = walIndexHdr(pWal);
   49400   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
   49401   walShmBarrier(pWal);
   49402   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
   49403 
   49404   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
   49405     return 1;   /* Dirty read */
   49406   }
   49407   if( h1.isInit==0 ){
   49408     return 1;   /* Malformed header - probably all zeros */
   49409   }
   49410   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
   49411   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
   49412     return 1;   /* Checksum does not match */
   49413   }
   49414 
   49415   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
   49416     *pChanged = 1;
   49417     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
   49418     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   49419     testcase( pWal->szPage<=32768 );
   49420     testcase( pWal->szPage>=65536 );
   49421   }
   49422 
   49423   /* The header was successfully read. Return zero. */
   49424   return 0;
   49425 }
   49426 
   49427 /*
   49428 ** Read the wal-index header from the wal-index and into pWal->hdr.
   49429 ** If the wal-header appears to be corrupt, try to reconstruct the
   49430 ** wal-index from the WAL before returning.
   49431 **
   49432 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
   49433 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
   49434 ** to 0.
   49435 **
   49436 ** If the wal-index header is successfully read, return SQLITE_OK.
   49437 ** Otherwise an SQLite error code.
   49438 */
   49439 static int walIndexReadHdr(Wal *pWal, int *pChanged){
   49440   int rc;                         /* Return code */
   49441   int badHdr;                     /* True if a header read failed */
   49442   volatile u32 *page0;            /* Chunk of wal-index containing header */
   49443 
   49444   /* Ensure that page 0 of the wal-index (the page that contains the
   49445   ** wal-index header) is mapped. Return early if an error occurs here.
   49446   */
   49447   assert( pChanged );
   49448   rc = walIndexPage(pWal, 0, &page0);
   49449   if( rc!=SQLITE_OK ){
   49450     return rc;
   49451   };
   49452   assert( page0 || pWal->writeLock==0 );
   49453 
   49454   /* If the first page of the wal-index has been mapped, try to read the
   49455   ** wal-index header immediately, without holding any lock. This usually
   49456   ** works, but may fail if the wal-index header is corrupt or currently
   49457   ** being modified by another thread or process.
   49458   */
   49459   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
   49460 
   49461   /* If the first attempt failed, it might have been due to a race
   49462   ** with a writer.  So get a WRITE lock and try again.
   49463   */
   49464   assert( badHdr==0 || pWal->writeLock==0 );
   49465   if( badHdr ){
   49466     if( pWal->readOnly & WAL_SHM_RDONLY ){
   49467       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
   49468         walUnlockShared(pWal, WAL_WRITE_LOCK);
   49469         rc = SQLITE_READONLY_RECOVERY;
   49470       }
   49471     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
   49472       pWal->writeLock = 1;
   49473       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
   49474         badHdr = walIndexTryHdr(pWal, pChanged);
   49475         if( badHdr ){
   49476           /* If the wal-index header is still malformed even while holding
   49477           ** a WRITE lock, it can only mean that the header is corrupted and
   49478           ** needs to be reconstructed.  So run recovery to do exactly that.
   49479           */
   49480           rc = walIndexRecover(pWal);
   49481           *pChanged = 1;
   49482         }
   49483       }
   49484       pWal->writeLock = 0;
   49485       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   49486     }
   49487   }
   49488 
   49489   /* If the header is read successfully, check the version number to make
   49490   ** sure the wal-index was not constructed with some future format that
   49491   ** this version of SQLite cannot understand.
   49492   */
   49493   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
   49494     rc = SQLITE_CANTOPEN_BKPT;
   49495   }
   49496 
   49497   return rc;
   49498 }
   49499 
   49500 /*
   49501 ** This is the value that walTryBeginRead returns when it needs to
   49502 ** be retried.
   49503 */
   49504 #define WAL_RETRY  (-1)
   49505 
   49506 /*
   49507 ** Attempt to start a read transaction.  This might fail due to a race or
   49508 ** other transient condition.  When that happens, it returns WAL_RETRY to
   49509 ** indicate to the caller that it is safe to retry immediately.
   49510 **
   49511 ** On success return SQLITE_OK.  On a permanent failure (such an
   49512 ** I/O error or an SQLITE_BUSY because another process is running
   49513 ** recovery) return a positive error code.
   49514 **
   49515 ** The useWal parameter is true to force the use of the WAL and disable
   49516 ** the case where the WAL is bypassed because it has been completely
   49517 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
   49518 ** to make a copy of the wal-index header into pWal->hdr.  If the
   49519 ** wal-index header has changed, *pChanged is set to 1 (as an indication
   49520 ** to the caller that the local paget cache is obsolete and needs to be
   49521 ** flushed.)  When useWal==1, the wal-index header is assumed to already
   49522 ** be loaded and the pChanged parameter is unused.
   49523 **
   49524 ** The caller must set the cnt parameter to the number of prior calls to
   49525 ** this routine during the current read attempt that returned WAL_RETRY.
   49526 ** This routine will start taking more aggressive measures to clear the
   49527 ** race conditions after multiple WAL_RETRY returns, and after an excessive
   49528 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
   49529 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
   49530 ** and is not honoring the locking protocol.  There is a vanishingly small
   49531 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
   49532 ** bad luck when there is lots of contention for the wal-index, but that
   49533 ** possibility is so small that it can be safely neglected, we believe.
   49534 **
   49535 ** On success, this routine obtains a read lock on
   49536 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
   49537 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
   49538 ** that means the Wal does not hold any read lock.  The reader must not
   49539 ** access any database page that is modified by a WAL frame up to and
   49540 ** including frame number aReadMark[pWal->readLock].  The reader will
   49541 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
   49542 ** Or if pWal->readLock==0, then the reader will ignore the WAL
   49543 ** completely and get all content directly from the database file.
   49544 ** If the useWal parameter is 1 then the WAL will never be ignored and
   49545 ** this routine will always set pWal->readLock>0 on success.
   49546 ** When the read transaction is completed, the caller must release the
   49547 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
   49548 **
   49549 ** This routine uses the nBackfill and aReadMark[] fields of the header
   49550 ** to select a particular WAL_READ_LOCK() that strives to let the
   49551 ** checkpoint process do as much work as possible.  This routine might
   49552 ** update values of the aReadMark[] array in the header, but if it does
   49553 ** so it takes care to hold an exclusive lock on the corresponding
   49554 ** WAL_READ_LOCK() while changing values.
   49555 */
   49556 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   49557   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
   49558   u32 mxReadMark;                 /* Largest aReadMark[] value */
   49559   int mxI;                        /* Index of largest aReadMark[] value */
   49560   int i;                          /* Loop counter */
   49561   int rc = SQLITE_OK;             /* Return code  */
   49562 
   49563   assert( pWal->readLock<0 );     /* Not currently locked */
   49564 
   49565   /* Take steps to avoid spinning forever if there is a protocol error.
   49566   **
   49567   ** Circumstances that cause a RETRY should only last for the briefest
   49568   ** instances of time.  No I/O or other system calls are done while the
   49569   ** locks are held, so the locks should not be held for very long. But
   49570   ** if we are unlucky, another process that is holding a lock might get
   49571   ** paged out or take a page-fault that is time-consuming to resolve,
   49572   ** during the few nanoseconds that it is holding the lock.  In that case,
   49573   ** it might take longer than normal for the lock to free.
   49574   **
   49575   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
   49576   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
   49577   ** is more of a scheduler yield than an actual delay.  But on the 10th
   49578   ** an subsequent retries, the delays start becoming longer and longer,
   49579   ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
   49580   ** The total delay time before giving up is less than 10 seconds.
   49581   */
   49582   if( cnt>5 ){
   49583     int nDelay = 1;                      /* Pause time in microseconds */
   49584     if( cnt>100 ){
   49585       VVA_ONLY( pWal->lockError = 1; )
   49586       return SQLITE_PROTOCOL;
   49587     }
   49588     if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
   49589     sqlite3OsSleep(pWal->pVfs, nDelay);
   49590   }
   49591 
   49592   if( !useWal ){
   49593     rc = walIndexReadHdr(pWal, pChanged);
   49594     if( rc==SQLITE_BUSY ){
   49595       /* If there is not a recovery running in another thread or process
   49596       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
   49597       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
   49598       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
   49599       ** would be technically correct.  But the race is benign since with
   49600       ** WAL_RETRY this routine will be called again and will probably be
   49601       ** right on the second iteration.
   49602       */
   49603       if( pWal->apWiData[0]==0 ){
   49604         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
   49605         ** We assume this is a transient condition, so return WAL_RETRY. The
   49606         ** xShmMap() implementation used by the default unix and win32 VFS
   49607         ** modules may return SQLITE_BUSY due to a race condition in the
   49608         ** code that determines whether or not the shared-memory region
   49609         ** must be zeroed before the requested page is returned.
   49610         */
   49611         rc = WAL_RETRY;
   49612       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
   49613         walUnlockShared(pWal, WAL_RECOVER_LOCK);
   49614         rc = WAL_RETRY;
   49615       }else if( rc==SQLITE_BUSY ){
   49616         rc = SQLITE_BUSY_RECOVERY;
   49617       }
   49618     }
   49619     if( rc!=SQLITE_OK ){
   49620       return rc;
   49621     }
   49622   }
   49623 
   49624   pInfo = walCkptInfo(pWal);
   49625   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
   49626     /* The WAL has been completely backfilled (or it is empty).
   49627     ** and can be safely ignored.
   49628     */
   49629     rc = walLockShared(pWal, WAL_READ_LOCK(0));
   49630     walShmBarrier(pWal);
   49631     if( rc==SQLITE_OK ){
   49632       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
   49633         /* It is not safe to allow the reader to continue here if frames
   49634         ** may have been appended to the log before READ_LOCK(0) was obtained.
   49635         ** When holding READ_LOCK(0), the reader ignores the entire log file,
   49636         ** which implies that the database file contains a trustworthy
   49637         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
   49638         ** happening, this is usually correct.
   49639         **
   49640         ** However, if frames have been appended to the log (or if the log
   49641         ** is wrapped and written for that matter) before the READ_LOCK(0)
   49642         ** is obtained, that is not necessarily true. A checkpointer may
   49643         ** have started to backfill the appended frames but crashed before
   49644         ** it finished. Leaving a corrupt image in the database file.
   49645         */
   49646         walUnlockShared(pWal, WAL_READ_LOCK(0));
   49647         return WAL_RETRY;
   49648       }
   49649       pWal->readLock = 0;
   49650       return SQLITE_OK;
   49651     }else if( rc!=SQLITE_BUSY ){
   49652       return rc;
   49653     }
   49654   }
   49655 
   49656   /* If we get this far, it means that the reader will want to use
   49657   ** the WAL to get at content from recent commits.  The job now is
   49658   ** to select one of the aReadMark[] entries that is closest to
   49659   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
   49660   */
   49661   mxReadMark = 0;
   49662   mxI = 0;
   49663   for(i=1; i<WAL_NREADER; i++){
   49664     u32 thisMark = pInfo->aReadMark[i];
   49665     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
   49666       assert( thisMark!=READMARK_NOT_USED );
   49667       mxReadMark = thisMark;
   49668       mxI = i;
   49669     }
   49670   }
   49671   /* There was once an "if" here. The extra "{" is to preserve indentation. */
   49672   {
   49673     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
   49674      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
   49675     ){
   49676       for(i=1; i<WAL_NREADER; i++){
   49677         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
   49678         if( rc==SQLITE_OK ){
   49679           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
   49680           mxI = i;
   49681           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   49682           break;
   49683         }else if( rc!=SQLITE_BUSY ){
   49684           return rc;
   49685         }
   49686       }
   49687     }
   49688     if( mxI==0 ){
   49689       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
   49690       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
   49691     }
   49692 
   49693     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
   49694     if( rc ){
   49695       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
   49696     }
   49697     /* Now that the read-lock has been obtained, check that neither the
   49698     ** value in the aReadMark[] array or the contents of the wal-index
   49699     ** header have changed.
   49700     **
   49701     ** It is necessary to check that the wal-index header did not change
   49702     ** between the time it was read and when the shared-lock was obtained
   49703     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
   49704     ** that the log file may have been wrapped by a writer, or that frames
   49705     ** that occur later in the log than pWal->hdr.mxFrame may have been
   49706     ** copied into the database by a checkpointer. If either of these things
   49707     ** happened, then reading the database with the current value of
   49708     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
   49709     ** instead.
   49710     **
   49711     ** This does not guarantee that the copy of the wal-index header is up to
   49712     ** date before proceeding. That would not be possible without somehow
   49713     ** blocking writers. It only guarantees that a dangerous checkpoint or
   49714     ** log-wrap (either of which would require an exclusive lock on
   49715     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
   49716     */
   49717     walShmBarrier(pWal);
   49718     if( pInfo->aReadMark[mxI]!=mxReadMark
   49719      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
   49720     ){
   49721       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
   49722       return WAL_RETRY;
   49723     }else{
   49724       assert( mxReadMark<=pWal->hdr.mxFrame );
   49725       pWal->readLock = (i16)mxI;
   49726     }
   49727   }
   49728   return rc;
   49729 }
   49730 
   49731 /*
   49732 ** Begin a read transaction on the database.
   49733 **
   49734 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
   49735 ** it takes a snapshot of the state of the WAL and wal-index for the current
   49736 ** instant in time.  The current thread will continue to use this snapshot.
   49737 ** Other threads might append new content to the WAL and wal-index but
   49738 ** that extra content is ignored by the current thread.
   49739 **
   49740 ** If the database contents have changes since the previous read
   49741 ** transaction, then *pChanged is set to 1 before returning.  The
   49742 ** Pager layer will use this to know that is cache is stale and
   49743 ** needs to be flushed.
   49744 */
   49745 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
   49746   int rc;                         /* Return code */
   49747   int cnt = 0;                    /* Number of TryBeginRead attempts */
   49748 
   49749   do{
   49750     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
   49751   }while( rc==WAL_RETRY );
   49752   testcase( (rc&0xff)==SQLITE_BUSY );
   49753   testcase( (rc&0xff)==SQLITE_IOERR );
   49754   testcase( rc==SQLITE_PROTOCOL );
   49755   testcase( rc==SQLITE_OK );
   49756   return rc;
   49757 }
   49758 
   49759 /*
   49760 ** Finish with a read transaction.  All this does is release the
   49761 ** read-lock.
   49762 */
   49763 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
   49764   sqlite3WalEndWriteTransaction(pWal);
   49765   if( pWal->readLock>=0 ){
   49766     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   49767     pWal->readLock = -1;
   49768   }
   49769 }
   49770 
   49771 /*
   49772 ** Search the wal file for page pgno. If found, set *piRead to the frame that
   49773 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
   49774 ** to zero.
   49775 **
   49776 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
   49777 ** error does occur, the final value of *piRead is undefined.
   49778 */
   49779 SQLITE_PRIVATE int sqlite3WalFindFrame(
   49780   Wal *pWal,                      /* WAL handle */
   49781   Pgno pgno,                      /* Database page number to read data for */
   49782   u32 *piRead                     /* OUT: Frame number (or zero) */
   49783 ){
   49784   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
   49785   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
   49786   int iHash;                      /* Used to loop through N hash tables */
   49787 
   49788   /* This routine is only be called from within a read transaction. */
   49789   assert( pWal->readLock>=0 || pWal->lockError );
   49790 
   49791   /* If the "last page" field of the wal-index header snapshot is 0, then
   49792   ** no data will be read from the wal under any circumstances. Return early
   49793   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
   49794   ** then the WAL is ignored by the reader so return early, as if the
   49795   ** WAL were empty.
   49796   */
   49797   if( iLast==0 || pWal->readLock==0 ){
   49798     *piRead = 0;
   49799     return SQLITE_OK;
   49800   }
   49801 
   49802   /* Search the hash table or tables for an entry matching page number
   49803   ** pgno. Each iteration of the following for() loop searches one
   49804   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
   49805   **
   49806   ** This code might run concurrently to the code in walIndexAppend()
   49807   ** that adds entries to the wal-index (and possibly to this hash
   49808   ** table). This means the value just read from the hash
   49809   ** slot (aHash[iKey]) may have been added before or after the
   49810   ** current read transaction was opened. Values added after the
   49811   ** read transaction was opened may have been written incorrectly -
   49812   ** i.e. these slots may contain garbage data. However, we assume
   49813   ** that any slots written before the current read transaction was
   49814   ** opened remain unmodified.
   49815   **
   49816   ** For the reasons above, the if(...) condition featured in the inner
   49817   ** loop of the following block is more stringent that would be required
   49818   ** if we had exclusive access to the hash-table:
   49819   **
   49820   **   (aPgno[iFrame]==pgno):
   49821   **     This condition filters out normal hash-table collisions.
   49822   **
   49823   **   (iFrame<=iLast):
   49824   **     This condition filters out entries that were added to the hash
   49825   **     table after the current read-transaction had started.
   49826   */
   49827   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
   49828     volatile ht_slot *aHash;      /* Pointer to hash table */
   49829     volatile u32 *aPgno;          /* Pointer to array of page numbers */
   49830     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
   49831     int iKey;                     /* Hash slot index */
   49832     int nCollide;                 /* Number of hash collisions remaining */
   49833     int rc;                       /* Error code */
   49834 
   49835     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
   49836     if( rc!=SQLITE_OK ){
   49837       return rc;
   49838     }
   49839     nCollide = HASHTABLE_NSLOT;
   49840     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
   49841       u32 iFrame = aHash[iKey] + iZero;
   49842       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
   49843         /* assert( iFrame>iRead ); -- not true if there is corruption */
   49844         iRead = iFrame;
   49845       }
   49846       if( (nCollide--)==0 ){
   49847         return SQLITE_CORRUPT_BKPT;
   49848       }
   49849     }
   49850   }
   49851 
   49852 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   49853   /* If expensive assert() statements are available, do a linear search
   49854   ** of the wal-index file content. Make sure the results agree with the
   49855   ** result obtained using the hash indexes above.  */
   49856   {
   49857     u32 iRead2 = 0;
   49858     u32 iTest;
   49859     for(iTest=iLast; iTest>0; iTest--){
   49860       if( walFramePgno(pWal, iTest)==pgno ){
   49861         iRead2 = iTest;
   49862         break;
   49863       }
   49864     }
   49865     assert( iRead==iRead2 );
   49866   }
   49867 #endif
   49868 
   49869   *piRead = iRead;
   49870   return SQLITE_OK;
   49871 }
   49872 
   49873 /*
   49874 ** Read the contents of frame iRead from the wal file into buffer pOut
   49875 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
   49876 ** error code otherwise.
   49877 */
   49878 SQLITE_PRIVATE int sqlite3WalReadFrame(
   49879   Wal *pWal,                      /* WAL handle */
   49880   u32 iRead,                      /* Frame to read */
   49881   int nOut,                       /* Size of buffer pOut in bytes */
   49882   u8 *pOut                        /* Buffer to write page data to */
   49883 ){
   49884   int sz;
   49885   i64 iOffset;
   49886   sz = pWal->hdr.szPage;
   49887   sz = (sz&0xfe00) + ((sz&0x0001)<<16);
   49888   testcase( sz<=32768 );
   49889   testcase( sz>=65536 );
   49890   iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
   49891   /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
   49892   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
   49893 }
   49894 
   49895 /*
   49896 ** Return the size of the database in pages (or zero, if unknown).
   49897 */
   49898 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
   49899   if( pWal && ALWAYS(pWal->readLock>=0) ){
   49900     return pWal->hdr.nPage;
   49901   }
   49902   return 0;
   49903 }
   49904 
   49905 
   49906 /*
   49907 ** This function starts a write transaction on the WAL.
   49908 **
   49909 ** A read transaction must have already been started by a prior call
   49910 ** to sqlite3WalBeginReadTransaction().
   49911 **
   49912 ** If another thread or process has written into the database since
   49913 ** the read transaction was started, then it is not possible for this
   49914 ** thread to write as doing so would cause a fork.  So this routine
   49915 ** returns SQLITE_BUSY in that case and no write transaction is started.
   49916 **
   49917 ** There can only be a single writer active at a time.
   49918 */
   49919 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
   49920   int rc;
   49921 
   49922   /* Cannot start a write transaction without first holding a read
   49923   ** transaction. */
   49924   assert( pWal->readLock>=0 );
   49925 
   49926   if( pWal->readOnly ){
   49927     return SQLITE_READONLY;
   49928   }
   49929 
   49930   /* Only one writer allowed at a time.  Get the write lock.  Return
   49931   ** SQLITE_BUSY if unable.
   49932   */
   49933   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
   49934   if( rc ){
   49935     return rc;
   49936   }
   49937   pWal->writeLock = 1;
   49938 
   49939   /* If another connection has written to the database file since the
   49940   ** time the read transaction on this connection was started, then
   49941   ** the write is disallowed.
   49942   */
   49943   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
   49944     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   49945     pWal->writeLock = 0;
   49946     rc = SQLITE_BUSY_SNAPSHOT;
   49947   }
   49948 
   49949   return rc;
   49950 }
   49951 
   49952 /*
   49953 ** End a write transaction.  The commit has already been done.  This
   49954 ** routine merely releases the lock.
   49955 */
   49956 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
   49957   if( pWal->writeLock ){
   49958     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   49959     pWal->writeLock = 0;
   49960     pWal->truncateOnCommit = 0;
   49961   }
   49962   return SQLITE_OK;
   49963 }
   49964 
   49965 /*
   49966 ** If any data has been written (but not committed) to the log file, this
   49967 ** function moves the write-pointer back to the start of the transaction.
   49968 **
   49969 ** Additionally, the callback function is invoked for each frame written
   49970 ** to the WAL since the start of the transaction. If the callback returns
   49971 ** other than SQLITE_OK, it is not invoked again and the error code is
   49972 ** returned to the caller.
   49973 **
   49974 ** Otherwise, if the callback function does not return an error, this
   49975 ** function returns SQLITE_OK.
   49976 */
   49977 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
   49978   int rc = SQLITE_OK;
   49979   if( ALWAYS(pWal->writeLock) ){
   49980     Pgno iMax = pWal->hdr.mxFrame;
   49981     Pgno iFrame;
   49982 
   49983     /* Restore the clients cache of the wal-index header to the state it
   49984     ** was in before the client began writing to the database.
   49985     */
   49986     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
   49987 
   49988     for(iFrame=pWal->hdr.mxFrame+1;
   49989         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
   49990         iFrame++
   49991     ){
   49992       /* This call cannot fail. Unless the page for which the page number
   49993       ** is passed as the second argument is (a) in the cache and
   49994       ** (b) has an outstanding reference, then xUndo is either a no-op
   49995       ** (if (a) is false) or simply expels the page from the cache (if (b)
   49996       ** is false).
   49997       **
   49998       ** If the upper layer is doing a rollback, it is guaranteed that there
   49999       ** are no outstanding references to any page other than page 1. And
   50000       ** page 1 is never written to the log until the transaction is
   50001       ** committed. As a result, the call to xUndo may not fail.
   50002       */
   50003       assert( walFramePgno(pWal, iFrame)!=1 );
   50004       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
   50005     }
   50006     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
   50007   }
   50008   assert( rc==SQLITE_OK );
   50009   return rc;
   50010 }
   50011 
   50012 /*
   50013 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
   50014 ** values. This function populates the array with values required to
   50015 ** "rollback" the write position of the WAL handle back to the current
   50016 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
   50017 */
   50018 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
   50019   assert( pWal->writeLock );
   50020   aWalData[0] = pWal->hdr.mxFrame;
   50021   aWalData[1] = pWal->hdr.aFrameCksum[0];
   50022   aWalData[2] = pWal->hdr.aFrameCksum[1];
   50023   aWalData[3] = pWal->nCkpt;
   50024 }
   50025 
   50026 /*
   50027 ** Move the write position of the WAL back to the point identified by
   50028 ** the values in the aWalData[] array. aWalData must point to an array
   50029 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
   50030 ** by a call to WalSavepoint().
   50031 */
   50032 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
   50033   int rc = SQLITE_OK;
   50034 
   50035   assert( pWal->writeLock );
   50036   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
   50037 
   50038   if( aWalData[3]!=pWal->nCkpt ){
   50039     /* This savepoint was opened immediately after the write-transaction
   50040     ** was started. Right after that, the writer decided to wrap around
   50041     ** to the start of the log. Update the savepoint values to match.
   50042     */
   50043     aWalData[0] = 0;
   50044     aWalData[3] = pWal->nCkpt;
   50045   }
   50046 
   50047   if( aWalData[0]<pWal->hdr.mxFrame ){
   50048     pWal->hdr.mxFrame = aWalData[0];
   50049     pWal->hdr.aFrameCksum[0] = aWalData[1];
   50050     pWal->hdr.aFrameCksum[1] = aWalData[2];
   50051     walCleanupHash(pWal);
   50052   }
   50053 
   50054   return rc;
   50055 }
   50056 
   50057 
   50058 /*
   50059 ** This function is called just before writing a set of frames to the log
   50060 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
   50061 ** to the current log file, it is possible to overwrite the start of the
   50062 ** existing log file with the new frames (i.e. "reset" the log). If so,
   50063 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
   50064 ** unchanged.
   50065 **
   50066 ** SQLITE_OK is returned if no error is encountered (regardless of whether
   50067 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
   50068 ** if an error occurs.
   50069 */
   50070 static int walRestartLog(Wal *pWal){
   50071   int rc = SQLITE_OK;
   50072   int cnt;
   50073 
   50074   if( pWal->readLock==0 ){
   50075     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   50076     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
   50077     if( pInfo->nBackfill>0 ){
   50078       u32 salt1;
   50079       sqlite3_randomness(4, &salt1);
   50080       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   50081       if( rc==SQLITE_OK ){
   50082         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
   50083         ** readers are currently using the WAL), then the transactions
   50084         ** frames will overwrite the start of the existing log. Update the
   50085         ** wal-index header to reflect this.
   50086         **
   50087         ** In theory it would be Ok to update the cache of the header only
   50088         ** at this point. But updating the actual wal-index header is also
   50089         ** safe and means there is no special case for sqlite3WalUndo()
   50090         ** to handle if this transaction is rolled back.
   50091         */
   50092         int i;                    /* Loop counter */
   50093         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
   50094 
   50095         pWal->nCkpt++;
   50096         pWal->hdr.mxFrame = 0;
   50097         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
   50098         aSalt[1] = salt1;
   50099         walIndexWriteHdr(pWal);
   50100         pInfo->nBackfill = 0;
   50101         pInfo->aReadMark[1] = 0;
   50102         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   50103         assert( pInfo->aReadMark[0]==0 );
   50104         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   50105       }else if( rc!=SQLITE_BUSY ){
   50106         return rc;
   50107       }
   50108     }
   50109     walUnlockShared(pWal, WAL_READ_LOCK(0));
   50110     pWal->readLock = -1;
   50111     cnt = 0;
   50112     do{
   50113       int notUsed;
   50114       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
   50115     }while( rc==WAL_RETRY );
   50116     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
   50117     testcase( (rc&0xff)==SQLITE_IOERR );
   50118     testcase( rc==SQLITE_PROTOCOL );
   50119     testcase( rc==SQLITE_OK );
   50120   }
   50121   return rc;
   50122 }
   50123 
   50124 /*
   50125 ** Information about the current state of the WAL file and where
   50126 ** the next fsync should occur - passed from sqlite3WalFrames() into
   50127 ** walWriteToLog().
   50128 */
   50129 typedef struct WalWriter {
   50130   Wal *pWal;                   /* The complete WAL information */
   50131   sqlite3_file *pFd;           /* The WAL file to which we write */
   50132   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
   50133   int syncFlags;               /* Flags for the fsync */
   50134   int szPage;                  /* Size of one page */
   50135 } WalWriter;
   50136 
   50137 /*
   50138 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
   50139 ** Do a sync when crossing the p->iSyncPoint boundary.
   50140 **
   50141 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
   50142 ** first write the part before iSyncPoint, then sync, then write the
   50143 ** rest.
   50144 */
   50145 static int walWriteToLog(
   50146   WalWriter *p,              /* WAL to write to */
   50147   void *pContent,            /* Content to be written */
   50148   int iAmt,                  /* Number of bytes to write */
   50149   sqlite3_int64 iOffset      /* Start writing at this offset */
   50150 ){
   50151   int rc;
   50152   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
   50153     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
   50154     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
   50155     if( rc ) return rc;
   50156     iOffset += iFirstAmt;
   50157     iAmt -= iFirstAmt;
   50158     pContent = (void*)(iFirstAmt + (char*)pContent);
   50159     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
   50160     rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
   50161     if( iAmt==0 || rc ) return rc;
   50162   }
   50163   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
   50164   return rc;
   50165 }
   50166 
   50167 /*
   50168 ** Write out a single frame of the WAL
   50169 */
   50170 static int walWriteOneFrame(
   50171   WalWriter *p,               /* Where to write the frame */
   50172   PgHdr *pPage,               /* The page of the frame to be written */
   50173   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
   50174   sqlite3_int64 iOffset       /* Byte offset at which to write */
   50175 ){
   50176   int rc;                         /* Result code from subfunctions */
   50177   void *pData;                    /* Data actually written */
   50178   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
   50179 #if defined(SQLITE_HAS_CODEC)
   50180   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
   50181 #else
   50182   pData = pPage->pData;
   50183 #endif
   50184   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
   50185   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
   50186   if( rc ) return rc;
   50187   /* Write the page data */
   50188   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
   50189   return rc;
   50190 }
   50191 
   50192 /*
   50193 ** Write a set of frames to the log. The caller must hold the write-lock
   50194 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
   50195 */
   50196 SQLITE_PRIVATE int sqlite3WalFrames(
   50197   Wal *pWal,                      /* Wal handle to write to */
   50198   int szPage,                     /* Database page-size in bytes */
   50199   PgHdr *pList,                   /* List of dirty pages to write */
   50200   Pgno nTruncate,                 /* Database size after this commit */
   50201   int isCommit,                   /* True if this is a commit */
   50202   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
   50203 ){
   50204   int rc;                         /* Used to catch return codes */
   50205   u32 iFrame;                     /* Next frame address */
   50206   PgHdr *p;                       /* Iterator to run through pList with. */
   50207   PgHdr *pLast = 0;               /* Last frame in list */
   50208   int nExtra = 0;                 /* Number of extra copies of last page */
   50209   int szFrame;                    /* The size of a single frame */
   50210   i64 iOffset;                    /* Next byte to write in WAL file */
   50211   WalWriter w;                    /* The writer */
   50212 
   50213   assert( pList );
   50214   assert( pWal->writeLock );
   50215 
   50216   /* If this frame set completes a transaction, then nTruncate>0.  If
   50217   ** nTruncate==0 then this frame set does not complete the transaction. */
   50218   assert( (isCommit!=0)==(nTruncate!=0) );
   50219 
   50220 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   50221   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
   50222     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
   50223               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
   50224   }
   50225 #endif
   50226 
   50227   /* See if it is possible to write these frames into the start of the
   50228   ** log file, instead of appending to it at pWal->hdr.mxFrame.
   50229   */
   50230   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
   50231     return rc;
   50232   }
   50233 
   50234   /* If this is the first frame written into the log, write the WAL
   50235   ** header to the start of the WAL file. See comments at the top of
   50236   ** this source file for a description of the WAL header format.
   50237   */
   50238   iFrame = pWal->hdr.mxFrame;
   50239   if( iFrame==0 ){
   50240     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
   50241     u32 aCksum[2];                /* Checksum for wal-header */
   50242 
   50243     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
   50244     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
   50245     sqlite3Put4byte(&aWalHdr[8], szPage);
   50246     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
   50247     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
   50248     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
   50249     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
   50250     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
   50251     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
   50252 
   50253     pWal->szPage = szPage;
   50254     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
   50255     pWal->hdr.aFrameCksum[0] = aCksum[0];
   50256     pWal->hdr.aFrameCksum[1] = aCksum[1];
   50257     pWal->truncateOnCommit = 1;
   50258 
   50259     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
   50260     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
   50261     if( rc!=SQLITE_OK ){
   50262       return rc;
   50263     }
   50264 
   50265     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
   50266     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
   50267     ** an out-of-order write following a WAL restart could result in
   50268     ** database corruption.  See the ticket:
   50269     **
   50270     **     http://localhost:591/sqlite/info/ff5be73dee
   50271     */
   50272     if( pWal->syncHeader && sync_flags ){
   50273       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
   50274       if( rc ) return rc;
   50275     }
   50276   }
   50277   assert( (int)pWal->szPage==szPage );
   50278 
   50279   /* Setup information needed to write frames into the WAL */
   50280   w.pWal = pWal;
   50281   w.pFd = pWal->pWalFd;
   50282   w.iSyncPoint = 0;
   50283   w.syncFlags = sync_flags;
   50284   w.szPage = szPage;
   50285   iOffset = walFrameOffset(iFrame+1, szPage);
   50286   szFrame = szPage + WAL_FRAME_HDRSIZE;
   50287 
   50288   /* Write all frames into the log file exactly once */
   50289   for(p=pList; p; p=p->pDirty){
   50290     int nDbSize;   /* 0 normally.  Positive == commit flag */
   50291     iFrame++;
   50292     assert( iOffset==walFrameOffset(iFrame, szPage) );
   50293     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
   50294     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
   50295     if( rc ) return rc;
   50296     pLast = p;
   50297     iOffset += szFrame;
   50298   }
   50299 
   50300   /* If this is the end of a transaction, then we might need to pad
   50301   ** the transaction and/or sync the WAL file.
   50302   **
   50303   ** Padding and syncing only occur if this set of frames complete a
   50304   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
   50305   ** or synchonous==OFF, then no padding or syncing are needed.
   50306   **
   50307   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
   50308   ** needed and only the sync is done.  If padding is needed, then the
   50309   ** final frame is repeated (with its commit mark) until the next sector
   50310   ** boundary is crossed.  Only the part of the WAL prior to the last
   50311   ** sector boundary is synced; the part of the last frame that extends
   50312   ** past the sector boundary is written after the sync.
   50313   */
   50314   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
   50315     if( pWal->padToSectorBoundary ){
   50316       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
   50317       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
   50318       while( iOffset<w.iSyncPoint ){
   50319         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
   50320         if( rc ) return rc;
   50321         iOffset += szFrame;
   50322         nExtra++;
   50323       }
   50324     }else{
   50325       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
   50326     }
   50327   }
   50328 
   50329   /* If this frame set completes the first transaction in the WAL and
   50330   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
   50331   ** journal size limit, if possible.
   50332   */
   50333   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
   50334     i64 sz = pWal->mxWalSize;
   50335     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
   50336       sz = walFrameOffset(iFrame+nExtra+1, szPage);
   50337     }
   50338     walLimitSize(pWal, sz);
   50339     pWal->truncateOnCommit = 0;
   50340   }
   50341 
   50342   /* Append data to the wal-index. It is not necessary to lock the
   50343   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
   50344   ** guarantees that there are no other writers, and no data that may
   50345   ** be in use by existing readers is being overwritten.
   50346   */
   50347   iFrame = pWal->hdr.mxFrame;
   50348   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
   50349     iFrame++;
   50350     rc = walIndexAppend(pWal, iFrame, p->pgno);
   50351   }
   50352   while( rc==SQLITE_OK && nExtra>0 ){
   50353     iFrame++;
   50354     nExtra--;
   50355     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
   50356   }
   50357 
   50358   if( rc==SQLITE_OK ){
   50359     /* Update the private copy of the header. */
   50360     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   50361     testcase( szPage<=32768 );
   50362     testcase( szPage>=65536 );
   50363     pWal->hdr.mxFrame = iFrame;
   50364     if( isCommit ){
   50365       pWal->hdr.iChange++;
   50366       pWal->hdr.nPage = nTruncate;
   50367     }
   50368     /* If this is a commit, update the wal-index header too. */
   50369     if( isCommit ){
   50370       walIndexWriteHdr(pWal);
   50371       pWal->iCallback = iFrame;
   50372     }
   50373   }
   50374 
   50375   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
   50376   return rc;
   50377 }
   50378 
   50379 /*
   50380 ** This routine is called to implement sqlite3_wal_checkpoint() and
   50381 ** related interfaces.
   50382 **
   50383 ** Obtain a CHECKPOINT lock and then backfill as much information as
   50384 ** we can from WAL into the database.
   50385 **
   50386 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
   50387 ** callback. In this case this function runs a blocking checkpoint.
   50388 */
   50389 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   50390   Wal *pWal,                      /* Wal connection */
   50391   int eMode,                      /* PASSIVE, FULL or RESTART */
   50392   int (*xBusy)(void*),            /* Function to call when busy */
   50393   void *pBusyArg,                 /* Context argument for xBusyHandler */
   50394   int sync_flags,                 /* Flags to sync db file with (or 0) */
   50395   int nBuf,                       /* Size of temporary buffer */
   50396   u8 *zBuf,                       /* Temporary buffer to use */
   50397   int *pnLog,                     /* OUT: Number of frames in WAL */
   50398   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   50399 ){
   50400   int rc;                         /* Return code */
   50401   int isChanged = 0;              /* True if a new wal-index header is loaded */
   50402   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
   50403 
   50404   assert( pWal->ckptLock==0 );
   50405   assert( pWal->writeLock==0 );
   50406 
   50407   if( pWal->readOnly ) return SQLITE_READONLY;
   50408   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
   50409   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
   50410   if( rc ){
   50411     /* Usually this is SQLITE_BUSY meaning that another thread or process
   50412     ** is already running a checkpoint, or maybe a recovery.  But it might
   50413     ** also be SQLITE_IOERR. */
   50414     return rc;
   50415   }
   50416   pWal->ckptLock = 1;
   50417 
   50418   /* If this is a blocking-checkpoint, then obtain the write-lock as well
   50419   ** to prevent any writers from running while the checkpoint is underway.
   50420   ** This has to be done before the call to walIndexReadHdr() below.
   50421   **
   50422   ** If the writer lock cannot be obtained, then a passive checkpoint is
   50423   ** run instead. Since the checkpointer is not holding the writer lock,
   50424   ** there is no point in blocking waiting for any readers. Assuming no
   50425   ** other error occurs, this function will return SQLITE_BUSY to the caller.
   50426   */
   50427   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   50428     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
   50429     if( rc==SQLITE_OK ){
   50430       pWal->writeLock = 1;
   50431     }else if( rc==SQLITE_BUSY ){
   50432       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
   50433       rc = SQLITE_OK;
   50434     }
   50435   }
   50436 
   50437   /* Read the wal-index header. */
   50438   if( rc==SQLITE_OK ){
   50439     rc = walIndexReadHdr(pWal, &isChanged);
   50440     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
   50441       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
   50442     }
   50443   }
   50444 
   50445   /* Copy data from the log to the database file. */
   50446   if( rc==SQLITE_OK ){
   50447     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
   50448       rc = SQLITE_CORRUPT_BKPT;
   50449     }else{
   50450       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
   50451     }
   50452 
   50453     /* If no error occurred, set the output variables. */
   50454     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
   50455       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
   50456       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
   50457     }
   50458   }
   50459 
   50460   if( isChanged ){
   50461     /* If a new wal-index header was loaded before the checkpoint was
   50462     ** performed, then the pager-cache associated with pWal is now
   50463     ** out of date. So zero the cached wal-index header to ensure that
   50464     ** next time the pager opens a snapshot on this database it knows that
   50465     ** the cache needs to be reset.
   50466     */
   50467     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   50468   }
   50469 
   50470   /* Release the locks. */
   50471   sqlite3WalEndWriteTransaction(pWal);
   50472   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
   50473   pWal->ckptLock = 0;
   50474   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
   50475   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
   50476 }
   50477 
   50478 /* Return the value to pass to a sqlite3_wal_hook callback, the
   50479 ** number of frames in the WAL at the point of the last commit since
   50480 ** sqlite3WalCallback() was called.  If no commits have occurred since
   50481 ** the last call, then return 0.
   50482 */
   50483 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
   50484   u32 ret = 0;
   50485   if( pWal ){
   50486     ret = pWal->iCallback;
   50487     pWal->iCallback = 0;
   50488   }
   50489   return (int)ret;
   50490 }
   50491 
   50492 /*
   50493 ** This function is called to change the WAL subsystem into or out
   50494 ** of locking_mode=EXCLUSIVE.
   50495 **
   50496 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
   50497 ** into locking_mode=NORMAL.  This means that we must acquire a lock
   50498 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
   50499 ** or if the acquisition of the lock fails, then return 0.  If the
   50500 ** transition out of exclusive-mode is successful, return 1.  This
   50501 ** operation must occur while the pager is still holding the exclusive
   50502 ** lock on the main database file.
   50503 **
   50504 ** If op is one, then change from locking_mode=NORMAL into
   50505 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
   50506 ** be released.  Return 1 if the transition is made and 0 if the
   50507 ** WAL is already in exclusive-locking mode - meaning that this
   50508 ** routine is a no-op.  The pager must already hold the exclusive lock
   50509 ** on the main database file before invoking this operation.
   50510 **
   50511 ** If op is negative, then do a dry-run of the op==1 case but do
   50512 ** not actually change anything. The pager uses this to see if it
   50513 ** should acquire the database exclusive lock prior to invoking
   50514 ** the op==1 case.
   50515 */
   50516 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
   50517   int rc;
   50518   assert( pWal->writeLock==0 );
   50519   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
   50520 
   50521   /* pWal->readLock is usually set, but might be -1 if there was a
   50522   ** prior error while attempting to acquire are read-lock. This cannot
   50523   ** happen if the connection is actually in exclusive mode (as no xShmLock
   50524   ** locks are taken in this case). Nor should the pager attempt to
   50525   ** upgrade to exclusive-mode following such an error.
   50526   */
   50527   assert( pWal->readLock>=0 || pWal->lockError );
   50528   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
   50529 
   50530   if( op==0 ){
   50531     if( pWal->exclusiveMode ){
   50532       pWal->exclusiveMode = 0;
   50533       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
   50534         pWal->exclusiveMode = 1;
   50535       }
   50536       rc = pWal->exclusiveMode==0;
   50537     }else{
   50538       /* Already in locking_mode=NORMAL */
   50539       rc = 0;
   50540     }
   50541   }else if( op>0 ){
   50542     assert( pWal->exclusiveMode==0 );
   50543     assert( pWal->readLock>=0 );
   50544     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   50545     pWal->exclusiveMode = 1;
   50546     rc = 1;
   50547   }else{
   50548     rc = pWal->exclusiveMode==0;
   50549   }
   50550   return rc;
   50551 }
   50552 
   50553 /*
   50554 ** Return true if the argument is non-NULL and the WAL module is using
   50555 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   50556 ** WAL module is using shared-memory, return false.
   50557 */
   50558 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
   50559   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
   50560 }
   50561 
   50562 #ifdef SQLITE_ENABLE_ZIPVFS
   50563 /*
   50564 ** If the argument is not NULL, it points to a Wal object that holds a
   50565 ** read-lock. This function returns the database page-size if it is known,
   50566 ** or zero if it is not (or if pWal is NULL).
   50567 */
   50568 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
   50569   assert( pWal==0 || pWal->readLock>=0 );
   50570   return (pWal ? pWal->szPage : 0);
   50571 }
   50572 #endif
   50573 
   50574 #endif /* #ifndef SQLITE_OMIT_WAL */
   50575 
   50576 /************** End of wal.c *************************************************/
   50577 /************** Begin file btmutex.c *****************************************/
   50578 /*
   50579 ** 2007 August 27
   50580 **
   50581 ** The author disclaims copyright to this source code.  In place of
   50582 ** a legal notice, here is a blessing:
   50583 **
   50584 **    May you do good and not evil.
   50585 **    May you find forgiveness for yourself and forgive others.
   50586 **    May you share freely, never taking more than you give.
   50587 **
   50588 *************************************************************************
   50589 **
   50590 ** This file contains code used to implement mutexes on Btree objects.
   50591 ** This code really belongs in btree.c.  But btree.c is getting too
   50592 ** big and we want to break it down some.  This packaged seemed like
   50593 ** a good breakout.
   50594 */
   50595 /************** Include btreeInt.h in the middle of btmutex.c ****************/
   50596 /************** Begin file btreeInt.h ****************************************/
   50597 /*
   50598 ** 2004 April 6
   50599 **
   50600 ** The author disclaims copyright to this source code.  In place of
   50601 ** a legal notice, here is a blessing:
   50602 **
   50603 **    May you do good and not evil.
   50604 **    May you find forgiveness for yourself and forgive others.
   50605 **    May you share freely, never taking more than you give.
   50606 **
   50607 *************************************************************************
   50608 ** This file implements a external (disk-based) database using BTrees.
   50609 ** For a detailed discussion of BTrees, refer to
   50610 **
   50611 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
   50612 **     "Sorting And Searching", pages 473-480. Addison-Wesley
   50613 **     Publishing Company, Reading, Massachusetts.
   50614 **
   50615 ** The basic idea is that each page of the file contains N database
   50616 ** entries and N+1 pointers to subpages.
   50617 **
   50618 **   ----------------------------------------------------------------
   50619 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
   50620 **   ----------------------------------------------------------------
   50621 **
   50622 ** All of the keys on the page that Ptr(0) points to have values less
   50623 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
   50624 ** values greater than Key(0) and less than Key(1).  All of the keys
   50625 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
   50626 ** so forth.
   50627 **
   50628 ** Finding a particular key requires reading O(log(M)) pages from the
   50629 ** disk where M is the number of entries in the tree.
   50630 **
   50631 ** In this implementation, a single file can hold one or more separate
   50632 ** BTrees.  Each BTree is identified by the index of its root page.  The
   50633 ** key and data for any entry are combined to form the "payload".  A
   50634 ** fixed amount of payload can be carried directly on the database
   50635 ** page.  If the payload is larger than the preset amount then surplus
   50636 ** bytes are stored on overflow pages.  The payload for an entry
   50637 ** and the preceding pointer are combined to form a "Cell".  Each
   50638 ** page has a small header which contains the Ptr(N) pointer and other
   50639 ** information such as the size of key and data.
   50640 **
   50641 ** FORMAT DETAILS
   50642 **
   50643 ** The file is divided into pages.  The first page is called page 1,
   50644 ** the second is page 2, and so forth.  A page number of zero indicates
   50645 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
   50646 ** Each page can be either a btree page, a freelist page, an overflow
   50647 ** page, or a pointer-map page.
   50648 **
   50649 ** The first page is always a btree page.  The first 100 bytes of the first
   50650 ** page contain a special header (the "file header") that describes the file.
   50651 ** The format of the file header is as follows:
   50652 **
   50653 **   OFFSET   SIZE    DESCRIPTION
   50654 **      0      16     Header string: "SQLite format 3\000"
   50655 **     16       2     Page size in bytes.  (1 means 65536)
   50656 **     18       1     File format write version
   50657 **     19       1     File format read version
   50658 **     20       1     Bytes of unused space at the end of each page
   50659 **     21       1     Max embedded payload fraction (must be 64)
   50660 **     22       1     Min embedded payload fraction (must be 32)
   50661 **     23       1     Min leaf payload fraction (must be 32)
   50662 **     24       4     File change counter
   50663 **     28       4     Reserved for future use
   50664 **     32       4     First freelist page
   50665 **     36       4     Number of freelist pages in the file
   50666 **     40      60     15 4-byte meta values passed to higher layers
   50667 **
   50668 **     40       4     Schema cookie
   50669 **     44       4     File format of schema layer
   50670 **     48       4     Size of page cache
   50671 **     52       4     Largest root-page (auto/incr_vacuum)
   50672 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
   50673 **     60       4     User version
   50674 **     64       4     Incremental vacuum mode
   50675 **     68       4     Application-ID
   50676 **     72      20     unused
   50677 **     92       4     The version-valid-for number
   50678 **     96       4     SQLITE_VERSION_NUMBER
   50679 **
   50680 ** All of the integer values are big-endian (most significant byte first).
   50681 **
   50682 ** The file change counter is incremented when the database is changed
   50683 ** This counter allows other processes to know when the file has changed
   50684 ** and thus when they need to flush their cache.
   50685 **
   50686 ** The max embedded payload fraction is the amount of the total usable
   50687 ** space in a page that can be consumed by a single cell for standard
   50688 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
   50689 ** is to limit the maximum cell size so that at least 4 cells will fit
   50690 ** on one page.  Thus the default max embedded payload fraction is 64.
   50691 **
   50692 ** If the payload for a cell is larger than the max payload, then extra
   50693 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
   50694 ** as many bytes as possible are moved into the overflow pages without letting
   50695 ** the cell size drop below the min embedded payload fraction.
   50696 **
   50697 ** The min leaf payload fraction is like the min embedded payload fraction
   50698 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
   50699 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
   50700 ** not specified in the header.
   50701 **
   50702 ** Each btree pages is divided into three sections:  The header, the
   50703 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
   50704 ** file header that occurs before the page header.
   50705 **
   50706 **      |----------------|
   50707 **      | file header    |   100 bytes.  Page 1 only.
   50708 **      |----------------|
   50709 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
   50710 **      |----------------|
   50711 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
   50712 **      | array          |   |  Grows downward
   50713 **      |                |   v
   50714 **      |----------------|
   50715 **      | unallocated    |
   50716 **      | space          |
   50717 **      |----------------|   ^  Grows upwards
   50718 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
   50719 **      | area           |   |  and free space fragments.
   50720 **      |----------------|
   50721 **
   50722 ** The page headers looks like this:
   50723 **
   50724 **   OFFSET   SIZE     DESCRIPTION
   50725 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
   50726 **      1       2      byte offset to the first freeblock
   50727 **      3       2      number of cells on this page
   50728 **      5       2      first byte of the cell content area
   50729 **      7       1      number of fragmented free bytes
   50730 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
   50731 **
   50732 ** The flags define the format of this btree page.  The leaf flag means that
   50733 ** this page has no children.  The zerodata flag means that this page carries
   50734 ** only keys and no data.  The intkey flag means that the key is a integer
   50735 ** which is stored in the key size entry of the cell header rather than in
   50736 ** the payload area.
   50737 **
   50738 ** The cell pointer array begins on the first byte after the page header.
   50739 ** The cell pointer array contains zero or more 2-byte numbers which are
   50740 ** offsets from the beginning of the page to the cell content in the cell
   50741 ** content area.  The cell pointers occur in sorted order.  The system strives
   50742 ** to keep free space after the last cell pointer so that new cells can
   50743 ** be easily added without having to defragment the page.
   50744 **
   50745 ** Cell content is stored at the very end of the page and grows toward the
   50746 ** beginning of the page.
   50747 **
   50748 ** Unused space within the cell content area is collected into a linked list of
   50749 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
   50750 ** to the first freeblock is given in the header.  Freeblocks occur in
   50751 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
   50752 ** any group of 3 or fewer unused bytes in the cell content area cannot
   50753 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
   50754 ** a fragment.  The total number of bytes in all fragments is recorded.
   50755 ** in the page header at offset 7.
   50756 **
   50757 **    SIZE    DESCRIPTION
   50758 **      2     Byte offset of the next freeblock
   50759 **      2     Bytes in this freeblock
   50760 **
   50761 ** Cells are of variable length.  Cells are stored in the cell content area at
   50762 ** the end of the page.  Pointers to the cells are in the cell pointer array
   50763 ** that immediately follows the page header.  Cells is not necessarily
   50764 ** contiguous or in order, but cell pointers are contiguous and in order.
   50765 **
   50766 ** Cell content makes use of variable length integers.  A variable
   50767 ** length integer is 1 to 9 bytes where the lower 7 bits of each
   50768 ** byte are used.  The integer consists of all bytes that have bit 8 set and
   50769 ** the first byte with bit 8 clear.  The most significant byte of the integer
   50770 ** appears first.  A variable-length integer may not be more than 9 bytes long.
   50771 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
   50772 ** allows a 64-bit integer to be encoded in 9 bytes.
   50773 **
   50774 **    0x00                      becomes  0x00000000
   50775 **    0x7f                      becomes  0x0000007f
   50776 **    0x81 0x00                 becomes  0x00000080
   50777 **    0x82 0x00                 becomes  0x00000100
   50778 **    0x80 0x7f                 becomes  0x0000007f
   50779 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
   50780 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
   50781 **
   50782 ** Variable length integers are used for rowids and to hold the number of
   50783 ** bytes of key and data in a btree cell.
   50784 **
   50785 ** The content of a cell looks like this:
   50786 **
   50787 **    SIZE    DESCRIPTION
   50788 **      4     Page number of the left child. Omitted if leaf flag is set.
   50789 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
   50790 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
   50791 **      *     Payload
   50792 **      4     First page of the overflow chain.  Omitted if no overflow
   50793 **
   50794 ** Overflow pages form a linked list.  Each page except the last is completely
   50795 ** filled with data (pagesize - 4 bytes).  The last page can have as little
   50796 ** as 1 byte of data.
   50797 **
   50798 **    SIZE    DESCRIPTION
   50799 **      4     Page number of next overflow page
   50800 **      *     Data
   50801 **
   50802 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
   50803 ** file header points to the first in a linked list of trunk page.  Each trunk
   50804 ** page points to multiple leaf pages.  The content of a leaf page is
   50805 ** unspecified.  A trunk page looks like this:
   50806 **
   50807 **    SIZE    DESCRIPTION
   50808 **      4     Page number of next trunk page
   50809 **      4     Number of leaf pointers on this page
   50810 **      *     zero or more pages numbers of leaves
   50811 */
   50812 
   50813 
   50814 /* The following value is the maximum cell size assuming a maximum page
   50815 ** size give above.
   50816 */
   50817 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
   50818 
   50819 /* The maximum number of cells on a single page of the database.  This
   50820 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
   50821 ** plus 2 bytes for the index to the cell in the page header).  Such
   50822 ** small cells will be rare, but they are possible.
   50823 */
   50824 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
   50825 
   50826 /* Forward declarations */
   50827 typedef struct MemPage MemPage;
   50828 typedef struct BtLock BtLock;
   50829 
   50830 /*
   50831 ** This is a magic string that appears at the beginning of every
   50832 ** SQLite database in order to identify the file as a real database.
   50833 **
   50834 ** You can change this value at compile-time by specifying a
   50835 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
   50836 ** header must be exactly 16 bytes including the zero-terminator so
   50837 ** the string itself should be 15 characters long.  If you change
   50838 ** the header, then your custom library will not be able to read
   50839 ** databases generated by the standard tools and the standard tools
   50840 ** will not be able to read databases created by your custom library.
   50841 */
   50842 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
   50843 #  define SQLITE_FILE_HEADER "SQLite format 3"
   50844 #endif
   50845 
   50846 /*
   50847 ** Page type flags.  An ORed combination of these flags appear as the
   50848 ** first byte of on-disk image of every BTree page.
   50849 */
   50850 #define PTF_INTKEY    0x01
   50851 #define PTF_ZERODATA  0x02
   50852 #define PTF_LEAFDATA  0x04
   50853 #define PTF_LEAF      0x08
   50854 
   50855 /*
   50856 ** As each page of the file is loaded into memory, an instance of the following
   50857 ** structure is appended and initialized to zero.  This structure stores
   50858 ** information about the page that is decoded from the raw file page.
   50859 **
   50860 ** The pParent field points back to the parent page.  This allows us to
   50861 ** walk up the BTree from any leaf to the root.  Care must be taken to
   50862 ** unref() the parent page pointer when this page is no longer referenced.
   50863 ** The pageDestructor() routine handles that chore.
   50864 **
   50865 ** Access to all fields of this structure is controlled by the mutex
   50866 ** stored in MemPage.pBt->mutex.
   50867 */
   50868 struct MemPage {
   50869   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
   50870   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
   50871   u8 intKey;           /* True if intkey flag is set */
   50872   u8 leaf;             /* True if leaf flag is set */
   50873   u8 hasData;          /* True if this page stores data */
   50874   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
   50875   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
   50876   u8 max1bytePayload;  /* min(maxLocal,127) */
   50877   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
   50878   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
   50879   u16 cellOffset;      /* Index in aData of first cell pointer */
   50880   u16 nFree;           /* Number of free bytes on the page */
   50881   u16 nCell;           /* Number of cells on this page, local and ovfl */
   50882   u16 maskPage;        /* Mask for page offset */
   50883   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
   50884                        ** non-overflow cell */
   50885   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
   50886   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   50887   u8 *aData;           /* Pointer to disk image of the page data */
   50888   u8 *aDataEnd;        /* One byte past the end of usable data */
   50889   u8 *aCellIdx;        /* The cell index area */
   50890   DbPage *pDbPage;     /* Pager page handle */
   50891   Pgno pgno;           /* Page number for this page */
   50892 };
   50893 
   50894 /*
   50895 ** The in-memory image of a disk page has the auxiliary information appended
   50896 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
   50897 ** that extra information.
   50898 */
   50899 #define EXTRA_SIZE sizeof(MemPage)
   50900 
   50901 /*
   50902 ** A linked list of the following structures is stored at BtShared.pLock.
   50903 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
   50904 ** is opened on the table with root page BtShared.iTable. Locks are removed
   50905 ** from this list when a transaction is committed or rolled back, or when
   50906 ** a btree handle is closed.
   50907 */
   50908 struct BtLock {
   50909   Btree *pBtree;        /* Btree handle holding this lock */
   50910   Pgno iTable;          /* Root page of table */
   50911   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
   50912   BtLock *pNext;        /* Next in BtShared.pLock list */
   50913 };
   50914 
   50915 /* Candidate values for BtLock.eLock */
   50916 #define READ_LOCK     1
   50917 #define WRITE_LOCK    2
   50918 
   50919 /* A Btree handle
   50920 **
   50921 ** A database connection contains a pointer to an instance of
   50922 ** this object for every database file that it has open.  This structure
   50923 ** is opaque to the database connection.  The database connection cannot
   50924 ** see the internals of this structure and only deals with pointers to
   50925 ** this structure.
   50926 **
   50927 ** For some database files, the same underlying database cache might be
   50928 ** shared between multiple connections.  In that case, each connection
   50929 ** has it own instance of this object.  But each instance of this object
   50930 ** points to the same BtShared object.  The database cache and the
   50931 ** schema associated with the database file are all contained within
   50932 ** the BtShared object.
   50933 **
   50934 ** All fields in this structure are accessed under sqlite3.mutex.
   50935 ** The pBt pointer itself may not be changed while there exists cursors
   50936 ** in the referenced BtShared that point back to this Btree since those
   50937 ** cursors have to go through this Btree to find their BtShared and
   50938 ** they often do so without holding sqlite3.mutex.
   50939 */
   50940 struct Btree {
   50941   sqlite3 *db;       /* The database connection holding this btree */
   50942   BtShared *pBt;     /* Sharable content of this btree */
   50943   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
   50944   u8 sharable;       /* True if we can share pBt with another db */
   50945   u8 locked;         /* True if db currently has pBt locked */
   50946   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
   50947   int nBackup;       /* Number of backup operations reading this btree */
   50948   Btree *pNext;      /* List of other sharable Btrees from the same db */
   50949   Btree *pPrev;      /* Back pointer of the same list */
   50950 #ifndef SQLITE_OMIT_SHARED_CACHE
   50951   BtLock lock;       /* Object used to lock page 1 */
   50952 #endif
   50953 };
   50954 
   50955 /*
   50956 ** Btree.inTrans may take one of the following values.
   50957 **
   50958 ** If the shared-data extension is enabled, there may be multiple users
   50959 ** of the Btree structure. At most one of these may open a write transaction,
   50960 ** but any number may have active read transactions.
   50961 */
   50962 #define TRANS_NONE  0
   50963 #define TRANS_READ  1
   50964 #define TRANS_WRITE 2
   50965 
   50966 /*
   50967 ** An instance of this object represents a single database file.
   50968 **
   50969 ** A single database file can be in use at the same time by two
   50970 ** or more database connections.  When two or more connections are
   50971 ** sharing the same database file, each connection has it own
   50972 ** private Btree object for the file and each of those Btrees points
   50973 ** to this one BtShared object.  BtShared.nRef is the number of
   50974 ** connections currently sharing this database file.
   50975 **
   50976 ** Fields in this structure are accessed under the BtShared.mutex
   50977 ** mutex, except for nRef and pNext which are accessed under the
   50978 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
   50979 ** may not be modified once it is initially set as long as nRef>0.
   50980 ** The pSchema field may be set once under BtShared.mutex and
   50981 ** thereafter is unchanged as long as nRef>0.
   50982 **
   50983 ** isPending:
   50984 **
   50985 **   If a BtShared client fails to obtain a write-lock on a database
   50986 **   table (because there exists one or more read-locks on the table),
   50987 **   the shared-cache enters 'pending-lock' state and isPending is
   50988 **   set to true.
   50989 **
   50990 **   The shared-cache leaves the 'pending lock' state when either of
   50991 **   the following occur:
   50992 **
   50993 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
   50994 **     2) The number of locks held by other connections drops to zero.
   50995 **
   50996 **   while in the 'pending-lock' state, no connection may start a new
   50997 **   transaction.
   50998 **
   50999 **   This feature is included to help prevent writer-starvation.
   51000 */
   51001 struct BtShared {
   51002   Pager *pPager;        /* The page cache */
   51003   sqlite3 *db;          /* Database connection currently using this Btree */
   51004   BtCursor *pCursor;    /* A list of all open cursors */
   51005   MemPage *pPage1;      /* First page of the database */
   51006   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
   51007 #ifndef SQLITE_OMIT_AUTOVACUUM
   51008   u8 autoVacuum;        /* True if auto-vacuum is enabled */
   51009   u8 incrVacuum;        /* True if incr-vacuum is enabled */
   51010   u8 bDoTruncate;       /* True to truncate db on commit */
   51011 #endif
   51012   u8 inTransaction;     /* Transaction state */
   51013   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
   51014   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
   51015   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   51016   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
   51017   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
   51018   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
   51019   u32 pageSize;         /* Total number of bytes on a page */
   51020   u32 usableSize;       /* Number of usable bytes on each page */
   51021   int nTransaction;     /* Number of open transactions (read + write) */
   51022   u32 nPage;            /* Number of pages in the database */
   51023   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
   51024   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
   51025   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
   51026   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
   51027 #ifndef SQLITE_OMIT_SHARED_CACHE
   51028   int nRef;             /* Number of references to this structure */
   51029   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
   51030   BtLock *pLock;        /* List of locks held on this shared-btree struct */
   51031   Btree *pWriter;       /* Btree with currently open write transaction */
   51032 #endif
   51033   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
   51034 };
   51035 
   51036 /*
   51037 ** Allowed values for BtShared.btsFlags
   51038 */
   51039 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
   51040 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
   51041 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
   51042 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
   51043 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
   51044 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
   51045 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
   51046 
   51047 /*
   51048 ** An instance of the following structure is used to hold information
   51049 ** about a cell.  The parseCellPtr() function fills in this structure
   51050 ** based on information extract from the raw disk page.
   51051 */
   51052 typedef struct CellInfo CellInfo;
   51053 struct CellInfo {
   51054   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
   51055   u8 *pCell;     /* Pointer to the start of cell content */
   51056   u32 nData;     /* Number of bytes of data */
   51057   u32 nPayload;  /* Total amount of payload */
   51058   u16 nHeader;   /* Size of the cell content header in bytes */
   51059   u16 nLocal;    /* Amount of payload held locally */
   51060   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
   51061   u16 nSize;     /* Size of the cell content on the main b-tree page */
   51062 };
   51063 
   51064 /*
   51065 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
   51066 ** this will be declared corrupt. This value is calculated based on a
   51067 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
   51068 ** root-node and 3 for all other internal nodes.
   51069 **
   51070 ** If a tree that appears to be taller than this is encountered, it is
   51071 ** assumed that the database is corrupt.
   51072 */
   51073 #define BTCURSOR_MAX_DEPTH 20
   51074 
   51075 /*
   51076 ** A cursor is a pointer to a particular entry within a particular
   51077 ** b-tree within a database file.
   51078 **
   51079 ** The entry is identified by its MemPage and the index in
   51080 ** MemPage.aCell[] of the entry.
   51081 **
   51082 ** A single database file can be shared by two more database connections,
   51083 ** but cursors cannot be shared.  Each cursor is associated with a
   51084 ** particular database connection identified BtCursor.pBtree.db.
   51085 **
   51086 ** Fields in this structure are accessed under the BtShared.mutex
   51087 ** found at self->pBt->mutex.
   51088 */
   51089 struct BtCursor {
   51090   Btree *pBtree;            /* The Btree to which this cursor belongs */
   51091   BtShared *pBt;            /* The BtShared this cursor points to */
   51092   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
   51093   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
   51094   Pgno *aOverflow;          /* Cache of overflow page locations */
   51095   CellInfo info;            /* A parse of the cell we are pointing at */
   51096   i64 nKey;                 /* Size of pKey, or last integer key */
   51097   void *pKey;               /* Saved key that was cursor last known position */
   51098   Pgno pgnoRoot;            /* The root page of this tree */
   51099   int nOvflAlloc;           /* Allocated size of aOverflow[] array */
   51100   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
   51101   u8 curFlags;              /* zero or more BTCF_* flags defined below */
   51102   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
   51103   u8 hints;                             /* As configured by CursorSetHints() */
   51104   i16 iPage;                            /* Index of current page in apPage */
   51105   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
   51106   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
   51107 };
   51108 
   51109 /*
   51110 ** Legal values for BtCursor.curFlags
   51111 */
   51112 #define BTCF_WriteFlag    0x01   /* True if a write cursor */
   51113 #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
   51114 #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
   51115 #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
   51116 #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
   51117 
   51118 /*
   51119 ** Potential values for BtCursor.eState.
   51120 **
   51121 ** CURSOR_INVALID:
   51122 **   Cursor does not point to a valid entry. This can happen (for example)
   51123 **   because the table is empty or because BtreeCursorFirst() has not been
   51124 **   called.
   51125 **
   51126 ** CURSOR_VALID:
   51127 **   Cursor points to a valid entry. getPayload() etc. may be called.
   51128 **
   51129 ** CURSOR_SKIPNEXT:
   51130 **   Cursor is valid except that the Cursor.skipNext field is non-zero
   51131 **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
   51132 **   operation should be a no-op.
   51133 **
   51134 ** CURSOR_REQUIRESEEK:
   51135 **   The table that this cursor was opened on still exists, but has been
   51136 **   modified since the cursor was last used. The cursor position is saved
   51137 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
   51138 **   this state, restoreCursorPosition() can be called to attempt to
   51139 **   seek the cursor to the saved position.
   51140 **
   51141 ** CURSOR_FAULT:
   51142 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
   51143 **   on a different connection that shares the BtShared cache with this
   51144 **   cursor.  The error has left the cache in an inconsistent state.
   51145 **   Do nothing else with this cursor.  Any attempt to use the cursor
   51146 **   should return the error code stored in BtCursor.skip
   51147 */
   51148 #define CURSOR_INVALID           0
   51149 #define CURSOR_VALID             1
   51150 #define CURSOR_SKIPNEXT          2
   51151 #define CURSOR_REQUIRESEEK       3
   51152 #define CURSOR_FAULT             4
   51153 
   51154 /*
   51155 ** The database page the PENDING_BYTE occupies. This page is never used.
   51156 */
   51157 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
   51158 
   51159 /*
   51160 ** These macros define the location of the pointer-map entry for a
   51161 ** database page. The first argument to each is the number of usable
   51162 ** bytes on each page of the database (often 1024). The second is the
   51163 ** page number to look up in the pointer map.
   51164 **
   51165 ** PTRMAP_PAGENO returns the database page number of the pointer-map
   51166 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
   51167 ** the offset of the requested map entry.
   51168 **
   51169 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
   51170 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
   51171 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
   51172 ** this test.
   51173 */
   51174 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
   51175 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
   51176 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
   51177 
   51178 /*
   51179 ** The pointer map is a lookup table that identifies the parent page for
   51180 ** each child page in the database file.  The parent page is the page that
   51181 ** contains a pointer to the child.  Every page in the database contains
   51182 ** 0 or 1 parent pages.  (In this context 'database page' refers
   51183 ** to any page that is not part of the pointer map itself.)  Each pointer map
   51184 ** entry consists of a single byte 'type' and a 4 byte parent page number.
   51185 ** The PTRMAP_XXX identifiers below are the valid types.
   51186 **
   51187 ** The purpose of the pointer map is to facility moving pages from one
   51188 ** position in the file to another as part of autovacuum.  When a page
   51189 ** is moved, the pointer in its parent must be updated to point to the
   51190 ** new location.  The pointer map is used to locate the parent page quickly.
   51191 **
   51192 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
   51193 **                  used in this case.
   51194 **
   51195 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
   51196 **                  is not used in this case.
   51197 **
   51198 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
   51199 **                   overflow pages. The page number identifies the page that
   51200 **                   contains the cell with a pointer to this overflow page.
   51201 **
   51202 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
   51203 **                   overflow pages. The page-number identifies the previous
   51204 **                   page in the overflow page list.
   51205 **
   51206 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
   51207 **               identifies the parent page in the btree.
   51208 */
   51209 #define PTRMAP_ROOTPAGE 1
   51210 #define PTRMAP_FREEPAGE 2
   51211 #define PTRMAP_OVERFLOW1 3
   51212 #define PTRMAP_OVERFLOW2 4
   51213 #define PTRMAP_BTREE 5
   51214 
   51215 /* A bunch of assert() statements to check the transaction state variables
   51216 ** of handle p (type Btree*) are internally consistent.
   51217 */
   51218 #define btreeIntegrity(p) \
   51219   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
   51220   assert( p->pBt->inTransaction>=p->inTrans );
   51221 
   51222 
   51223 /*
   51224 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
   51225 ** if the database supports auto-vacuum or not. Because it is used
   51226 ** within an expression that is an argument to another macro
   51227 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
   51228 ** So, this macro is defined instead.
   51229 */
   51230 #ifndef SQLITE_OMIT_AUTOVACUUM
   51231 #define ISAUTOVACUUM (pBt->autoVacuum)
   51232 #else
   51233 #define ISAUTOVACUUM 0
   51234 #endif
   51235 
   51236 
   51237 /*
   51238 ** This structure is passed around through all the sanity checking routines
   51239 ** in order to keep track of some global state information.
   51240 **
   51241 ** The aRef[] array is allocated so that there is 1 bit for each page in
   51242 ** the database. As the integrity-check proceeds, for each page used in
   51243 ** the database the corresponding bit is set. This allows integrity-check to
   51244 ** detect pages that are used twice and orphaned pages (both of which
   51245 ** indicate corruption).
   51246 */
   51247 typedef struct IntegrityCk IntegrityCk;
   51248 struct IntegrityCk {
   51249   BtShared *pBt;    /* The tree being checked out */
   51250   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
   51251   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
   51252   Pgno nPage;       /* Number of pages in the database */
   51253   int mxErr;        /* Stop accumulating errors when this reaches zero */
   51254   int nErr;         /* Number of messages written to zErrMsg so far */
   51255   int mallocFailed; /* A memory allocation error has occurred */
   51256   StrAccum errMsg;  /* Accumulate the error message text here */
   51257 };
   51258 
   51259 /*
   51260 ** Routines to read or write a two- and four-byte big-endian integer values.
   51261 */
   51262 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   51263 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   51264 #define get4byte sqlite3Get4byte
   51265 #define put4byte sqlite3Put4byte
   51266 
   51267 /************** End of btreeInt.h ********************************************/
   51268 /************** Continuing where we left off in btmutex.c ********************/
   51269 #ifndef SQLITE_OMIT_SHARED_CACHE
   51270 #if SQLITE_THREADSAFE
   51271 
   51272 /*
   51273 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
   51274 ** set BtShared.db to the database handle associated with p and the
   51275 ** p->locked boolean to true.
   51276 */
   51277 static void lockBtreeMutex(Btree *p){
   51278   assert( p->locked==0 );
   51279   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
   51280   assert( sqlite3_mutex_held(p->db->mutex) );
   51281 
   51282   sqlite3_mutex_enter(p->pBt->mutex);
   51283   p->pBt->db = p->db;
   51284   p->locked = 1;
   51285 }
   51286 
   51287 /*
   51288 ** Release the BtShared mutex associated with B-Tree handle p and
   51289 ** clear the p->locked boolean.
   51290 */
   51291 static void unlockBtreeMutex(Btree *p){
   51292   BtShared *pBt = p->pBt;
   51293   assert( p->locked==1 );
   51294   assert( sqlite3_mutex_held(pBt->mutex) );
   51295   assert( sqlite3_mutex_held(p->db->mutex) );
   51296   assert( p->db==pBt->db );
   51297 
   51298   sqlite3_mutex_leave(pBt->mutex);
   51299   p->locked = 0;
   51300 }
   51301 
   51302 /*
   51303 ** Enter a mutex on the given BTree object.
   51304 **
   51305 ** If the object is not sharable, then no mutex is ever required
   51306 ** and this routine is a no-op.  The underlying mutex is non-recursive.
   51307 ** But we keep a reference count in Btree.wantToLock so the behavior
   51308 ** of this interface is recursive.
   51309 **
   51310 ** To avoid deadlocks, multiple Btrees are locked in the same order
   51311 ** by all database connections.  The p->pNext is a list of other
   51312 ** Btrees belonging to the same database connection as the p Btree
   51313 ** which need to be locked after p.  If we cannot get a lock on
   51314 ** p, then first unlock all of the others on p->pNext, then wait
   51315 ** for the lock to become available on p, then relock all of the
   51316 ** subsequent Btrees that desire a lock.
   51317 */
   51318 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   51319   Btree *pLater;
   51320 
   51321   /* Some basic sanity checking on the Btree.  The list of Btrees
   51322   ** connected by pNext and pPrev should be in sorted order by
   51323   ** Btree.pBt value. All elements of the list should belong to
   51324   ** the same connection. Only shared Btrees are on the list. */
   51325   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
   51326   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
   51327   assert( p->pNext==0 || p->pNext->db==p->db );
   51328   assert( p->pPrev==0 || p->pPrev->db==p->db );
   51329   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
   51330 
   51331   /* Check for locking consistency */
   51332   assert( !p->locked || p->wantToLock>0 );
   51333   assert( p->sharable || p->wantToLock==0 );
   51334 
   51335   /* We should already hold a lock on the database connection */
   51336   assert( sqlite3_mutex_held(p->db->mutex) );
   51337 
   51338   /* Unless the database is sharable and unlocked, then BtShared.db
   51339   ** should already be set correctly. */
   51340   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   51341 
   51342   if( !p->sharable ) return;
   51343   p->wantToLock++;
   51344   if( p->locked ) return;
   51345 
   51346   /* In most cases, we should be able to acquire the lock we
   51347   ** want without having to go throught the ascending lock
   51348   ** procedure that follows.  Just be sure not to block.
   51349   */
   51350   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
   51351     p->pBt->db = p->db;
   51352     p->locked = 1;
   51353     return;
   51354   }
   51355 
   51356   /* To avoid deadlock, first release all locks with a larger
   51357   ** BtShared address.  Then acquire our lock.  Then reacquire
   51358   ** the other BtShared locks that we used to hold in ascending
   51359   ** order.
   51360   */
   51361   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   51362     assert( pLater->sharable );
   51363     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
   51364     assert( !pLater->locked || pLater->wantToLock>0 );
   51365     if( pLater->locked ){
   51366       unlockBtreeMutex(pLater);
   51367     }
   51368   }
   51369   lockBtreeMutex(p);
   51370   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   51371     if( pLater->wantToLock ){
   51372       lockBtreeMutex(pLater);
   51373     }
   51374   }
   51375 }
   51376 
   51377 /*
   51378 ** Exit the recursive mutex on a Btree.
   51379 */
   51380 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
   51381   if( p->sharable ){
   51382     assert( p->wantToLock>0 );
   51383     p->wantToLock--;
   51384     if( p->wantToLock==0 ){
   51385       unlockBtreeMutex(p);
   51386     }
   51387   }
   51388 }
   51389 
   51390 #ifndef NDEBUG
   51391 /*
   51392 ** Return true if the BtShared mutex is held on the btree, or if the
   51393 ** B-Tree is not marked as sharable.
   51394 **
   51395 ** This routine is used only from within assert() statements.
   51396 */
   51397 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
   51398   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
   51399   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
   51400   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
   51401   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
   51402 
   51403   return (p->sharable==0 || p->locked);
   51404 }
   51405 #endif
   51406 
   51407 
   51408 #ifndef SQLITE_OMIT_INCRBLOB
   51409 /*
   51410 ** Enter and leave a mutex on a Btree given a cursor owned by that
   51411 ** Btree.  These entry points are used by incremental I/O and can be
   51412 ** omitted if that module is not used.
   51413 */
   51414 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
   51415   sqlite3BtreeEnter(pCur->pBtree);
   51416 }
   51417 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
   51418   sqlite3BtreeLeave(pCur->pBtree);
   51419 }
   51420 #endif /* SQLITE_OMIT_INCRBLOB */
   51421 
   51422 
   51423 /*
   51424 ** Enter the mutex on every Btree associated with a database
   51425 ** connection.  This is needed (for example) prior to parsing
   51426 ** a statement since we will be comparing table and column names
   51427 ** against all schemas and we do not want those schemas being
   51428 ** reset out from under us.
   51429 **
   51430 ** There is a corresponding leave-all procedures.
   51431 **
   51432 ** Enter the mutexes in accending order by BtShared pointer address
   51433 ** to avoid the possibility of deadlock when two threads with
   51434 ** two or more btrees in common both try to lock all their btrees
   51435 ** at the same instant.
   51436 */
   51437 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   51438   int i;
   51439   Btree *p;
   51440   assert( sqlite3_mutex_held(db->mutex) );
   51441   for(i=0; i<db->nDb; i++){
   51442     p = db->aDb[i].pBt;
   51443     if( p ) sqlite3BtreeEnter(p);
   51444   }
   51445 }
   51446 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
   51447   int i;
   51448   Btree *p;
   51449   assert( sqlite3_mutex_held(db->mutex) );
   51450   for(i=0; i<db->nDb; i++){
   51451     p = db->aDb[i].pBt;
   51452     if( p ) sqlite3BtreeLeave(p);
   51453   }
   51454 }
   51455 
   51456 /*
   51457 ** Return true if a particular Btree requires a lock.  Return FALSE if
   51458 ** no lock is ever required since it is not sharable.
   51459 */
   51460 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
   51461   return p->sharable;
   51462 }
   51463 
   51464 #ifndef NDEBUG
   51465 /*
   51466 ** Return true if the current thread holds the database connection
   51467 ** mutex and all required BtShared mutexes.
   51468 **
   51469 ** This routine is used inside assert() statements only.
   51470 */
   51471 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
   51472   int i;
   51473   if( !sqlite3_mutex_held(db->mutex) ){
   51474     return 0;
   51475   }
   51476   for(i=0; i<db->nDb; i++){
   51477     Btree *p;
   51478     p = db->aDb[i].pBt;
   51479     if( p && p->sharable &&
   51480          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
   51481       return 0;
   51482     }
   51483   }
   51484   return 1;
   51485 }
   51486 #endif /* NDEBUG */
   51487 
   51488 #ifndef NDEBUG
   51489 /*
   51490 ** Return true if the correct mutexes are held for accessing the
   51491 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
   51492 ** access are:
   51493 **
   51494 **   (1) The mutex on db
   51495 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
   51496 **
   51497 ** If pSchema is not NULL, then iDb is computed from pSchema and
   51498 ** db using sqlite3SchemaToIndex().
   51499 */
   51500 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
   51501   Btree *p;
   51502   assert( db!=0 );
   51503   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
   51504   assert( iDb>=0 && iDb<db->nDb );
   51505   if( !sqlite3_mutex_held(db->mutex) ) return 0;
   51506   if( iDb==1 ) return 1;
   51507   p = db->aDb[iDb].pBt;
   51508   assert( p!=0 );
   51509   return p->sharable==0 || p->locked==1;
   51510 }
   51511 #endif /* NDEBUG */
   51512 
   51513 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
   51514 /*
   51515 ** The following are special cases for mutex enter routines for use
   51516 ** in single threaded applications that use shared cache.  Except for
   51517 ** these two routines, all mutex operations are no-ops in that case and
   51518 ** are null #defines in btree.h.
   51519 **
   51520 ** If shared cache is disabled, then all btree mutex routines, including
   51521 ** the ones below, are no-ops and are null #defines in btree.h.
   51522 */
   51523 
   51524 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   51525   p->pBt->db = p->db;
   51526 }
   51527 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   51528   int i;
   51529   for(i=0; i<db->nDb; i++){
   51530     Btree *p = db->aDb[i].pBt;
   51531     if( p ){
   51532       p->pBt->db = p->db;
   51533     }
   51534   }
   51535 }
   51536 #endif /* if SQLITE_THREADSAFE */
   51537 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
   51538 
   51539 /************** End of btmutex.c *********************************************/
   51540 /************** Begin file btree.c *******************************************/
   51541 /*
   51542 ** 2004 April 6
   51543 **
   51544 ** The author disclaims copyright to this source code.  In place of
   51545 ** a legal notice, here is a blessing:
   51546 **
   51547 **    May you do good and not evil.
   51548 **    May you find forgiveness for yourself and forgive others.
   51549 **    May you share freely, never taking more than you give.
   51550 **
   51551 *************************************************************************
   51552 ** This file implements a external (disk-based) database using BTrees.
   51553 ** See the header comment on "btreeInt.h" for additional information.
   51554 ** Including a description of file format and an overview of operation.
   51555 */
   51556 
   51557 /*
   51558 ** The header string that appears at the beginning of every
   51559 ** SQLite database.
   51560 */
   51561 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
   51562 
   51563 /*
   51564 ** Set this global variable to 1 to enable tracing using the TRACE
   51565 ** macro.
   51566 */
   51567 #if 0
   51568 int sqlite3BtreeTrace=1;  /* True to enable tracing */
   51569 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
   51570 #else
   51571 # define TRACE(X)
   51572 #endif
   51573 
   51574 /*
   51575 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
   51576 ** But if the value is zero, make it 65536.
   51577 **
   51578 ** This routine is used to extract the "offset to cell content area" value
   51579 ** from the header of a btree page.  If the page size is 65536 and the page
   51580 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
   51581 ** This routine makes the necessary adjustment to 65536.
   51582 */
   51583 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
   51584 
   51585 /*
   51586 ** Values passed as the 5th argument to allocateBtreePage()
   51587 */
   51588 #define BTALLOC_ANY   0           /* Allocate any page */
   51589 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
   51590 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
   51591 
   51592 /*
   51593 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
   51594 ** defined, or 0 if it is. For example:
   51595 **
   51596 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
   51597 */
   51598 #ifndef SQLITE_OMIT_AUTOVACUUM
   51599 #define IfNotOmitAV(expr) (expr)
   51600 #else
   51601 #define IfNotOmitAV(expr) 0
   51602 #endif
   51603 
   51604 #ifndef SQLITE_OMIT_SHARED_CACHE
   51605 /*
   51606 ** A list of BtShared objects that are eligible for participation
   51607 ** in shared cache.  This variable has file scope during normal builds,
   51608 ** but the test harness needs to access it so we make it global for
   51609 ** test builds.
   51610 **
   51611 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
   51612 */
   51613 #ifdef SQLITE_TEST
   51614 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   51615 #else
   51616 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   51617 #endif
   51618 #endif /* SQLITE_OMIT_SHARED_CACHE */
   51619 
   51620 #ifndef SQLITE_OMIT_SHARED_CACHE
   51621 /*
   51622 ** Enable or disable the shared pager and schema features.
   51623 **
   51624 ** This routine has no effect on existing database connections.
   51625 ** The shared cache setting effects only future calls to
   51626 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
   51627 */
   51628 SQLITE_API int sqlite3_enable_shared_cache(int enable){
   51629   sqlite3GlobalConfig.sharedCacheEnabled = enable;
   51630   return SQLITE_OK;
   51631 }
   51632 #endif
   51633 
   51634 
   51635 
   51636 #ifdef SQLITE_OMIT_SHARED_CACHE
   51637   /*
   51638   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
   51639   ** and clearAllSharedCacheTableLocks()
   51640   ** manipulate entries in the BtShared.pLock linked list used to store
   51641   ** shared-cache table level locks. If the library is compiled with the
   51642   ** shared-cache feature disabled, then there is only ever one user
   51643   ** of each BtShared structure and so this locking is not necessary.
   51644   ** So define the lock related functions as no-ops.
   51645   */
   51646   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
   51647   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
   51648   #define clearAllSharedCacheTableLocks(a)
   51649   #define downgradeAllSharedCacheTableLocks(a)
   51650   #define hasSharedCacheTableLock(a,b,c,d) 1
   51651   #define hasReadConflicts(a, b) 0
   51652 #endif
   51653 
   51654 #ifndef SQLITE_OMIT_SHARED_CACHE
   51655 
   51656 #ifdef SQLITE_DEBUG
   51657 /*
   51658 **** This function is only used as part of an assert() statement. ***
   51659 **
   51660 ** Check to see if pBtree holds the required locks to read or write to the
   51661 ** table with root page iRoot.   Return 1 if it does and 0 if not.
   51662 **
   51663 ** For example, when writing to a table with root-page iRoot via
   51664 ** Btree connection pBtree:
   51665 **
   51666 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
   51667 **
   51668 ** When writing to an index that resides in a sharable database, the
   51669 ** caller should have first obtained a lock specifying the root page of
   51670 ** the corresponding table. This makes things a bit more complicated,
   51671 ** as this module treats each table as a separate structure. To determine
   51672 ** the table corresponding to the index being written, this
   51673 ** function has to search through the database schema.
   51674 **
   51675 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
   51676 ** hold a write-lock on the schema table (root page 1). This is also
   51677 ** acceptable.
   51678 */
   51679 static int hasSharedCacheTableLock(
   51680   Btree *pBtree,         /* Handle that must hold lock */
   51681   Pgno iRoot,            /* Root page of b-tree */
   51682   int isIndex,           /* True if iRoot is the root of an index b-tree */
   51683   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
   51684 ){
   51685   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
   51686   Pgno iTab = 0;
   51687   BtLock *pLock;
   51688 
   51689   /* If this database is not shareable, or if the client is reading
   51690   ** and has the read-uncommitted flag set, then no lock is required.
   51691   ** Return true immediately.
   51692   */
   51693   if( (pBtree->sharable==0)
   51694    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
   51695   ){
   51696     return 1;
   51697   }
   51698 
   51699   /* If the client is reading  or writing an index and the schema is
   51700   ** not loaded, then it is too difficult to actually check to see if
   51701   ** the correct locks are held.  So do not bother - just return true.
   51702   ** This case does not come up very often anyhow.
   51703   */
   51704   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
   51705     return 1;
   51706   }
   51707 
   51708   /* Figure out the root-page that the lock should be held on. For table
   51709   ** b-trees, this is just the root page of the b-tree being read or
   51710   ** written. For index b-trees, it is the root page of the associated
   51711   ** table.  */
   51712   if( isIndex ){
   51713     HashElem *p;
   51714     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
   51715       Index *pIdx = (Index *)sqliteHashData(p);
   51716       if( pIdx->tnum==(int)iRoot ){
   51717         iTab = pIdx->pTable->tnum;
   51718       }
   51719     }
   51720   }else{
   51721     iTab = iRoot;
   51722   }
   51723 
   51724   /* Search for the required lock. Either a write-lock on root-page iTab, a
   51725   ** write-lock on the schema table, or (if the client is reading) a
   51726   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
   51727   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
   51728     if( pLock->pBtree==pBtree
   51729      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
   51730      && pLock->eLock>=eLockType
   51731     ){
   51732       return 1;
   51733     }
   51734   }
   51735 
   51736   /* Failed to find the required lock. */
   51737   return 0;
   51738 }
   51739 #endif /* SQLITE_DEBUG */
   51740 
   51741 #ifdef SQLITE_DEBUG
   51742 /*
   51743 **** This function may be used as part of assert() statements only. ****
   51744 **
   51745 ** Return true if it would be illegal for pBtree to write into the
   51746 ** table or index rooted at iRoot because other shared connections are
   51747 ** simultaneously reading that same table or index.
   51748 **
   51749 ** It is illegal for pBtree to write if some other Btree object that
   51750 ** shares the same BtShared object is currently reading or writing
   51751 ** the iRoot table.  Except, if the other Btree object has the
   51752 ** read-uncommitted flag set, then it is OK for the other object to
   51753 ** have a read cursor.
   51754 **
   51755 ** For example, before writing to any part of the table or index
   51756 ** rooted at page iRoot, one should call:
   51757 **
   51758 **    assert( !hasReadConflicts(pBtree, iRoot) );
   51759 */
   51760 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
   51761   BtCursor *p;
   51762   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   51763     if( p->pgnoRoot==iRoot
   51764      && p->pBtree!=pBtree
   51765      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
   51766     ){
   51767       return 1;
   51768     }
   51769   }
   51770   return 0;
   51771 }
   51772 #endif    /* #ifdef SQLITE_DEBUG */
   51773 
   51774 /*
   51775 ** Query to see if Btree handle p may obtain a lock of type eLock
   51776 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
   51777 ** SQLITE_OK if the lock may be obtained (by calling
   51778 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
   51779 */
   51780 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   51781   BtShared *pBt = p->pBt;
   51782   BtLock *pIter;
   51783 
   51784   assert( sqlite3BtreeHoldsMutex(p) );
   51785   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   51786   assert( p->db!=0 );
   51787   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
   51788 
   51789   /* If requesting a write-lock, then the Btree must have an open write
   51790   ** transaction on this file. And, obviously, for this to be so there
   51791   ** must be an open write transaction on the file itself.
   51792   */
   51793   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
   51794   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
   51795 
   51796   /* This routine is a no-op if the shared-cache is not enabled */
   51797   if( !p->sharable ){
   51798     return SQLITE_OK;
   51799   }
   51800 
   51801   /* If some other connection is holding an exclusive lock, the
   51802   ** requested lock may not be obtained.
   51803   */
   51804   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
   51805     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
   51806     return SQLITE_LOCKED_SHAREDCACHE;
   51807   }
   51808 
   51809   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   51810     /* The condition (pIter->eLock!=eLock) in the following if(...)
   51811     ** statement is a simplification of:
   51812     **
   51813     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
   51814     **
   51815     ** since we know that if eLock==WRITE_LOCK, then no other connection
   51816     ** may hold a WRITE_LOCK on any table in this file (since there can
   51817     ** only be a single writer).
   51818     */
   51819     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
   51820     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
   51821     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
   51822       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
   51823       if( eLock==WRITE_LOCK ){
   51824         assert( p==pBt->pWriter );
   51825         pBt->btsFlags |= BTS_PENDING;
   51826       }
   51827       return SQLITE_LOCKED_SHAREDCACHE;
   51828     }
   51829   }
   51830   return SQLITE_OK;
   51831 }
   51832 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   51833 
   51834 #ifndef SQLITE_OMIT_SHARED_CACHE
   51835 /*
   51836 ** Add a lock on the table with root-page iTable to the shared-btree used
   51837 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
   51838 ** WRITE_LOCK.
   51839 **
   51840 ** This function assumes the following:
   51841 **
   51842 **   (a) The specified Btree object p is connected to a sharable
   51843 **       database (one with the BtShared.sharable flag set), and
   51844 **
   51845 **   (b) No other Btree objects hold a lock that conflicts
   51846 **       with the requested lock (i.e. querySharedCacheTableLock() has
   51847 **       already been called and returned SQLITE_OK).
   51848 **
   51849 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
   51850 ** is returned if a malloc attempt fails.
   51851 */
   51852 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
   51853   BtShared *pBt = p->pBt;
   51854   BtLock *pLock = 0;
   51855   BtLock *pIter;
   51856 
   51857   assert( sqlite3BtreeHoldsMutex(p) );
   51858   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   51859   assert( p->db!=0 );
   51860 
   51861   /* A connection with the read-uncommitted flag set will never try to
   51862   ** obtain a read-lock using this function. The only read-lock obtained
   51863   ** by a connection in read-uncommitted mode is on the sqlite_master
   51864   ** table, and that lock is obtained in BtreeBeginTrans().  */
   51865   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
   51866 
   51867   /* This function should only be called on a sharable b-tree after it
   51868   ** has been determined that no other b-tree holds a conflicting lock.  */
   51869   assert( p->sharable );
   51870   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
   51871 
   51872   /* First search the list for an existing lock on this table. */
   51873   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   51874     if( pIter->iTable==iTable && pIter->pBtree==p ){
   51875       pLock = pIter;
   51876       break;
   51877     }
   51878   }
   51879 
   51880   /* If the above search did not find a BtLock struct associating Btree p
   51881   ** with table iTable, allocate one and link it into the list.
   51882   */
   51883   if( !pLock ){
   51884     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
   51885     if( !pLock ){
   51886       return SQLITE_NOMEM;
   51887     }
   51888     pLock->iTable = iTable;
   51889     pLock->pBtree = p;
   51890     pLock->pNext = pBt->pLock;
   51891     pBt->pLock = pLock;
   51892   }
   51893 
   51894   /* Set the BtLock.eLock variable to the maximum of the current lock
   51895   ** and the requested lock. This means if a write-lock was already held
   51896   ** and a read-lock requested, we don't incorrectly downgrade the lock.
   51897   */
   51898   assert( WRITE_LOCK>READ_LOCK );
   51899   if( eLock>pLock->eLock ){
   51900     pLock->eLock = eLock;
   51901   }
   51902 
   51903   return SQLITE_OK;
   51904 }
   51905 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   51906 
   51907 #ifndef SQLITE_OMIT_SHARED_CACHE
   51908 /*
   51909 ** Release all the table locks (locks obtained via calls to
   51910 ** the setSharedCacheTableLock() procedure) held by Btree object p.
   51911 **
   51912 ** This function assumes that Btree p has an open read or write
   51913 ** transaction. If it does not, then the BTS_PENDING flag
   51914 ** may be incorrectly cleared.
   51915 */
   51916 static void clearAllSharedCacheTableLocks(Btree *p){
   51917   BtShared *pBt = p->pBt;
   51918   BtLock **ppIter = &pBt->pLock;
   51919 
   51920   assert( sqlite3BtreeHoldsMutex(p) );
   51921   assert( p->sharable || 0==*ppIter );
   51922   assert( p->inTrans>0 );
   51923 
   51924   while( *ppIter ){
   51925     BtLock *pLock = *ppIter;
   51926     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
   51927     assert( pLock->pBtree->inTrans>=pLock->eLock );
   51928     if( pLock->pBtree==p ){
   51929       *ppIter = pLock->pNext;
   51930       assert( pLock->iTable!=1 || pLock==&p->lock );
   51931       if( pLock->iTable!=1 ){
   51932         sqlite3_free(pLock);
   51933       }
   51934     }else{
   51935       ppIter = &pLock->pNext;
   51936     }
   51937   }
   51938 
   51939   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
   51940   if( pBt->pWriter==p ){
   51941     pBt->pWriter = 0;
   51942     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   51943   }else if( pBt->nTransaction==2 ){
   51944     /* This function is called when Btree p is concluding its
   51945     ** transaction. If there currently exists a writer, and p is not
   51946     ** that writer, then the number of locks held by connections other
   51947     ** than the writer must be about to drop to zero. In this case
   51948     ** set the BTS_PENDING flag to 0.
   51949     **
   51950     ** If there is not currently a writer, then BTS_PENDING must
   51951     ** be zero already. So this next line is harmless in that case.
   51952     */
   51953     pBt->btsFlags &= ~BTS_PENDING;
   51954   }
   51955 }
   51956 
   51957 /*
   51958 ** This function changes all write-locks held by Btree p into read-locks.
   51959 */
   51960 static void downgradeAllSharedCacheTableLocks(Btree *p){
   51961   BtShared *pBt = p->pBt;
   51962   if( pBt->pWriter==p ){
   51963     BtLock *pLock;
   51964     pBt->pWriter = 0;
   51965     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   51966     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
   51967       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
   51968       pLock->eLock = READ_LOCK;
   51969     }
   51970   }
   51971 }
   51972 
   51973 #endif /* SQLITE_OMIT_SHARED_CACHE */
   51974 
   51975 static void releasePage(MemPage *pPage);  /* Forward reference */
   51976 
   51977 /*
   51978 ***** This routine is used inside of assert() only ****
   51979 **
   51980 ** Verify that the cursor holds the mutex on its BtShared
   51981 */
   51982 #ifdef SQLITE_DEBUG
   51983 static int cursorHoldsMutex(BtCursor *p){
   51984   return sqlite3_mutex_held(p->pBt->mutex);
   51985 }
   51986 #endif
   51987 
   51988 /*
   51989 ** Invalidate the overflow cache of the cursor passed as the first argument.
   51990 ** on the shared btree structure pBt.
   51991 */
   51992 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
   51993 
   51994 /*
   51995 ** Invalidate the overflow page-list cache for all cursors opened
   51996 ** on the shared btree structure pBt.
   51997 */
   51998 static void invalidateAllOverflowCache(BtShared *pBt){
   51999   BtCursor *p;
   52000   assert( sqlite3_mutex_held(pBt->mutex) );
   52001   for(p=pBt->pCursor; p; p=p->pNext){
   52002     invalidateOverflowCache(p);
   52003   }
   52004 }
   52005 
   52006 #ifndef SQLITE_OMIT_INCRBLOB
   52007 /*
   52008 ** This function is called before modifying the contents of a table
   52009 ** to invalidate any incrblob cursors that are open on the
   52010 ** row or one of the rows being modified.
   52011 **
   52012 ** If argument isClearTable is true, then the entire contents of the
   52013 ** table is about to be deleted. In this case invalidate all incrblob
   52014 ** cursors open on any row within the table with root-page pgnoRoot.
   52015 **
   52016 ** Otherwise, if argument isClearTable is false, then the row with
   52017 ** rowid iRow is being replaced or deleted. In this case invalidate
   52018 ** only those incrblob cursors open on that specific row.
   52019 */
   52020 static void invalidateIncrblobCursors(
   52021   Btree *pBtree,          /* The database file to check */
   52022   i64 iRow,               /* The rowid that might be changing */
   52023   int isClearTable        /* True if all rows are being deleted */
   52024 ){
   52025   BtCursor *p;
   52026   BtShared *pBt = pBtree->pBt;
   52027   assert( sqlite3BtreeHoldsMutex(pBtree) );
   52028   for(p=pBt->pCursor; p; p=p->pNext){
   52029     if( (p->curFlags & BTCF_Incrblob)!=0 && (isClearTable || p->info.nKey==iRow) ){
   52030       p->eState = CURSOR_INVALID;
   52031     }
   52032   }
   52033 }
   52034 
   52035 #else
   52036   /* Stub function when INCRBLOB is omitted */
   52037   #define invalidateIncrblobCursors(x,y,z)
   52038 #endif /* SQLITE_OMIT_INCRBLOB */
   52039 
   52040 /*
   52041 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
   52042 ** when a page that previously contained data becomes a free-list leaf
   52043 ** page.
   52044 **
   52045 ** The BtShared.pHasContent bitvec exists to work around an obscure
   52046 ** bug caused by the interaction of two useful IO optimizations surrounding
   52047 ** free-list leaf pages:
   52048 **
   52049 **   1) When all data is deleted from a page and the page becomes
   52050 **      a free-list leaf page, the page is not written to the database
   52051 **      (as free-list leaf pages contain no meaningful data). Sometimes
   52052 **      such a page is not even journalled (as it will not be modified,
   52053 **      why bother journalling it?).
   52054 **
   52055 **   2) When a free-list leaf page is reused, its content is not read
   52056 **      from the database or written to the journal file (why should it
   52057 **      be, if it is not at all meaningful?).
   52058 **
   52059 ** By themselves, these optimizations work fine and provide a handy
   52060 ** performance boost to bulk delete or insert operations. However, if
   52061 ** a page is moved to the free-list and then reused within the same
   52062 ** transaction, a problem comes up. If the page is not journalled when
   52063 ** it is moved to the free-list and it is also not journalled when it
   52064 ** is extracted from the free-list and reused, then the original data
   52065 ** may be lost. In the event of a rollback, it may not be possible
   52066 ** to restore the database to its original configuration.
   52067 **
   52068 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
   52069 ** moved to become a free-list leaf page, the corresponding bit is
   52070 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
   52071 ** optimization 2 above is omitted if the corresponding bit is already
   52072 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
   52073 ** at the end of every transaction.
   52074 */
   52075 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
   52076   int rc = SQLITE_OK;
   52077   if( !pBt->pHasContent ){
   52078     assert( pgno<=pBt->nPage );
   52079     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
   52080     if( !pBt->pHasContent ){
   52081       rc = SQLITE_NOMEM;
   52082     }
   52083   }
   52084   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
   52085     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
   52086   }
   52087   return rc;
   52088 }
   52089 
   52090 /*
   52091 ** Query the BtShared.pHasContent vector.
   52092 **
   52093 ** This function is called when a free-list leaf page is removed from the
   52094 ** free-list for reuse. It returns false if it is safe to retrieve the
   52095 ** page from the pager layer with the 'no-content' flag set. True otherwise.
   52096 */
   52097 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
   52098   Bitvec *p = pBt->pHasContent;
   52099   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
   52100 }
   52101 
   52102 /*
   52103 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
   52104 ** invoked at the conclusion of each write-transaction.
   52105 */
   52106 static void btreeClearHasContent(BtShared *pBt){
   52107   sqlite3BitvecDestroy(pBt->pHasContent);
   52108   pBt->pHasContent = 0;
   52109 }
   52110 
   52111 /*
   52112 ** Release all of the apPage[] pages for a cursor.
   52113 */
   52114 static void btreeReleaseAllCursorPages(BtCursor *pCur){
   52115   int i;
   52116   for(i=0; i<=pCur->iPage; i++){
   52117     releasePage(pCur->apPage[i]);
   52118     pCur->apPage[i] = 0;
   52119   }
   52120   pCur->iPage = -1;
   52121 }
   52122 
   52123 
   52124 /*
   52125 ** Save the current cursor position in the variables BtCursor.nKey
   52126 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
   52127 **
   52128 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
   52129 ** prior to calling this routine.
   52130 */
   52131 static int saveCursorPosition(BtCursor *pCur){
   52132   int rc;
   52133 
   52134   assert( CURSOR_VALID==pCur->eState );
   52135   assert( 0==pCur->pKey );
   52136   assert( cursorHoldsMutex(pCur) );
   52137 
   52138   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
   52139   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
   52140 
   52141   /* If this is an intKey table, then the above call to BtreeKeySize()
   52142   ** stores the integer key in pCur->nKey. In this case this value is
   52143   ** all that is required. Otherwise, if pCur is not open on an intKey
   52144   ** table, then malloc space for and store the pCur->nKey bytes of key
   52145   ** data.
   52146   */
   52147   if( 0==pCur->apPage[0]->intKey ){
   52148     void *pKey = sqlite3Malloc( (int)pCur->nKey );
   52149     if( pKey ){
   52150       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
   52151       if( rc==SQLITE_OK ){
   52152         pCur->pKey = pKey;
   52153       }else{
   52154         sqlite3_free(pKey);
   52155       }
   52156     }else{
   52157       rc = SQLITE_NOMEM;
   52158     }
   52159   }
   52160   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
   52161 
   52162   if( rc==SQLITE_OK ){
   52163     btreeReleaseAllCursorPages(pCur);
   52164     pCur->eState = CURSOR_REQUIRESEEK;
   52165   }
   52166 
   52167   invalidateOverflowCache(pCur);
   52168   return rc;
   52169 }
   52170 
   52171 /*
   52172 ** Save the positions of all cursors (except pExcept) that are open on
   52173 ** the table  with root-page iRoot. Usually, this is called just before cursor
   52174 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
   52175 */
   52176 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
   52177   BtCursor *p;
   52178   assert( sqlite3_mutex_held(pBt->mutex) );
   52179   assert( pExcept==0 || pExcept->pBt==pBt );
   52180   for(p=pBt->pCursor; p; p=p->pNext){
   52181     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
   52182       if( p->eState==CURSOR_VALID ){
   52183         int rc = saveCursorPosition(p);
   52184         if( SQLITE_OK!=rc ){
   52185           return rc;
   52186         }
   52187       }else{
   52188         testcase( p->iPage>0 );
   52189         btreeReleaseAllCursorPages(p);
   52190       }
   52191     }
   52192   }
   52193   return SQLITE_OK;
   52194 }
   52195 
   52196 /*
   52197 ** Clear the current cursor position.
   52198 */
   52199 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
   52200   assert( cursorHoldsMutex(pCur) );
   52201   sqlite3_free(pCur->pKey);
   52202   pCur->pKey = 0;
   52203   pCur->eState = CURSOR_INVALID;
   52204 }
   52205 
   52206 /*
   52207 ** In this version of BtreeMoveto, pKey is a packed index record
   52208 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
   52209 ** record and then call BtreeMovetoUnpacked() to do the work.
   52210 */
   52211 static int btreeMoveto(
   52212   BtCursor *pCur,     /* Cursor open on the btree to be searched */
   52213   const void *pKey,   /* Packed key if the btree is an index */
   52214   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
   52215   int bias,           /* Bias search to the high end */
   52216   int *pRes           /* Write search results here */
   52217 ){
   52218   int rc;                    /* Status code */
   52219   UnpackedRecord *pIdxKey;   /* Unpacked index key */
   52220   char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
   52221   char *pFree = 0;
   52222 
   52223   if( pKey ){
   52224     assert( nKey==(i64)(int)nKey );
   52225     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
   52226         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
   52227     );
   52228     if( pIdxKey==0 ) return SQLITE_NOMEM;
   52229     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
   52230     if( pIdxKey->nField==0 ){
   52231       sqlite3DbFree(pCur->pKeyInfo->db, pFree);
   52232       return SQLITE_CORRUPT_BKPT;
   52233     }
   52234   }else{
   52235     pIdxKey = 0;
   52236   }
   52237   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
   52238   if( pFree ){
   52239     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
   52240   }
   52241   return rc;
   52242 }
   52243 
   52244 /*
   52245 ** Restore the cursor to the position it was in (or as close to as possible)
   52246 ** when saveCursorPosition() was called. Note that this call deletes the
   52247 ** saved position info stored by saveCursorPosition(), so there can be
   52248 ** at most one effective restoreCursorPosition() call after each
   52249 ** saveCursorPosition().
   52250 */
   52251 static int btreeRestoreCursorPosition(BtCursor *pCur){
   52252   int rc;
   52253   assert( cursorHoldsMutex(pCur) );
   52254   assert( pCur->eState>=CURSOR_REQUIRESEEK );
   52255   if( pCur->eState==CURSOR_FAULT ){
   52256     return pCur->skipNext;
   52257   }
   52258   pCur->eState = CURSOR_INVALID;
   52259   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
   52260   if( rc==SQLITE_OK ){
   52261     sqlite3_free(pCur->pKey);
   52262     pCur->pKey = 0;
   52263     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
   52264     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
   52265       pCur->eState = CURSOR_SKIPNEXT;
   52266     }
   52267   }
   52268   return rc;
   52269 }
   52270 
   52271 #define restoreCursorPosition(p) \
   52272   (p->eState>=CURSOR_REQUIRESEEK ? \
   52273          btreeRestoreCursorPosition(p) : \
   52274          SQLITE_OK)
   52275 
   52276 /*
   52277 ** Determine whether or not a cursor has moved from the position it
   52278 ** was last placed at.  Cursors can move when the row they are pointing
   52279 ** at is deleted out from under them.
   52280 **
   52281 ** This routine returns an error code if something goes wrong.  The
   52282 ** integer *pHasMoved is set as follows:
   52283 **
   52284 **    0:   The cursor is unchanged
   52285 **    1:   The cursor is still pointing at the same row, but the pointers
   52286 **         returned by sqlite3BtreeKeyFetch() or sqlite3BtreeDataFetch()
   52287 **         might now be invalid because of a balance() or other change to the
   52288 **         b-tree.
   52289 **    2:   The cursor is no longer pointing to the row.  The row might have
   52290 **         been deleted out from under the cursor.
   52291 */
   52292 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
   52293   int rc;
   52294 
   52295   if( pCur->eState==CURSOR_VALID ){
   52296     *pHasMoved = 0;
   52297     return SQLITE_OK;
   52298   }
   52299   rc = restoreCursorPosition(pCur);
   52300   if( rc ){
   52301     *pHasMoved = 2;
   52302     return rc;
   52303   }
   52304   if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
   52305     *pHasMoved = 2;
   52306   }else{
   52307     *pHasMoved = 1;
   52308   }
   52309   return SQLITE_OK;
   52310 }
   52311 
   52312 #ifndef SQLITE_OMIT_AUTOVACUUM
   52313 /*
   52314 ** Given a page number of a regular database page, return the page
   52315 ** number for the pointer-map page that contains the entry for the
   52316 ** input page number.
   52317 **
   52318 ** Return 0 (not a valid page) for pgno==1 since there is
   52319 ** no pointer map associated with page 1.  The integrity_check logic
   52320 ** requires that ptrmapPageno(*,1)!=1.
   52321 */
   52322 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
   52323   int nPagesPerMapPage;
   52324   Pgno iPtrMap, ret;
   52325   assert( sqlite3_mutex_held(pBt->mutex) );
   52326   if( pgno<2 ) return 0;
   52327   nPagesPerMapPage = (pBt->usableSize/5)+1;
   52328   iPtrMap = (pgno-2)/nPagesPerMapPage;
   52329   ret = (iPtrMap*nPagesPerMapPage) + 2;
   52330   if( ret==PENDING_BYTE_PAGE(pBt) ){
   52331     ret++;
   52332   }
   52333   return ret;
   52334 }
   52335 
   52336 /*
   52337 ** Write an entry into the pointer map.
   52338 **
   52339 ** This routine updates the pointer map entry for page number 'key'
   52340 ** so that it maps to type 'eType' and parent page number 'pgno'.
   52341 **
   52342 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
   52343 ** a no-op.  If an error occurs, the appropriate error code is written
   52344 ** into *pRC.
   52345 */
   52346 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
   52347   DbPage *pDbPage;  /* The pointer map page */
   52348   u8 *pPtrmap;      /* The pointer map data */
   52349   Pgno iPtrmap;     /* The pointer map page number */
   52350   int offset;       /* Offset in pointer map page */
   52351   int rc;           /* Return code from subfunctions */
   52352 
   52353   if( *pRC ) return;
   52354 
   52355   assert( sqlite3_mutex_held(pBt->mutex) );
   52356   /* The master-journal page number must never be used as a pointer map page */
   52357   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
   52358 
   52359   assert( pBt->autoVacuum );
   52360   if( key==0 ){
   52361     *pRC = SQLITE_CORRUPT_BKPT;
   52362     return;
   52363   }
   52364   iPtrmap = PTRMAP_PAGENO(pBt, key);
   52365   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   52366   if( rc!=SQLITE_OK ){
   52367     *pRC = rc;
   52368     return;
   52369   }
   52370   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   52371   if( offset<0 ){
   52372     *pRC = SQLITE_CORRUPT_BKPT;
   52373     goto ptrmap_exit;
   52374   }
   52375   assert( offset <= (int)pBt->usableSize-5 );
   52376   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   52377 
   52378   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
   52379     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
   52380     *pRC= rc = sqlite3PagerWrite(pDbPage);
   52381     if( rc==SQLITE_OK ){
   52382       pPtrmap[offset] = eType;
   52383       put4byte(&pPtrmap[offset+1], parent);
   52384     }
   52385   }
   52386 
   52387 ptrmap_exit:
   52388   sqlite3PagerUnref(pDbPage);
   52389 }
   52390 
   52391 /*
   52392 ** Read an entry from the pointer map.
   52393 **
   52394 ** This routine retrieves the pointer map entry for page 'key', writing
   52395 ** the type and parent page number to *pEType and *pPgno respectively.
   52396 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   52397 */
   52398 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
   52399   DbPage *pDbPage;   /* The pointer map page */
   52400   int iPtrmap;       /* Pointer map page index */
   52401   u8 *pPtrmap;       /* Pointer map page data */
   52402   int offset;        /* Offset of entry in pointer map */
   52403   int rc;
   52404 
   52405   assert( sqlite3_mutex_held(pBt->mutex) );
   52406 
   52407   iPtrmap = PTRMAP_PAGENO(pBt, key);
   52408   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   52409   if( rc!=0 ){
   52410     return rc;
   52411   }
   52412   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   52413 
   52414   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   52415   if( offset<0 ){
   52416     sqlite3PagerUnref(pDbPage);
   52417     return SQLITE_CORRUPT_BKPT;
   52418   }
   52419   assert( offset <= (int)pBt->usableSize-5 );
   52420   assert( pEType!=0 );
   52421   *pEType = pPtrmap[offset];
   52422   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
   52423 
   52424   sqlite3PagerUnref(pDbPage);
   52425   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
   52426   return SQLITE_OK;
   52427 }
   52428 
   52429 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
   52430   #define ptrmapPut(w,x,y,z,rc)
   52431   #define ptrmapGet(w,x,y,z) SQLITE_OK
   52432   #define ptrmapPutOvflPtr(x, y, rc)
   52433 #endif
   52434 
   52435 /*
   52436 ** Given a btree page and a cell index (0 means the first cell on
   52437 ** the page, 1 means the second cell, and so forth) return a pointer
   52438 ** to the cell content.
   52439 **
   52440 ** This routine works only for pages that do not contain overflow cells.
   52441 */
   52442 #define findCell(P,I) \
   52443   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
   52444 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
   52445 
   52446 
   52447 /*
   52448 ** This a more complex version of findCell() that works for
   52449 ** pages that do contain overflow cells.
   52450 */
   52451 static u8 *findOverflowCell(MemPage *pPage, int iCell){
   52452   int i;
   52453   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52454   for(i=pPage->nOverflow-1; i>=0; i--){
   52455     int k;
   52456     k = pPage->aiOvfl[i];
   52457     if( k<=iCell ){
   52458       if( k==iCell ){
   52459         return pPage->apOvfl[i];
   52460       }
   52461       iCell--;
   52462     }
   52463   }
   52464   return findCell(pPage, iCell);
   52465 }
   52466 
   52467 /*
   52468 ** Parse a cell content block and fill in the CellInfo structure.  There
   52469 ** are two versions of this function.  btreeParseCell() takes a
   52470 ** cell index as the second argument and btreeParseCellPtr()
   52471 ** takes a pointer to the body of the cell as its second argument.
   52472 **
   52473 ** Within this file, the parseCell() macro can be called instead of
   52474 ** btreeParseCellPtr(). Using some compilers, this will be faster.
   52475 */
   52476 static void btreeParseCellPtr(
   52477   MemPage *pPage,         /* Page containing the cell */
   52478   u8 *pCell,              /* Pointer to the cell text. */
   52479   CellInfo *pInfo         /* Fill in this structure */
   52480 ){
   52481   u16 n;                  /* Number bytes in cell content header */
   52482   u32 nPayload;           /* Number of bytes of cell payload */
   52483 
   52484   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52485 
   52486   pInfo->pCell = pCell;
   52487   assert( pPage->leaf==0 || pPage->leaf==1 );
   52488   n = pPage->childPtrSize;
   52489   assert( n==4-4*pPage->leaf );
   52490   if( pPage->intKey ){
   52491     if( pPage->hasData ){
   52492       assert( n==0 );
   52493       n = getVarint32(pCell, nPayload);
   52494     }else{
   52495       nPayload = 0;
   52496     }
   52497     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
   52498     pInfo->nData = nPayload;
   52499   }else{
   52500     pInfo->nData = 0;
   52501     n += getVarint32(&pCell[n], nPayload);
   52502     pInfo->nKey = nPayload;
   52503   }
   52504   pInfo->nPayload = nPayload;
   52505   pInfo->nHeader = n;
   52506   testcase( nPayload==pPage->maxLocal );
   52507   testcase( nPayload==pPage->maxLocal+1 );
   52508   if( likely(nPayload<=pPage->maxLocal) ){
   52509     /* This is the (easy) common case where the entire payload fits
   52510     ** on the local page.  No overflow is required.
   52511     */
   52512     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
   52513     pInfo->nLocal = (u16)nPayload;
   52514     pInfo->iOverflow = 0;
   52515   }else{
   52516     /* If the payload will not fit completely on the local page, we have
   52517     ** to decide how much to store locally and how much to spill onto
   52518     ** overflow pages.  The strategy is to minimize the amount of unused
   52519     ** space on overflow pages while keeping the amount of local storage
   52520     ** in between minLocal and maxLocal.
   52521     **
   52522     ** Warning:  changing the way overflow payload is distributed in any
   52523     ** way will result in an incompatible file format.
   52524     */
   52525     int minLocal;  /* Minimum amount of payload held locally */
   52526     int maxLocal;  /* Maximum amount of payload held locally */
   52527     int surplus;   /* Overflow payload available for local storage */
   52528 
   52529     minLocal = pPage->minLocal;
   52530     maxLocal = pPage->maxLocal;
   52531     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
   52532     testcase( surplus==maxLocal );
   52533     testcase( surplus==maxLocal+1 );
   52534     if( surplus <= maxLocal ){
   52535       pInfo->nLocal = (u16)surplus;
   52536     }else{
   52537       pInfo->nLocal = (u16)minLocal;
   52538     }
   52539     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
   52540     pInfo->nSize = pInfo->iOverflow + 4;
   52541   }
   52542 }
   52543 #define parseCell(pPage, iCell, pInfo) \
   52544   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
   52545 static void btreeParseCell(
   52546   MemPage *pPage,         /* Page containing the cell */
   52547   int iCell,              /* The cell index.  First cell is 0 */
   52548   CellInfo *pInfo         /* Fill in this structure */
   52549 ){
   52550   parseCell(pPage, iCell, pInfo);
   52551 }
   52552 
   52553 /*
   52554 ** Compute the total number of bytes that a Cell needs in the cell
   52555 ** data area of the btree-page.  The return number includes the cell
   52556 ** data header and the local payload, but not any overflow page or
   52557 ** the space used by the cell pointer.
   52558 */
   52559 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
   52560   u8 *pIter = &pCell[pPage->childPtrSize];
   52561   u32 nSize;
   52562 
   52563 #ifdef SQLITE_DEBUG
   52564   /* The value returned by this function should always be the same as
   52565   ** the (CellInfo.nSize) value found by doing a full parse of the
   52566   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
   52567   ** this function verifies that this invariant is not violated. */
   52568   CellInfo debuginfo;
   52569   btreeParseCellPtr(pPage, pCell, &debuginfo);
   52570 #endif
   52571 
   52572   if( pPage->intKey ){
   52573     u8 *pEnd;
   52574     if( pPage->hasData ){
   52575       pIter += getVarint32(pIter, nSize);
   52576     }else{
   52577       nSize = 0;
   52578     }
   52579 
   52580     /* pIter now points at the 64-bit integer key value, a variable length
   52581     ** integer. The following block moves pIter to point at the first byte
   52582     ** past the end of the key value. */
   52583     pEnd = &pIter[9];
   52584     while( (*pIter++)&0x80 && pIter<pEnd );
   52585   }else{
   52586     pIter += getVarint32(pIter, nSize);
   52587   }
   52588 
   52589   testcase( nSize==pPage->maxLocal );
   52590   testcase( nSize==pPage->maxLocal+1 );
   52591   if( nSize>pPage->maxLocal ){
   52592     int minLocal = pPage->minLocal;
   52593     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
   52594     testcase( nSize==pPage->maxLocal );
   52595     testcase( nSize==pPage->maxLocal+1 );
   52596     if( nSize>pPage->maxLocal ){
   52597       nSize = minLocal;
   52598     }
   52599     nSize += 4;
   52600   }
   52601   nSize += (u32)(pIter - pCell);
   52602 
   52603   /* The minimum size of any cell is 4 bytes. */
   52604   if( nSize<4 ){
   52605     nSize = 4;
   52606   }
   52607 
   52608   assert( nSize==debuginfo.nSize );
   52609   return (u16)nSize;
   52610 }
   52611 
   52612 #ifdef SQLITE_DEBUG
   52613 /* This variation on cellSizePtr() is used inside of assert() statements
   52614 ** only. */
   52615 static u16 cellSize(MemPage *pPage, int iCell){
   52616   return cellSizePtr(pPage, findCell(pPage, iCell));
   52617 }
   52618 #endif
   52619 
   52620 #ifndef SQLITE_OMIT_AUTOVACUUM
   52621 /*
   52622 ** If the cell pCell, part of page pPage contains a pointer
   52623 ** to an overflow page, insert an entry into the pointer-map
   52624 ** for the overflow page.
   52625 */
   52626 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
   52627   CellInfo info;
   52628   if( *pRC ) return;
   52629   assert( pCell!=0 );
   52630   btreeParseCellPtr(pPage, pCell, &info);
   52631   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
   52632   if( info.iOverflow ){
   52633     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
   52634     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
   52635   }
   52636 }
   52637 #endif
   52638 
   52639 
   52640 /*
   52641 ** Defragment the page given.  All Cells are moved to the
   52642 ** end of the page and all free space is collected into one
   52643 ** big FreeBlk that occurs in between the header and cell
   52644 ** pointer array and the cell content area.
   52645 */
   52646 static int defragmentPage(MemPage *pPage){
   52647   int i;                     /* Loop counter */
   52648   int pc;                    /* Address of a i-th cell */
   52649   int hdr;                   /* Offset to the page header */
   52650   int size;                  /* Size of a cell */
   52651   int usableSize;            /* Number of usable bytes on a page */
   52652   int cellOffset;            /* Offset to the cell pointer array */
   52653   int cbrk;                  /* Offset to the cell content area */
   52654   int nCell;                 /* Number of cells on the page */
   52655   unsigned char *data;       /* The page data */
   52656   unsigned char *temp;       /* Temp area for cell content */
   52657   int iCellFirst;            /* First allowable cell index */
   52658   int iCellLast;             /* Last possible cell index */
   52659 
   52660 
   52661   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52662   assert( pPage->pBt!=0 );
   52663   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
   52664   assert( pPage->nOverflow==0 );
   52665   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52666   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
   52667   data = pPage->aData;
   52668   hdr = pPage->hdrOffset;
   52669   cellOffset = pPage->cellOffset;
   52670   nCell = pPage->nCell;
   52671   assert( nCell==get2byte(&data[hdr+3]) );
   52672   usableSize = pPage->pBt->usableSize;
   52673   cbrk = get2byte(&data[hdr+5]);
   52674   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
   52675   cbrk = usableSize;
   52676   iCellFirst = cellOffset + 2*nCell;
   52677   iCellLast = usableSize - 4;
   52678   for(i=0; i<nCell; i++){
   52679     u8 *pAddr;     /* The i-th cell pointer */
   52680     pAddr = &data[cellOffset + i*2];
   52681     pc = get2byte(pAddr);
   52682     testcase( pc==iCellFirst );
   52683     testcase( pc==iCellLast );
   52684 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   52685     /* These conditions have already been verified in btreeInitPage()
   52686     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
   52687     */
   52688     if( pc<iCellFirst || pc>iCellLast ){
   52689       return SQLITE_CORRUPT_BKPT;
   52690     }
   52691 #endif
   52692     assert( pc>=iCellFirst && pc<=iCellLast );
   52693     size = cellSizePtr(pPage, &temp[pc]);
   52694     cbrk -= size;
   52695 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   52696     if( cbrk<iCellFirst ){
   52697       return SQLITE_CORRUPT_BKPT;
   52698     }
   52699 #else
   52700     if( cbrk<iCellFirst || pc+size>usableSize ){
   52701       return SQLITE_CORRUPT_BKPT;
   52702     }
   52703 #endif
   52704     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
   52705     testcase( cbrk+size==usableSize );
   52706     testcase( pc+size==usableSize );
   52707     memcpy(&data[cbrk], &temp[pc], size);
   52708     put2byte(pAddr, cbrk);
   52709   }
   52710   assert( cbrk>=iCellFirst );
   52711   put2byte(&data[hdr+5], cbrk);
   52712   data[hdr+1] = 0;
   52713   data[hdr+2] = 0;
   52714   data[hdr+7] = 0;
   52715   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
   52716   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52717   if( cbrk-iCellFirst!=pPage->nFree ){
   52718     return SQLITE_CORRUPT_BKPT;
   52719   }
   52720   return SQLITE_OK;
   52721 }
   52722 
   52723 /*
   52724 ** Allocate nByte bytes of space from within the B-Tree page passed
   52725 ** as the first argument. Write into *pIdx the index into pPage->aData[]
   52726 ** of the first byte of allocated space. Return either SQLITE_OK or
   52727 ** an error code (usually SQLITE_CORRUPT).
   52728 **
   52729 ** The caller guarantees that there is sufficient space to make the
   52730 ** allocation.  This routine might need to defragment in order to bring
   52731 ** all the space together, however.  This routine will avoid using
   52732 ** the first two bytes past the cell pointer area since presumably this
   52733 ** allocation is being made in order to insert a new cell, so we will
   52734 ** also end up needing a new cell pointer.
   52735 */
   52736 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   52737   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
   52738   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
   52739   int nFrag;                           /* Number of fragmented bytes on pPage */
   52740   int top;                             /* First byte of cell content area */
   52741   int gap;        /* First byte of gap between cell pointers and cell content */
   52742   int rc;         /* Integer return code */
   52743   int usableSize; /* Usable size of the page */
   52744 
   52745   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52746   assert( pPage->pBt );
   52747   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52748   assert( nByte>=0 );  /* Minimum cell size is 4 */
   52749   assert( pPage->nFree>=nByte );
   52750   assert( pPage->nOverflow==0 );
   52751   usableSize = pPage->pBt->usableSize;
   52752   assert( nByte < usableSize-8 );
   52753 
   52754   nFrag = data[hdr+7];
   52755   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
   52756   gap = pPage->cellOffset + 2*pPage->nCell;
   52757   top = get2byteNotZero(&data[hdr+5]);
   52758   if( gap>top ) return SQLITE_CORRUPT_BKPT;
   52759   testcase( gap+2==top );
   52760   testcase( gap+1==top );
   52761   testcase( gap==top );
   52762 
   52763   if( nFrag>=60 ){
   52764     /* Always defragment highly fragmented pages */
   52765     rc = defragmentPage(pPage);
   52766     if( rc ) return rc;
   52767     top = get2byteNotZero(&data[hdr+5]);
   52768   }else if( gap+2<=top ){
   52769     /* Search the freelist looking for a free slot big enough to satisfy
   52770     ** the request. The allocation is made from the first free slot in
   52771     ** the list that is large enough to accommodate it.
   52772     */
   52773     int pc, addr;
   52774     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
   52775       int size;            /* Size of the free slot */
   52776       if( pc>usableSize-4 || pc<addr+4 ){
   52777         return SQLITE_CORRUPT_BKPT;
   52778       }
   52779       size = get2byte(&data[pc+2]);
   52780       if( size>=nByte ){
   52781         int x = size - nByte;
   52782         testcase( x==4 );
   52783         testcase( x==3 );
   52784         if( x<4 ){
   52785           /* Remove the slot from the free-list. Update the number of
   52786           ** fragmented bytes within the page. */
   52787           memcpy(&data[addr], &data[pc], 2);
   52788           data[hdr+7] = (u8)(nFrag + x);
   52789         }else if( size+pc > usableSize ){
   52790           return SQLITE_CORRUPT_BKPT;
   52791         }else{
   52792           /* The slot remains on the free-list. Reduce its size to account
   52793           ** for the portion used by the new allocation. */
   52794           put2byte(&data[pc+2], x);
   52795         }
   52796         *pIdx = pc + x;
   52797         return SQLITE_OK;
   52798       }
   52799     }
   52800   }
   52801 
   52802   /* Check to make sure there is enough space in the gap to satisfy
   52803   ** the allocation.  If not, defragment.
   52804   */
   52805   testcase( gap+2+nByte==top );
   52806   if( gap+2+nByte>top ){
   52807     rc = defragmentPage(pPage);
   52808     if( rc ) return rc;
   52809     top = get2byteNotZero(&data[hdr+5]);
   52810     assert( gap+nByte<=top );
   52811   }
   52812 
   52813 
   52814   /* Allocate memory from the gap in between the cell pointer array
   52815   ** and the cell content area.  The btreeInitPage() call has already
   52816   ** validated the freelist.  Given that the freelist is valid, there
   52817   ** is no way that the allocation can extend off the end of the page.
   52818   ** The assert() below verifies the previous sentence.
   52819   */
   52820   top -= nByte;
   52821   put2byte(&data[hdr+5], top);
   52822   assert( top+nByte <= (int)pPage->pBt->usableSize );
   52823   *pIdx = top;
   52824   return SQLITE_OK;
   52825 }
   52826 
   52827 /*
   52828 ** Return a section of the pPage->aData to the freelist.
   52829 ** The first byte of the new free block is pPage->aDisk[start]
   52830 ** and the size of the block is "size" bytes.
   52831 **
   52832 ** Most of the effort here is involved in coalesing adjacent
   52833 ** free blocks into a single big free block.
   52834 */
   52835 static int freeSpace(MemPage *pPage, int start, int size){
   52836   int addr, pbegin, hdr;
   52837   int iLast;                        /* Largest possible freeblock offset */
   52838   unsigned char *data = pPage->aData;
   52839 
   52840   assert( pPage->pBt!=0 );
   52841   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52842   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
   52843   assert( (start + size) <= (int)pPage->pBt->usableSize );
   52844   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52845   assert( size>=0 );   /* Minimum cell size is 4 */
   52846 
   52847   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
   52848     /* Overwrite deleted information with zeros when the secure_delete
   52849     ** option is enabled */
   52850     memset(&data[start], 0, size);
   52851   }
   52852 
   52853   /* Add the space back into the linked list of freeblocks.  Note that
   52854   ** even though the freeblock list was checked by btreeInitPage(),
   52855   ** btreeInitPage() did not detect overlapping cells or
   52856   ** freeblocks that overlapped cells.   Nor does it detect when the
   52857   ** cell content area exceeds the value in the page header.  If these
   52858   ** situations arise, then subsequent insert operations might corrupt
   52859   ** the freelist.  So we do need to check for corruption while scanning
   52860   ** the freelist.
   52861   */
   52862   hdr = pPage->hdrOffset;
   52863   addr = hdr + 1;
   52864   iLast = pPage->pBt->usableSize - 4;
   52865   assert( start<=iLast );
   52866   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
   52867     if( pbegin<addr+4 ){
   52868       return SQLITE_CORRUPT_BKPT;
   52869     }
   52870     addr = pbegin;
   52871   }
   52872   if( pbegin>iLast ){
   52873     return SQLITE_CORRUPT_BKPT;
   52874   }
   52875   assert( pbegin>addr || pbegin==0 );
   52876   put2byte(&data[addr], start);
   52877   put2byte(&data[start], pbegin);
   52878   put2byte(&data[start+2], size);
   52879   pPage->nFree = pPage->nFree + (u16)size;
   52880 
   52881   /* Coalesce adjacent free blocks */
   52882   addr = hdr + 1;
   52883   while( (pbegin = get2byte(&data[addr]))>0 ){
   52884     int pnext, psize, x;
   52885     assert( pbegin>addr );
   52886     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
   52887     pnext = get2byte(&data[pbegin]);
   52888     psize = get2byte(&data[pbegin+2]);
   52889     if( pbegin + psize + 3 >= pnext && pnext>0 ){
   52890       int frag = pnext - (pbegin+psize);
   52891       if( (frag<0) || (frag>(int)data[hdr+7]) ){
   52892         return SQLITE_CORRUPT_BKPT;
   52893       }
   52894       data[hdr+7] -= (u8)frag;
   52895       x = get2byte(&data[pnext]);
   52896       put2byte(&data[pbegin], x);
   52897       x = pnext + get2byte(&data[pnext+2]) - pbegin;
   52898       put2byte(&data[pbegin+2], x);
   52899     }else{
   52900       addr = pbegin;
   52901     }
   52902   }
   52903 
   52904   /* If the cell content area begins with a freeblock, remove it. */
   52905   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
   52906     int top;
   52907     pbegin = get2byte(&data[hdr+1]);
   52908     memcpy(&data[hdr+1], &data[pbegin], 2);
   52909     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
   52910     put2byte(&data[hdr+5], top);
   52911   }
   52912   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52913   return SQLITE_OK;
   52914 }
   52915 
   52916 /*
   52917 ** Decode the flags byte (the first byte of the header) for a page
   52918 ** and initialize fields of the MemPage structure accordingly.
   52919 **
   52920 ** Only the following combinations are supported.  Anything different
   52921 ** indicates a corrupt database files:
   52922 **
   52923 **         PTF_ZERODATA
   52924 **         PTF_ZERODATA | PTF_LEAF
   52925 **         PTF_LEAFDATA | PTF_INTKEY
   52926 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
   52927 */
   52928 static int decodeFlags(MemPage *pPage, int flagByte){
   52929   BtShared *pBt;     /* A copy of pPage->pBt */
   52930 
   52931   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
   52932   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52933   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
   52934   flagByte &= ~PTF_LEAF;
   52935   pPage->childPtrSize = 4-4*pPage->leaf;
   52936   pBt = pPage->pBt;
   52937   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
   52938     pPage->intKey = 1;
   52939     pPage->hasData = pPage->leaf;
   52940     pPage->maxLocal = pBt->maxLeaf;
   52941     pPage->minLocal = pBt->minLeaf;
   52942   }else if( flagByte==PTF_ZERODATA ){
   52943     pPage->intKey = 0;
   52944     pPage->hasData = 0;
   52945     pPage->maxLocal = pBt->maxLocal;
   52946     pPage->minLocal = pBt->minLocal;
   52947   }else{
   52948     return SQLITE_CORRUPT_BKPT;
   52949   }
   52950   pPage->max1bytePayload = pBt->max1bytePayload;
   52951   return SQLITE_OK;
   52952 }
   52953 
   52954 /*
   52955 ** Initialize the auxiliary information for a disk block.
   52956 **
   52957 ** Return SQLITE_OK on success.  If we see that the page does
   52958 ** not contain a well-formed database page, then return
   52959 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
   52960 ** guarantee that the page is well-formed.  It only shows that
   52961 ** we failed to detect any corruption.
   52962 */
   52963 static int btreeInitPage(MemPage *pPage){
   52964 
   52965   assert( pPage->pBt!=0 );
   52966   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52967   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
   52968   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
   52969   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
   52970 
   52971   if( !pPage->isInit ){
   52972     u16 pc;            /* Address of a freeblock within pPage->aData[] */
   52973     u8 hdr;            /* Offset to beginning of page header */
   52974     u8 *data;          /* Equal to pPage->aData */
   52975     BtShared *pBt;        /* The main btree structure */
   52976     int usableSize;    /* Amount of usable space on each page */
   52977     u16 cellOffset;    /* Offset from start of page to first cell pointer */
   52978     int nFree;         /* Number of unused bytes on the page */
   52979     int top;           /* First byte of the cell content area */
   52980     int iCellFirst;    /* First allowable cell or freeblock offset */
   52981     int iCellLast;     /* Last possible cell or freeblock offset */
   52982 
   52983     pBt = pPage->pBt;
   52984 
   52985     hdr = pPage->hdrOffset;
   52986     data = pPage->aData;
   52987     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
   52988     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   52989     pPage->maskPage = (u16)(pBt->pageSize - 1);
   52990     pPage->nOverflow = 0;
   52991     usableSize = pBt->usableSize;
   52992     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
   52993     pPage->aDataEnd = &data[usableSize];
   52994     pPage->aCellIdx = &data[cellOffset];
   52995     top = get2byteNotZero(&data[hdr+5]);
   52996     pPage->nCell = get2byte(&data[hdr+3]);
   52997     if( pPage->nCell>MX_CELL(pBt) ){
   52998       /* To many cells for a single page.  The page must be corrupt */
   52999       return SQLITE_CORRUPT_BKPT;
   53000     }
   53001     testcase( pPage->nCell==MX_CELL(pBt) );
   53002 
   53003     /* A malformed database page might cause us to read past the end
   53004     ** of page when parsing a cell.
   53005     **
   53006     ** The following block of code checks early to see if a cell extends
   53007     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
   53008     ** returned if it does.
   53009     */
   53010     iCellFirst = cellOffset + 2*pPage->nCell;
   53011     iCellLast = usableSize - 4;
   53012 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   53013     {
   53014       int i;            /* Index into the cell pointer array */
   53015       int sz;           /* Size of a cell */
   53016 
   53017       if( !pPage->leaf ) iCellLast--;
   53018       for(i=0; i<pPage->nCell; i++){
   53019         pc = get2byte(&data[cellOffset+i*2]);
   53020         testcase( pc==iCellFirst );
   53021         testcase( pc==iCellLast );
   53022         if( pc<iCellFirst || pc>iCellLast ){
   53023           return SQLITE_CORRUPT_BKPT;
   53024         }
   53025         sz = cellSizePtr(pPage, &data[pc]);
   53026         testcase( pc+sz==usableSize );
   53027         if( pc+sz>usableSize ){
   53028           return SQLITE_CORRUPT_BKPT;
   53029         }
   53030       }
   53031       if( !pPage->leaf ) iCellLast++;
   53032     }
   53033 #endif
   53034 
   53035     /* Compute the total free space on the page */
   53036     pc = get2byte(&data[hdr+1]);
   53037     nFree = data[hdr+7] + top;
   53038     while( pc>0 ){
   53039       u16 next, size;
   53040       if( pc<iCellFirst || pc>iCellLast ){
   53041         /* Start of free block is off the page */
   53042         return SQLITE_CORRUPT_BKPT;
   53043       }
   53044       next = get2byte(&data[pc]);
   53045       size = get2byte(&data[pc+2]);
   53046       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
   53047         /* Free blocks must be in ascending order. And the last byte of
   53048         ** the free-block must lie on the database page.  */
   53049         return SQLITE_CORRUPT_BKPT;
   53050       }
   53051       nFree = nFree + size;
   53052       pc = next;
   53053     }
   53054 
   53055     /* At this point, nFree contains the sum of the offset to the start
   53056     ** of the cell-content area plus the number of free bytes within
   53057     ** the cell-content area. If this is greater than the usable-size
   53058     ** of the page, then the page must be corrupted. This check also
   53059     ** serves to verify that the offset to the start of the cell-content
   53060     ** area, according to the page header, lies within the page.
   53061     */
   53062     if( nFree>usableSize ){
   53063       return SQLITE_CORRUPT_BKPT;
   53064     }
   53065     pPage->nFree = (u16)(nFree - iCellFirst);
   53066     pPage->isInit = 1;
   53067   }
   53068   return SQLITE_OK;
   53069 }
   53070 
   53071 /*
   53072 ** Set up a raw page so that it looks like a database page holding
   53073 ** no entries.
   53074 */
   53075 static void zeroPage(MemPage *pPage, int flags){
   53076   unsigned char *data = pPage->aData;
   53077   BtShared *pBt = pPage->pBt;
   53078   u8 hdr = pPage->hdrOffset;
   53079   u16 first;
   53080 
   53081   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
   53082   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   53083   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
   53084   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   53085   assert( sqlite3_mutex_held(pBt->mutex) );
   53086   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   53087     memset(&data[hdr], 0, pBt->usableSize - hdr);
   53088   }
   53089   data[hdr] = (char)flags;
   53090   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
   53091   memset(&data[hdr+1], 0, 4);
   53092   data[hdr+7] = 0;
   53093   put2byte(&data[hdr+5], pBt->usableSize);
   53094   pPage->nFree = (u16)(pBt->usableSize - first);
   53095   decodeFlags(pPage, flags);
   53096   pPage->cellOffset = first;
   53097   pPage->aDataEnd = &data[pBt->usableSize];
   53098   pPage->aCellIdx = &data[first];
   53099   pPage->nOverflow = 0;
   53100   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   53101   pPage->maskPage = (u16)(pBt->pageSize - 1);
   53102   pPage->nCell = 0;
   53103   pPage->isInit = 1;
   53104 }
   53105 
   53106 
   53107 /*
   53108 ** Convert a DbPage obtained from the pager into a MemPage used by
   53109 ** the btree layer.
   53110 */
   53111 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
   53112   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
   53113   pPage->aData = sqlite3PagerGetData(pDbPage);
   53114   pPage->pDbPage = pDbPage;
   53115   pPage->pBt = pBt;
   53116   pPage->pgno = pgno;
   53117   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
   53118   return pPage;
   53119 }
   53120 
   53121 /*
   53122 ** Get a page from the pager.  Initialize the MemPage.pBt and
   53123 ** MemPage.aData elements if needed.
   53124 **
   53125 ** If the noContent flag is set, it means that we do not care about
   53126 ** the content of the page at this time.  So do not go to the disk
   53127 ** to fetch the content.  Just fill in the content with zeros for now.
   53128 ** If in the future we call sqlite3PagerWrite() on this page, that
   53129 ** means we have started to be concerned about content and the disk
   53130 ** read should occur at that point.
   53131 */
   53132 static int btreeGetPage(
   53133   BtShared *pBt,       /* The btree */
   53134   Pgno pgno,           /* Number of the page to fetch */
   53135   MemPage **ppPage,    /* Return the page in this parameter */
   53136   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
   53137 ){
   53138   int rc;
   53139   DbPage *pDbPage;
   53140 
   53141   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
   53142   assert( sqlite3_mutex_held(pBt->mutex) );
   53143   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
   53144   if( rc ) return rc;
   53145   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
   53146   return SQLITE_OK;
   53147 }
   53148 
   53149 /*
   53150 ** Retrieve a page from the pager cache. If the requested page is not
   53151 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
   53152 ** MemPage.aData elements if needed.
   53153 */
   53154 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
   53155   DbPage *pDbPage;
   53156   assert( sqlite3_mutex_held(pBt->mutex) );
   53157   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
   53158   if( pDbPage ){
   53159     return btreePageFromDbPage(pDbPage, pgno, pBt);
   53160   }
   53161   return 0;
   53162 }
   53163 
   53164 /*
   53165 ** Return the size of the database file in pages. If there is any kind of
   53166 ** error, return ((unsigned int)-1).
   53167 */
   53168 static Pgno btreePagecount(BtShared *pBt){
   53169   return pBt->nPage;
   53170 }
   53171 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
   53172   assert( sqlite3BtreeHoldsMutex(p) );
   53173   assert( ((p->pBt->nPage)&0x8000000)==0 );
   53174   return btreePagecount(p->pBt);
   53175 }
   53176 
   53177 /*
   53178 ** Get a page from the pager and initialize it.  This routine is just a
   53179 ** convenience wrapper around separate calls to btreeGetPage() and
   53180 ** btreeInitPage().
   53181 **
   53182 ** If an error occurs, then the value *ppPage is set to is undefined. It
   53183 ** may remain unchanged, or it may be set to an invalid value.
   53184 */
   53185 static int getAndInitPage(
   53186   BtShared *pBt,                  /* The database file */
   53187   Pgno pgno,                      /* Number of the page to get */
   53188   MemPage **ppPage,               /* Write the page pointer here */
   53189   int bReadonly                   /* PAGER_GET_READONLY or 0 */
   53190 ){
   53191   int rc;
   53192   assert( sqlite3_mutex_held(pBt->mutex) );
   53193   assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
   53194 
   53195   if( pgno>btreePagecount(pBt) ){
   53196     rc = SQLITE_CORRUPT_BKPT;
   53197   }else{
   53198     rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
   53199     if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
   53200       rc = btreeInitPage(*ppPage);
   53201       if( rc!=SQLITE_OK ){
   53202         releasePage(*ppPage);
   53203       }
   53204     }
   53205   }
   53206 
   53207   testcase( pgno==0 );
   53208   assert( pgno!=0 || rc==SQLITE_CORRUPT );
   53209   return rc;
   53210 }
   53211 
   53212 /*
   53213 ** Release a MemPage.  This should be called once for each prior
   53214 ** call to btreeGetPage.
   53215 */
   53216 static void releasePage(MemPage *pPage){
   53217   if( pPage ){
   53218     assert( pPage->aData );
   53219     assert( pPage->pBt );
   53220     assert( pPage->pDbPage!=0 );
   53221     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   53222     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
   53223     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   53224     sqlite3PagerUnrefNotNull(pPage->pDbPage);
   53225   }
   53226 }
   53227 
   53228 /*
   53229 ** During a rollback, when the pager reloads information into the cache
   53230 ** so that the cache is restored to its original state at the start of
   53231 ** the transaction, for each page restored this routine is called.
   53232 **
   53233 ** This routine needs to reset the extra data section at the end of the
   53234 ** page to agree with the restored data.
   53235 */
   53236 static void pageReinit(DbPage *pData){
   53237   MemPage *pPage;
   53238   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
   53239   assert( sqlite3PagerPageRefcount(pData)>0 );
   53240   if( pPage->isInit ){
   53241     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   53242     pPage->isInit = 0;
   53243     if( sqlite3PagerPageRefcount(pData)>1 ){
   53244       /* pPage might not be a btree page;  it might be an overflow page
   53245       ** or ptrmap page or a free page.  In those cases, the following
   53246       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
   53247       ** But no harm is done by this.  And it is very important that
   53248       ** btreeInitPage() be called on every btree page so we make
   53249       ** the call for every page that comes in for re-initing. */
   53250       btreeInitPage(pPage);
   53251     }
   53252   }
   53253 }
   53254 
   53255 /*
   53256 ** Invoke the busy handler for a btree.
   53257 */
   53258 static int btreeInvokeBusyHandler(void *pArg){
   53259   BtShared *pBt = (BtShared*)pArg;
   53260   assert( pBt->db );
   53261   assert( sqlite3_mutex_held(pBt->db->mutex) );
   53262   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
   53263 }
   53264 
   53265 /*
   53266 ** Open a database file.
   53267 **
   53268 ** zFilename is the name of the database file.  If zFilename is NULL
   53269 ** then an ephemeral database is created.  The ephemeral database might
   53270 ** be exclusively in memory, or it might use a disk-based memory cache.
   53271 ** Either way, the ephemeral database will be automatically deleted
   53272 ** when sqlite3BtreeClose() is called.
   53273 **
   53274 ** If zFilename is ":memory:" then an in-memory database is created
   53275 ** that is automatically destroyed when it is closed.
   53276 **
   53277 ** The "flags" parameter is a bitmask that might contain bits like
   53278 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
   53279 **
   53280 ** If the database is already opened in the same database connection
   53281 ** and we are in shared cache mode, then the open will fail with an
   53282 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
   53283 ** objects in the same database connection since doing so will lead
   53284 ** to problems with locking.
   53285 */
   53286 SQLITE_PRIVATE int sqlite3BtreeOpen(
   53287   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
   53288   const char *zFilename,  /* Name of the file containing the BTree database */
   53289   sqlite3 *db,            /* Associated database handle */
   53290   Btree **ppBtree,        /* Pointer to new Btree object written here */
   53291   int flags,              /* Options */
   53292   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
   53293 ){
   53294   BtShared *pBt = 0;             /* Shared part of btree structure */
   53295   Btree *p;                      /* Handle to return */
   53296   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
   53297   int rc = SQLITE_OK;            /* Result code from this function */
   53298   u8 nReserve;                   /* Byte of unused space on each page */
   53299   unsigned char zDbHeader[100];  /* Database header content */
   53300 
   53301   /* True if opening an ephemeral, temporary database */
   53302   const int isTempDb = zFilename==0 || zFilename[0]==0;
   53303 
   53304   /* Set the variable isMemdb to true for an in-memory database, or
   53305   ** false for a file-based database.
   53306   */
   53307 #ifdef SQLITE_OMIT_MEMORYDB
   53308   const int isMemdb = 0;
   53309 #else
   53310   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
   53311                        || (isTempDb && sqlite3TempInMemory(db))
   53312                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
   53313 #endif
   53314 
   53315   assert( db!=0 );
   53316   assert( pVfs!=0 );
   53317   assert( sqlite3_mutex_held(db->mutex) );
   53318   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
   53319 
   53320   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
   53321   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
   53322 
   53323   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
   53324   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
   53325 
   53326   if( isMemdb ){
   53327     flags |= BTREE_MEMORY;
   53328   }
   53329   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
   53330     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
   53331   }
   53332   p = sqlite3MallocZero(sizeof(Btree));
   53333   if( !p ){
   53334     return SQLITE_NOMEM;
   53335   }
   53336   p->inTrans = TRANS_NONE;
   53337   p->db = db;
   53338 #ifndef SQLITE_OMIT_SHARED_CACHE
   53339   p->lock.pBtree = p;
   53340   p->lock.iTable = 1;
   53341 #endif
   53342 
   53343 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   53344   /*
   53345   ** If this Btree is a candidate for shared cache, try to find an
   53346   ** existing BtShared object that we can share with
   53347   */
   53348   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
   53349     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
   53350       int nFullPathname = pVfs->mxPathname+1;
   53351       char *zFullPathname = sqlite3Malloc(nFullPathname);
   53352       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   53353       p->sharable = 1;
   53354       if( !zFullPathname ){
   53355         sqlite3_free(p);
   53356         return SQLITE_NOMEM;
   53357       }
   53358       if( isMemdb ){
   53359         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
   53360       }else{
   53361         rc = sqlite3OsFullPathname(pVfs, zFilename,
   53362                                    nFullPathname, zFullPathname);
   53363         if( rc ){
   53364           sqlite3_free(zFullPathname);
   53365           sqlite3_free(p);
   53366           return rc;
   53367         }
   53368       }
   53369 #if SQLITE_THREADSAFE
   53370       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
   53371       sqlite3_mutex_enter(mutexOpen);
   53372       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   53373       sqlite3_mutex_enter(mutexShared);
   53374 #endif
   53375       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
   53376         assert( pBt->nRef>0 );
   53377         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
   53378                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
   53379           int iDb;
   53380           for(iDb=db->nDb-1; iDb>=0; iDb--){
   53381             Btree *pExisting = db->aDb[iDb].pBt;
   53382             if( pExisting && pExisting->pBt==pBt ){
   53383               sqlite3_mutex_leave(mutexShared);
   53384               sqlite3_mutex_leave(mutexOpen);
   53385               sqlite3_free(zFullPathname);
   53386               sqlite3_free(p);
   53387               return SQLITE_CONSTRAINT;
   53388             }
   53389           }
   53390           p->pBt = pBt;
   53391           pBt->nRef++;
   53392           break;
   53393         }
   53394       }
   53395       sqlite3_mutex_leave(mutexShared);
   53396       sqlite3_free(zFullPathname);
   53397     }
   53398 #ifdef SQLITE_DEBUG
   53399     else{
   53400       /* In debug mode, we mark all persistent databases as sharable
   53401       ** even when they are not.  This exercises the locking code and
   53402       ** gives more opportunity for asserts(sqlite3_mutex_held())
   53403       ** statements to find locking problems.
   53404       */
   53405       p->sharable = 1;
   53406     }
   53407 #endif
   53408   }
   53409 #endif
   53410   if( pBt==0 ){
   53411     /*
   53412     ** The following asserts make sure that structures used by the btree are
   53413     ** the right size.  This is to guard against size changes that result
   53414     ** when compiling on a different architecture.
   53415     */
   53416     assert( sizeof(i64)==8 || sizeof(i64)==4 );
   53417     assert( sizeof(u64)==8 || sizeof(u64)==4 );
   53418     assert( sizeof(u32)==4 );
   53419     assert( sizeof(u16)==2 );
   53420     assert( sizeof(Pgno)==4 );
   53421 
   53422     pBt = sqlite3MallocZero( sizeof(*pBt) );
   53423     if( pBt==0 ){
   53424       rc = SQLITE_NOMEM;
   53425       goto btree_open_out;
   53426     }
   53427     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
   53428                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
   53429     if( rc==SQLITE_OK ){
   53430       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
   53431       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
   53432     }
   53433     if( rc!=SQLITE_OK ){
   53434       goto btree_open_out;
   53435     }
   53436     pBt->openFlags = (u8)flags;
   53437     pBt->db = db;
   53438     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
   53439     p->pBt = pBt;
   53440 
   53441     pBt->pCursor = 0;
   53442     pBt->pPage1 = 0;
   53443     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
   53444 #ifdef SQLITE_SECURE_DELETE
   53445     pBt->btsFlags |= BTS_SECURE_DELETE;
   53446 #endif
   53447     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
   53448     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
   53449          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
   53450       pBt->pageSize = 0;
   53451 #ifndef SQLITE_OMIT_AUTOVACUUM
   53452       /* If the magic name ":memory:" will create an in-memory database, then
   53453       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
   53454       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
   53455       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
   53456       ** regular file-name. In this case the auto-vacuum applies as per normal.
   53457       */
   53458       if( zFilename && !isMemdb ){
   53459         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
   53460         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
   53461       }
   53462 #endif
   53463       nReserve = 0;
   53464     }else{
   53465       nReserve = zDbHeader[20];
   53466       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   53467 #ifndef SQLITE_OMIT_AUTOVACUUM
   53468       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
   53469       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
   53470 #endif
   53471     }
   53472     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   53473     if( rc ) goto btree_open_out;
   53474     pBt->usableSize = pBt->pageSize - nReserve;
   53475     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
   53476 
   53477 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   53478     /* Add the new BtShared object to the linked list sharable BtShareds.
   53479     */
   53480     if( p->sharable ){
   53481       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   53482       pBt->nRef = 1;
   53483       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
   53484       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
   53485         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
   53486         if( pBt->mutex==0 ){
   53487           rc = SQLITE_NOMEM;
   53488           db->mallocFailed = 0;
   53489           goto btree_open_out;
   53490         }
   53491       }
   53492       sqlite3_mutex_enter(mutexShared);
   53493       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
   53494       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
   53495       sqlite3_mutex_leave(mutexShared);
   53496     }
   53497 #endif
   53498   }
   53499 
   53500 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   53501   /* If the new Btree uses a sharable pBtShared, then link the new
   53502   ** Btree into the list of all sharable Btrees for the same connection.
   53503   ** The list is kept in ascending order by pBt address.
   53504   */
   53505   if( p->sharable ){
   53506     int i;
   53507     Btree *pSib;
   53508     for(i=0; i<db->nDb; i++){
   53509       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
   53510         while( pSib->pPrev ){ pSib = pSib->pPrev; }
   53511         if( p->pBt<pSib->pBt ){
   53512           p->pNext = pSib;
   53513           p->pPrev = 0;
   53514           pSib->pPrev = p;
   53515         }else{
   53516           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
   53517             pSib = pSib->pNext;
   53518           }
   53519           p->pNext = pSib->pNext;
   53520           p->pPrev = pSib;
   53521           if( p->pNext ){
   53522             p->pNext->pPrev = p;
   53523           }
   53524           pSib->pNext = p;
   53525         }
   53526         break;
   53527       }
   53528     }
   53529   }
   53530 #endif
   53531   *ppBtree = p;
   53532 
   53533 btree_open_out:
   53534   if( rc!=SQLITE_OK ){
   53535     if( pBt && pBt->pPager ){
   53536       sqlite3PagerClose(pBt->pPager);
   53537     }
   53538     sqlite3_free(pBt);
   53539     sqlite3_free(p);
   53540     *ppBtree = 0;
   53541   }else{
   53542     /* If the B-Tree was successfully opened, set the pager-cache size to the
   53543     ** default value. Except, when opening on an existing shared pager-cache,
   53544     ** do not change the pager-cache size.
   53545     */
   53546     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
   53547       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
   53548     }
   53549   }
   53550   if( mutexOpen ){
   53551     assert( sqlite3_mutex_held(mutexOpen) );
   53552     sqlite3_mutex_leave(mutexOpen);
   53553   }
   53554   return rc;
   53555 }
   53556 
   53557 /*
   53558 ** Decrement the BtShared.nRef counter.  When it reaches zero,
   53559 ** remove the BtShared structure from the sharing list.  Return
   53560 ** true if the BtShared.nRef counter reaches zero and return
   53561 ** false if it is still positive.
   53562 */
   53563 static int removeFromSharingList(BtShared *pBt){
   53564 #ifndef SQLITE_OMIT_SHARED_CACHE
   53565   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
   53566   BtShared *pList;
   53567   int removed = 0;
   53568 
   53569   assert( sqlite3_mutex_notheld(pBt->mutex) );
   53570   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   53571   sqlite3_mutex_enter(pMaster);
   53572   pBt->nRef--;
   53573   if( pBt->nRef<=0 ){
   53574     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
   53575       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
   53576     }else{
   53577       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
   53578       while( ALWAYS(pList) && pList->pNext!=pBt ){
   53579         pList=pList->pNext;
   53580       }
   53581       if( ALWAYS(pList) ){
   53582         pList->pNext = pBt->pNext;
   53583       }
   53584     }
   53585     if( SQLITE_THREADSAFE ){
   53586       sqlite3_mutex_free(pBt->mutex);
   53587     }
   53588     removed = 1;
   53589   }
   53590   sqlite3_mutex_leave(pMaster);
   53591   return removed;
   53592 #else
   53593   return 1;
   53594 #endif
   53595 }
   53596 
   53597 /*
   53598 ** Make sure pBt->pTmpSpace points to an allocation of
   53599 ** MX_CELL_SIZE(pBt) bytes.
   53600 */
   53601 static void allocateTempSpace(BtShared *pBt){
   53602   if( !pBt->pTmpSpace ){
   53603     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
   53604 
   53605     /* One of the uses of pBt->pTmpSpace is to format cells before
   53606     ** inserting them into a leaf page (function fillInCell()). If
   53607     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
   53608     ** by the various routines that manipulate binary cells. Which
   53609     ** can mean that fillInCell() only initializes the first 2 or 3
   53610     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
   53611     ** it into a database page. This is not actually a problem, but it
   53612     ** does cause a valgrind error when the 1 or 2 bytes of unitialized
   53613     ** data is passed to system call write(). So to avoid this error,
   53614     ** zero the first 4 bytes of temp space here.  */
   53615     if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
   53616   }
   53617 }
   53618 
   53619 /*
   53620 ** Free the pBt->pTmpSpace allocation
   53621 */
   53622 static void freeTempSpace(BtShared *pBt){
   53623   sqlite3PageFree( pBt->pTmpSpace);
   53624   pBt->pTmpSpace = 0;
   53625 }
   53626 
   53627 /*
   53628 ** Close an open database and invalidate all cursors.
   53629 */
   53630 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   53631   BtShared *pBt = p->pBt;
   53632   BtCursor *pCur;
   53633 
   53634   /* Close all cursors opened via this handle.  */
   53635   assert( sqlite3_mutex_held(p->db->mutex) );
   53636   sqlite3BtreeEnter(p);
   53637   pCur = pBt->pCursor;
   53638   while( pCur ){
   53639     BtCursor *pTmp = pCur;
   53640     pCur = pCur->pNext;
   53641     if( pTmp->pBtree==p ){
   53642       sqlite3BtreeCloseCursor(pTmp);
   53643     }
   53644   }
   53645 
   53646   /* Rollback any active transaction and free the handle structure.
   53647   ** The call to sqlite3BtreeRollback() drops any table-locks held by
   53648   ** this handle.
   53649   */
   53650   sqlite3BtreeRollback(p, SQLITE_OK);
   53651   sqlite3BtreeLeave(p);
   53652 
   53653   /* If there are still other outstanding references to the shared-btree
   53654   ** structure, return now. The remainder of this procedure cleans
   53655   ** up the shared-btree.
   53656   */
   53657   assert( p->wantToLock==0 && p->locked==0 );
   53658   if( !p->sharable || removeFromSharingList(pBt) ){
   53659     /* The pBt is no longer on the sharing list, so we can access
   53660     ** it without having to hold the mutex.
   53661     **
   53662     ** Clean out and delete the BtShared object.
   53663     */
   53664     assert( !pBt->pCursor );
   53665     sqlite3PagerClose(pBt->pPager);
   53666     if( pBt->xFreeSchema && pBt->pSchema ){
   53667       pBt->xFreeSchema(pBt->pSchema);
   53668     }
   53669     sqlite3DbFree(0, pBt->pSchema);
   53670     freeTempSpace(pBt);
   53671     sqlite3_free(pBt);
   53672   }
   53673 
   53674 #ifndef SQLITE_OMIT_SHARED_CACHE
   53675   assert( p->wantToLock==0 );
   53676   assert( p->locked==0 );
   53677   if( p->pPrev ) p->pPrev->pNext = p->pNext;
   53678   if( p->pNext ) p->pNext->pPrev = p->pPrev;
   53679 #endif
   53680 
   53681   sqlite3_free(p);
   53682   return SQLITE_OK;
   53683 }
   53684 
   53685 /*
   53686 ** Change the limit on the number of pages allowed in the cache.
   53687 **
   53688 ** The maximum number of cache pages is set to the absolute
   53689 ** value of mxPage.  If mxPage is negative, the pager will
   53690 ** operate asynchronously - it will not stop to do fsync()s
   53691 ** to insure data is written to the disk surface before
   53692 ** continuing.  Transactions still work if synchronous is off,
   53693 ** and the database cannot be corrupted if this program
   53694 ** crashes.  But if the operating system crashes or there is
   53695 ** an abrupt power failure when synchronous is off, the database
   53696 ** could be left in an inconsistent and unrecoverable state.
   53697 ** Synchronous is on by default so database corruption is not
   53698 ** normally a worry.
   53699 */
   53700 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
   53701   BtShared *pBt = p->pBt;
   53702   assert( sqlite3_mutex_held(p->db->mutex) );
   53703   sqlite3BtreeEnter(p);
   53704   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
   53705   sqlite3BtreeLeave(p);
   53706   return SQLITE_OK;
   53707 }
   53708 
   53709 #if SQLITE_MAX_MMAP_SIZE>0
   53710 /*
   53711 ** Change the limit on the amount of the database file that may be
   53712 ** memory mapped.
   53713 */
   53714 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
   53715   BtShared *pBt = p->pBt;
   53716   assert( sqlite3_mutex_held(p->db->mutex) );
   53717   sqlite3BtreeEnter(p);
   53718   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
   53719   sqlite3BtreeLeave(p);
   53720   return SQLITE_OK;
   53721 }
   53722 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   53723 
   53724 /*
   53725 ** Change the way data is synced to disk in order to increase or decrease
   53726 ** how well the database resists damage due to OS crashes and power
   53727 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
   53728 ** there is a high probability of damage)  Level 2 is the default.  There
   53729 ** is a very low but non-zero probability of damage.  Level 3 reduces the
   53730 ** probability of damage to near zero but with a write performance reduction.
   53731 */
   53732 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   53733 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
   53734   Btree *p,              /* The btree to set the safety level on */
   53735   unsigned pgFlags       /* Various PAGER_* flags */
   53736 ){
   53737   BtShared *pBt = p->pBt;
   53738   assert( sqlite3_mutex_held(p->db->mutex) );
   53739   sqlite3BtreeEnter(p);
   53740   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
   53741   sqlite3BtreeLeave(p);
   53742   return SQLITE_OK;
   53743 }
   53744 #endif
   53745 
   53746 /*
   53747 ** Return TRUE if the given btree is set to safety level 1.  In other
   53748 ** words, return TRUE if no sync() occurs on the disk files.
   53749 */
   53750 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
   53751   BtShared *pBt = p->pBt;
   53752   int rc;
   53753   assert( sqlite3_mutex_held(p->db->mutex) );
   53754   sqlite3BtreeEnter(p);
   53755   assert( pBt && pBt->pPager );
   53756   rc = sqlite3PagerNosync(pBt->pPager);
   53757   sqlite3BtreeLeave(p);
   53758   return rc;
   53759 }
   53760 
   53761 /*
   53762 ** Change the default pages size and the number of reserved bytes per page.
   53763 ** Or, if the page size has already been fixed, return SQLITE_READONLY
   53764 ** without changing anything.
   53765 **
   53766 ** The page size must be a power of 2 between 512 and 65536.  If the page
   53767 ** size supplied does not meet this constraint then the page size is not
   53768 ** changed.
   53769 **
   53770 ** Page sizes are constrained to be a power of two so that the region
   53771 ** of the database file used for locking (beginning at PENDING_BYTE,
   53772 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
   53773 ** at the beginning of a page.
   53774 **
   53775 ** If parameter nReserve is less than zero, then the number of reserved
   53776 ** bytes per page is left unchanged.
   53777 **
   53778 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
   53779 ** and autovacuum mode can no longer be changed.
   53780 */
   53781 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
   53782   int rc = SQLITE_OK;
   53783   BtShared *pBt = p->pBt;
   53784   assert( nReserve>=-1 && nReserve<=255 );
   53785   sqlite3BtreeEnter(p);
   53786   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
   53787     sqlite3BtreeLeave(p);
   53788     return SQLITE_READONLY;
   53789   }
   53790   if( nReserve<0 ){
   53791     nReserve = pBt->pageSize - pBt->usableSize;
   53792   }
   53793   assert( nReserve>=0 && nReserve<=255 );
   53794   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
   53795         ((pageSize-1)&pageSize)==0 ){
   53796     assert( (pageSize & 7)==0 );
   53797     assert( !pBt->pPage1 && !pBt->pCursor );
   53798     pBt->pageSize = (u32)pageSize;
   53799     freeTempSpace(pBt);
   53800   }
   53801   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   53802   pBt->usableSize = pBt->pageSize - (u16)nReserve;
   53803   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   53804   sqlite3BtreeLeave(p);
   53805   return rc;
   53806 }
   53807 
   53808 /*
   53809 ** Return the currently defined page size
   53810 */
   53811 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
   53812   return p->pBt->pageSize;
   53813 }
   53814 
   53815 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
   53816 /*
   53817 ** This function is similar to sqlite3BtreeGetReserve(), except that it
   53818 ** may only be called if it is guaranteed that the b-tree mutex is already
   53819 ** held.
   53820 **
   53821 ** This is useful in one special case in the backup API code where it is
   53822 ** known that the shared b-tree mutex is held, but the mutex on the
   53823 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
   53824 ** were to be called, it might collide with some other operation on the
   53825 ** database handle that owns *p, causing undefined behavior.
   53826 */
   53827 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
   53828   assert( sqlite3_mutex_held(p->pBt->mutex) );
   53829   return p->pBt->pageSize - p->pBt->usableSize;
   53830 }
   53831 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
   53832 
   53833 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
   53834 /*
   53835 ** Return the number of bytes of space at the end of every page that
   53836 ** are intentually left unused.  This is the "reserved" space that is
   53837 ** sometimes used by extensions.
   53838 */
   53839 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
   53840   int n;
   53841   sqlite3BtreeEnter(p);
   53842   n = p->pBt->pageSize - p->pBt->usableSize;
   53843   sqlite3BtreeLeave(p);
   53844   return n;
   53845 }
   53846 
   53847 /*
   53848 ** Set the maximum page count for a database if mxPage is positive.
   53849 ** No changes are made if mxPage is 0 or negative.
   53850 ** Regardless of the value of mxPage, return the maximum page count.
   53851 */
   53852 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
   53853   int n;
   53854   sqlite3BtreeEnter(p);
   53855   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
   53856   sqlite3BtreeLeave(p);
   53857   return n;
   53858 }
   53859 
   53860 /*
   53861 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
   53862 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
   53863 ** setting after the change.
   53864 */
   53865 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
   53866   int b;
   53867   if( p==0 ) return 0;
   53868   sqlite3BtreeEnter(p);
   53869   if( newFlag>=0 ){
   53870     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
   53871     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
   53872   }
   53873   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
   53874   sqlite3BtreeLeave(p);
   53875   return b;
   53876 }
   53877 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
   53878 
   53879 /*
   53880 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
   53881 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
   53882 ** is disabled. The default value for the auto-vacuum property is
   53883 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
   53884 */
   53885 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
   53886 #ifdef SQLITE_OMIT_AUTOVACUUM
   53887   return SQLITE_READONLY;
   53888 #else
   53889   BtShared *pBt = p->pBt;
   53890   int rc = SQLITE_OK;
   53891   u8 av = (u8)autoVacuum;
   53892 
   53893   sqlite3BtreeEnter(p);
   53894   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
   53895     rc = SQLITE_READONLY;
   53896   }else{
   53897     pBt->autoVacuum = av ?1:0;
   53898     pBt->incrVacuum = av==2 ?1:0;
   53899   }
   53900   sqlite3BtreeLeave(p);
   53901   return rc;
   53902 #endif
   53903 }
   53904 
   53905 /*
   53906 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
   53907 ** enabled 1 is returned. Otherwise 0.
   53908 */
   53909 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
   53910 #ifdef SQLITE_OMIT_AUTOVACUUM
   53911   return BTREE_AUTOVACUUM_NONE;
   53912 #else
   53913   int rc;
   53914   sqlite3BtreeEnter(p);
   53915   rc = (
   53916     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
   53917     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
   53918     BTREE_AUTOVACUUM_INCR
   53919   );
   53920   sqlite3BtreeLeave(p);
   53921   return rc;
   53922 #endif
   53923 }
   53924 
   53925 
   53926 /*
   53927 ** Get a reference to pPage1 of the database file.  This will
   53928 ** also acquire a readlock on that file.
   53929 **
   53930 ** SQLITE_OK is returned on success.  If the file is not a
   53931 ** well-formed database file, then SQLITE_CORRUPT is returned.
   53932 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
   53933 ** is returned if we run out of memory.
   53934 */
   53935 static int lockBtree(BtShared *pBt){
   53936   int rc;              /* Result code from subfunctions */
   53937   MemPage *pPage1;     /* Page 1 of the database file */
   53938   int nPage;           /* Number of pages in the database */
   53939   int nPageFile = 0;   /* Number of pages in the database file */
   53940   int nPageHeader;     /* Number of pages in the database according to hdr */
   53941 
   53942   assert( sqlite3_mutex_held(pBt->mutex) );
   53943   assert( pBt->pPage1==0 );
   53944   rc = sqlite3PagerSharedLock(pBt->pPager);
   53945   if( rc!=SQLITE_OK ) return rc;
   53946   rc = btreeGetPage(pBt, 1, &pPage1, 0);
   53947   if( rc!=SQLITE_OK ) return rc;
   53948 
   53949   /* Do some checking to help insure the file we opened really is
   53950   ** a valid database file.
   53951   */
   53952   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
   53953   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
   53954   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
   53955     nPage = nPageFile;
   53956   }
   53957   if( nPage>0 ){
   53958     u32 pageSize;
   53959     u32 usableSize;
   53960     u8 *page1 = pPage1->aData;
   53961     rc = SQLITE_NOTADB;
   53962     if( memcmp(page1, zMagicHeader, 16)!=0 ){
   53963       goto page1_init_failed;
   53964     }
   53965 
   53966 #ifdef SQLITE_OMIT_WAL
   53967     if( page1[18]>1 ){
   53968       pBt->btsFlags |= BTS_READ_ONLY;
   53969     }
   53970     if( page1[19]>1 ){
   53971       goto page1_init_failed;
   53972     }
   53973 #else
   53974     if( page1[18]>2 ){
   53975       pBt->btsFlags |= BTS_READ_ONLY;
   53976     }
   53977     if( page1[19]>2 ){
   53978       goto page1_init_failed;
   53979     }
   53980 
   53981     /* If the write version is set to 2, this database should be accessed
   53982     ** in WAL mode. If the log is not already open, open it now. Then
   53983     ** return SQLITE_OK and return without populating BtShared.pPage1.
   53984     ** The caller detects this and calls this function again. This is
   53985     ** required as the version of page 1 currently in the page1 buffer
   53986     ** may not be the latest version - there may be a newer one in the log
   53987     ** file.
   53988     */
   53989     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
   53990       int isOpen = 0;
   53991       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
   53992       if( rc!=SQLITE_OK ){
   53993         goto page1_init_failed;
   53994       }else if( isOpen==0 ){
   53995         releasePage(pPage1);
   53996         return SQLITE_OK;
   53997       }
   53998       rc = SQLITE_NOTADB;
   53999     }
   54000 #endif
   54001 
   54002     /* The maximum embedded fraction must be exactly 25%.  And the minimum
   54003     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
   54004     ** The original design allowed these amounts to vary, but as of
   54005     ** version 3.6.0, we require them to be fixed.
   54006     */
   54007     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
   54008       goto page1_init_failed;
   54009     }
   54010     pageSize = (page1[16]<<8) | (page1[17]<<16);
   54011     if( ((pageSize-1)&pageSize)!=0
   54012      || pageSize>SQLITE_MAX_PAGE_SIZE
   54013      || pageSize<=256
   54014     ){
   54015       goto page1_init_failed;
   54016     }
   54017     assert( (pageSize & 7)==0 );
   54018     usableSize = pageSize - page1[20];
   54019     if( (u32)pageSize!=pBt->pageSize ){
   54020       /* After reading the first page of the database assuming a page size
   54021       ** of BtShared.pageSize, we have discovered that the page-size is
   54022       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
   54023       ** zero and return SQLITE_OK. The caller will call this function
   54024       ** again with the correct page-size.
   54025       */
   54026       releasePage(pPage1);
   54027       pBt->usableSize = usableSize;
   54028       pBt->pageSize = pageSize;
   54029       freeTempSpace(pBt);
   54030       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
   54031                                    pageSize-usableSize);
   54032       return rc;
   54033     }
   54034     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
   54035       rc = SQLITE_CORRUPT_BKPT;
   54036       goto page1_init_failed;
   54037     }
   54038     if( usableSize<480 ){
   54039       goto page1_init_failed;
   54040     }
   54041     pBt->pageSize = pageSize;
   54042     pBt->usableSize = usableSize;
   54043 #ifndef SQLITE_OMIT_AUTOVACUUM
   54044     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
   54045     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
   54046 #endif
   54047   }
   54048 
   54049   /* maxLocal is the maximum amount of payload to store locally for
   54050   ** a cell.  Make sure it is small enough so that at least minFanout
   54051   ** cells can will fit on one page.  We assume a 10-byte page header.
   54052   ** Besides the payload, the cell must store:
   54053   **     2-byte pointer to the cell
   54054   **     4-byte child pointer
   54055   **     9-byte nKey value
   54056   **     4-byte nData value
   54057   **     4-byte overflow page pointer
   54058   ** So a cell consists of a 2-byte pointer, a header which is as much as
   54059   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
   54060   ** page pointer.
   54061   */
   54062   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
   54063   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
   54064   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
   54065   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
   54066   if( pBt->maxLocal>127 ){
   54067     pBt->max1bytePayload = 127;
   54068   }else{
   54069     pBt->max1bytePayload = (u8)pBt->maxLocal;
   54070   }
   54071   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
   54072   pBt->pPage1 = pPage1;
   54073   pBt->nPage = nPage;
   54074   return SQLITE_OK;
   54075 
   54076 page1_init_failed:
   54077   releasePage(pPage1);
   54078   pBt->pPage1 = 0;
   54079   return rc;
   54080 }
   54081 
   54082 #ifndef NDEBUG
   54083 /*
   54084 ** Return the number of cursors open on pBt. This is for use
   54085 ** in assert() expressions, so it is only compiled if NDEBUG is not
   54086 ** defined.
   54087 **
   54088 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
   54089 ** false then all cursors are counted.
   54090 **
   54091 ** For the purposes of this routine, a cursor is any cursor that
   54092 ** is capable of reading or writing to the databse.  Cursors that
   54093 ** have been tripped into the CURSOR_FAULT state are not counted.
   54094 */
   54095 static int countValidCursors(BtShared *pBt, int wrOnly){
   54096   BtCursor *pCur;
   54097   int r = 0;
   54098   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
   54099     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
   54100      && pCur->eState!=CURSOR_FAULT ) r++;
   54101   }
   54102   return r;
   54103 }
   54104 #endif
   54105 
   54106 /*
   54107 ** If there are no outstanding cursors and we are not in the middle
   54108 ** of a transaction but there is a read lock on the database, then
   54109 ** this routine unrefs the first page of the database file which
   54110 ** has the effect of releasing the read lock.
   54111 **
   54112 ** If there is a transaction in progress, this routine is a no-op.
   54113 */
   54114 static void unlockBtreeIfUnused(BtShared *pBt){
   54115   assert( sqlite3_mutex_held(pBt->mutex) );
   54116   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
   54117   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
   54118     assert( pBt->pPage1->aData );
   54119     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
   54120     assert( pBt->pPage1->aData );
   54121     releasePage(pBt->pPage1);
   54122     pBt->pPage1 = 0;
   54123   }
   54124 }
   54125 
   54126 /*
   54127 ** If pBt points to an empty file then convert that empty file
   54128 ** into a new empty database by initializing the first page of
   54129 ** the database.
   54130 */
   54131 static int newDatabase(BtShared *pBt){
   54132   MemPage *pP1;
   54133   unsigned char *data;
   54134   int rc;
   54135 
   54136   assert( sqlite3_mutex_held(pBt->mutex) );
   54137   if( pBt->nPage>0 ){
   54138     return SQLITE_OK;
   54139   }
   54140   pP1 = pBt->pPage1;
   54141   assert( pP1!=0 );
   54142   data = pP1->aData;
   54143   rc = sqlite3PagerWrite(pP1->pDbPage);
   54144   if( rc ) return rc;
   54145   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
   54146   assert( sizeof(zMagicHeader)==16 );
   54147   data[16] = (u8)((pBt->pageSize>>8)&0xff);
   54148   data[17] = (u8)((pBt->pageSize>>16)&0xff);
   54149   data[18] = 1;
   54150   data[19] = 1;
   54151   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
   54152   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
   54153   data[21] = 64;
   54154   data[22] = 32;
   54155   data[23] = 32;
   54156   memset(&data[24], 0, 100-24);
   54157   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
   54158   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   54159 #ifndef SQLITE_OMIT_AUTOVACUUM
   54160   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
   54161   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
   54162   put4byte(&data[36 + 4*4], pBt->autoVacuum);
   54163   put4byte(&data[36 + 7*4], pBt->incrVacuum);
   54164 #endif
   54165   pBt->nPage = 1;
   54166   data[31] = 1;
   54167   return SQLITE_OK;
   54168 }
   54169 
   54170 /*
   54171 ** Initialize the first page of the database file (creating a database
   54172 ** consisting of a single page and no schema objects). Return SQLITE_OK
   54173 ** if successful, or an SQLite error code otherwise.
   54174 */
   54175 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
   54176   int rc;
   54177   sqlite3BtreeEnter(p);
   54178   p->pBt->nPage = 0;
   54179   rc = newDatabase(p->pBt);
   54180   sqlite3BtreeLeave(p);
   54181   return rc;
   54182 }
   54183 
   54184 /*
   54185 ** Attempt to start a new transaction. A write-transaction
   54186 ** is started if the second argument is nonzero, otherwise a read-
   54187 ** transaction.  If the second argument is 2 or more and exclusive
   54188 ** transaction is started, meaning that no other process is allowed
   54189 ** to access the database.  A preexisting transaction may not be
   54190 ** upgraded to exclusive by calling this routine a second time - the
   54191 ** exclusivity flag only works for a new transaction.
   54192 **
   54193 ** A write-transaction must be started before attempting any
   54194 ** changes to the database.  None of the following routines
   54195 ** will work unless a transaction is started first:
   54196 **
   54197 **      sqlite3BtreeCreateTable()
   54198 **      sqlite3BtreeCreateIndex()
   54199 **      sqlite3BtreeClearTable()
   54200 **      sqlite3BtreeDropTable()
   54201 **      sqlite3BtreeInsert()
   54202 **      sqlite3BtreeDelete()
   54203 **      sqlite3BtreeUpdateMeta()
   54204 **
   54205 ** If an initial attempt to acquire the lock fails because of lock contention
   54206 ** and the database was previously unlocked, then invoke the busy handler
   54207 ** if there is one.  But if there was previously a read-lock, do not
   54208 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
   54209 ** returned when there is already a read-lock in order to avoid a deadlock.
   54210 **
   54211 ** Suppose there are two processes A and B.  A has a read lock and B has
   54212 ** a reserved lock.  B tries to promote to exclusive but is blocked because
   54213 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
   54214 ** One or the other of the two processes must give way or there can be
   54215 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
   54216 ** when A already has a read lock, we encourage A to give up and let B
   54217 ** proceed.
   54218 */
   54219 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
   54220   sqlite3 *pBlock = 0;
   54221   BtShared *pBt = p->pBt;
   54222   int rc = SQLITE_OK;
   54223 
   54224   sqlite3BtreeEnter(p);
   54225   btreeIntegrity(p);
   54226 
   54227   /* If the btree is already in a write-transaction, or it
   54228   ** is already in a read-transaction and a read-transaction
   54229   ** is requested, this is a no-op.
   54230   */
   54231   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
   54232     goto trans_begun;
   54233   }
   54234   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
   54235 
   54236   /* Write transactions are not possible on a read-only database */
   54237   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
   54238     rc = SQLITE_READONLY;
   54239     goto trans_begun;
   54240   }
   54241 
   54242 #ifndef SQLITE_OMIT_SHARED_CACHE
   54243   /* If another database handle has already opened a write transaction
   54244   ** on this shared-btree structure and a second write transaction is
   54245   ** requested, return SQLITE_LOCKED.
   54246   */
   54247   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
   54248    || (pBt->btsFlags & BTS_PENDING)!=0
   54249   ){
   54250     pBlock = pBt->pWriter->db;
   54251   }else if( wrflag>1 ){
   54252     BtLock *pIter;
   54253     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   54254       if( pIter->pBtree!=p ){
   54255         pBlock = pIter->pBtree->db;
   54256         break;
   54257       }
   54258     }
   54259   }
   54260   if( pBlock ){
   54261     sqlite3ConnectionBlocked(p->db, pBlock);
   54262     rc = SQLITE_LOCKED_SHAREDCACHE;
   54263     goto trans_begun;
   54264   }
   54265 #endif
   54266 
   54267   /* Any read-only or read-write transaction implies a read-lock on
   54268   ** page 1. So if some other shared-cache client already has a write-lock
   54269   ** on page 1, the transaction cannot be opened. */
   54270   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   54271   if( SQLITE_OK!=rc ) goto trans_begun;
   54272 
   54273   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
   54274   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
   54275   do {
   54276     /* Call lockBtree() until either pBt->pPage1 is populated or
   54277     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
   54278     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
   54279     ** reading page 1 it discovers that the page-size of the database
   54280     ** file is not pBt->pageSize. In this case lockBtree() will update
   54281     ** pBt->pageSize to the page-size of the file on disk.
   54282     */
   54283     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
   54284 
   54285     if( rc==SQLITE_OK && wrflag ){
   54286       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
   54287         rc = SQLITE_READONLY;
   54288       }else{
   54289         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
   54290         if( rc==SQLITE_OK ){
   54291           rc = newDatabase(pBt);
   54292         }
   54293       }
   54294     }
   54295 
   54296     if( rc!=SQLITE_OK ){
   54297       unlockBtreeIfUnused(pBt);
   54298     }
   54299   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
   54300           btreeInvokeBusyHandler(pBt) );
   54301 
   54302   if( rc==SQLITE_OK ){
   54303     if( p->inTrans==TRANS_NONE ){
   54304       pBt->nTransaction++;
   54305 #ifndef SQLITE_OMIT_SHARED_CACHE
   54306       if( p->sharable ){
   54307         assert( p->lock.pBtree==p && p->lock.iTable==1 );
   54308         p->lock.eLock = READ_LOCK;
   54309         p->lock.pNext = pBt->pLock;
   54310         pBt->pLock = &p->lock;
   54311       }
   54312 #endif
   54313     }
   54314     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
   54315     if( p->inTrans>pBt->inTransaction ){
   54316       pBt->inTransaction = p->inTrans;
   54317     }
   54318     if( wrflag ){
   54319       MemPage *pPage1 = pBt->pPage1;
   54320 #ifndef SQLITE_OMIT_SHARED_CACHE
   54321       assert( !pBt->pWriter );
   54322       pBt->pWriter = p;
   54323       pBt->btsFlags &= ~BTS_EXCLUSIVE;
   54324       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
   54325 #endif
   54326 
   54327       /* If the db-size header field is incorrect (as it may be if an old
   54328       ** client has been writing the database file), update it now. Doing
   54329       ** this sooner rather than later means the database size can safely
   54330       ** re-read the database size from page 1 if a savepoint or transaction
   54331       ** rollback occurs within the transaction.
   54332       */
   54333       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
   54334         rc = sqlite3PagerWrite(pPage1->pDbPage);
   54335         if( rc==SQLITE_OK ){
   54336           put4byte(&pPage1->aData[28], pBt->nPage);
   54337         }
   54338       }
   54339     }
   54340   }
   54341 
   54342 
   54343 trans_begun:
   54344   if( rc==SQLITE_OK && wrflag ){
   54345     /* This call makes sure that the pager has the correct number of
   54346     ** open savepoints. If the second parameter is greater than 0 and
   54347     ** the sub-journal is not already open, then it will be opened here.
   54348     */
   54349     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
   54350   }
   54351 
   54352   btreeIntegrity(p);
   54353   sqlite3BtreeLeave(p);
   54354   return rc;
   54355 }
   54356 
   54357 #ifndef SQLITE_OMIT_AUTOVACUUM
   54358 
   54359 /*
   54360 ** Set the pointer-map entries for all children of page pPage. Also, if
   54361 ** pPage contains cells that point to overflow pages, set the pointer
   54362 ** map entries for the overflow pages as well.
   54363 */
   54364 static int setChildPtrmaps(MemPage *pPage){
   54365   int i;                             /* Counter variable */
   54366   int nCell;                         /* Number of cells in page pPage */
   54367   int rc;                            /* Return code */
   54368   BtShared *pBt = pPage->pBt;
   54369   u8 isInitOrig = pPage->isInit;
   54370   Pgno pgno = pPage->pgno;
   54371 
   54372   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54373   rc = btreeInitPage(pPage);
   54374   if( rc!=SQLITE_OK ){
   54375     goto set_child_ptrmaps_out;
   54376   }
   54377   nCell = pPage->nCell;
   54378 
   54379   for(i=0; i<nCell; i++){
   54380     u8 *pCell = findCell(pPage, i);
   54381 
   54382     ptrmapPutOvflPtr(pPage, pCell, &rc);
   54383 
   54384     if( !pPage->leaf ){
   54385       Pgno childPgno = get4byte(pCell);
   54386       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   54387     }
   54388   }
   54389 
   54390   if( !pPage->leaf ){
   54391     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   54392     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   54393   }
   54394 
   54395 set_child_ptrmaps_out:
   54396   pPage->isInit = isInitOrig;
   54397   return rc;
   54398 }
   54399 
   54400 /*
   54401 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
   54402 ** that it points to iTo. Parameter eType describes the type of pointer to
   54403 ** be modified, as  follows:
   54404 **
   54405 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
   54406 **                   page of pPage.
   54407 **
   54408 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
   54409 **                   page pointed to by one of the cells on pPage.
   54410 **
   54411 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
   54412 **                   overflow page in the list.
   54413 */
   54414 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
   54415   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54416   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   54417   if( eType==PTRMAP_OVERFLOW2 ){
   54418     /* The pointer is always the first 4 bytes of the page in this case.  */
   54419     if( get4byte(pPage->aData)!=iFrom ){
   54420       return SQLITE_CORRUPT_BKPT;
   54421     }
   54422     put4byte(pPage->aData, iTo);
   54423   }else{
   54424     u8 isInitOrig = pPage->isInit;
   54425     int i;
   54426     int nCell;
   54427 
   54428     btreeInitPage(pPage);
   54429     nCell = pPage->nCell;
   54430 
   54431     for(i=0; i<nCell; i++){
   54432       u8 *pCell = findCell(pPage, i);
   54433       if( eType==PTRMAP_OVERFLOW1 ){
   54434         CellInfo info;
   54435         btreeParseCellPtr(pPage, pCell, &info);
   54436         if( info.iOverflow
   54437          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
   54438          && iFrom==get4byte(&pCell[info.iOverflow])
   54439         ){
   54440           put4byte(&pCell[info.iOverflow], iTo);
   54441           break;
   54442         }
   54443       }else{
   54444         if( get4byte(pCell)==iFrom ){
   54445           put4byte(pCell, iTo);
   54446           break;
   54447         }
   54448       }
   54449     }
   54450 
   54451     if( i==nCell ){
   54452       if( eType!=PTRMAP_BTREE ||
   54453           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
   54454         return SQLITE_CORRUPT_BKPT;
   54455       }
   54456       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
   54457     }
   54458 
   54459     pPage->isInit = isInitOrig;
   54460   }
   54461   return SQLITE_OK;
   54462 }
   54463 
   54464 
   54465 /*
   54466 ** Move the open database page pDbPage to location iFreePage in the
   54467 ** database. The pDbPage reference remains valid.
   54468 **
   54469 ** The isCommit flag indicates that there is no need to remember that
   54470 ** the journal needs to be sync()ed before database page pDbPage->pgno
   54471 ** can be written to. The caller has already promised not to write to that
   54472 ** page.
   54473 */
   54474 static int relocatePage(
   54475   BtShared *pBt,           /* Btree */
   54476   MemPage *pDbPage,        /* Open page to move */
   54477   u8 eType,                /* Pointer map 'type' entry for pDbPage */
   54478   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
   54479   Pgno iFreePage,          /* The location to move pDbPage to */
   54480   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
   54481 ){
   54482   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
   54483   Pgno iDbPage = pDbPage->pgno;
   54484   Pager *pPager = pBt->pPager;
   54485   int rc;
   54486 
   54487   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
   54488       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
   54489   assert( sqlite3_mutex_held(pBt->mutex) );
   54490   assert( pDbPage->pBt==pBt );
   54491 
   54492   /* Move page iDbPage from its current location to page number iFreePage */
   54493   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
   54494       iDbPage, iFreePage, iPtrPage, eType));
   54495   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
   54496   if( rc!=SQLITE_OK ){
   54497     return rc;
   54498   }
   54499   pDbPage->pgno = iFreePage;
   54500 
   54501   /* If pDbPage was a btree-page, then it may have child pages and/or cells
   54502   ** that point to overflow pages. The pointer map entries for all these
   54503   ** pages need to be changed.
   54504   **
   54505   ** If pDbPage is an overflow page, then the first 4 bytes may store a
   54506   ** pointer to a subsequent overflow page. If this is the case, then
   54507   ** the pointer map needs to be updated for the subsequent overflow page.
   54508   */
   54509   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
   54510     rc = setChildPtrmaps(pDbPage);
   54511     if( rc!=SQLITE_OK ){
   54512       return rc;
   54513     }
   54514   }else{
   54515     Pgno nextOvfl = get4byte(pDbPage->aData);
   54516     if( nextOvfl!=0 ){
   54517       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
   54518       if( rc!=SQLITE_OK ){
   54519         return rc;
   54520       }
   54521     }
   54522   }
   54523 
   54524   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
   54525   ** that it points at iFreePage. Also fix the pointer map entry for
   54526   ** iPtrPage.
   54527   */
   54528   if( eType!=PTRMAP_ROOTPAGE ){
   54529     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
   54530     if( rc!=SQLITE_OK ){
   54531       return rc;
   54532     }
   54533     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
   54534     if( rc!=SQLITE_OK ){
   54535       releasePage(pPtrPage);
   54536       return rc;
   54537     }
   54538     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
   54539     releasePage(pPtrPage);
   54540     if( rc==SQLITE_OK ){
   54541       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
   54542     }
   54543   }
   54544   return rc;
   54545 }
   54546 
   54547 /* Forward declaration required by incrVacuumStep(). */
   54548 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
   54549 
   54550 /*
   54551 ** Perform a single step of an incremental-vacuum. If successful, return
   54552 ** SQLITE_OK. If there is no work to do (and therefore no point in
   54553 ** calling this function again), return SQLITE_DONE. Or, if an error
   54554 ** occurs, return some other error code.
   54555 **
   54556 ** More specificly, this function attempts to re-organize the database so
   54557 ** that the last page of the file currently in use is no longer in use.
   54558 **
   54559 ** Parameter nFin is the number of pages that this database would contain
   54560 ** were this function called until it returns SQLITE_DONE.
   54561 **
   54562 ** If the bCommit parameter is non-zero, this function assumes that the
   54563 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
   54564 ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
   54565 ** operation, or false for an incremental vacuum.
   54566 */
   54567 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
   54568   Pgno nFreeList;           /* Number of pages still on the free-list */
   54569   int rc;
   54570 
   54571   assert( sqlite3_mutex_held(pBt->mutex) );
   54572   assert( iLastPg>nFin );
   54573 
   54574   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
   54575     u8 eType;
   54576     Pgno iPtrPage;
   54577 
   54578     nFreeList = get4byte(&pBt->pPage1->aData[36]);
   54579     if( nFreeList==0 ){
   54580       return SQLITE_DONE;
   54581     }
   54582 
   54583     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
   54584     if( rc!=SQLITE_OK ){
   54585       return rc;
   54586     }
   54587     if( eType==PTRMAP_ROOTPAGE ){
   54588       return SQLITE_CORRUPT_BKPT;
   54589     }
   54590 
   54591     if( eType==PTRMAP_FREEPAGE ){
   54592       if( bCommit==0 ){
   54593         /* Remove the page from the files free-list. This is not required
   54594         ** if bCommit is non-zero. In that case, the free-list will be
   54595         ** truncated to zero after this function returns, so it doesn't
   54596         ** matter if it still contains some garbage entries.
   54597         */
   54598         Pgno iFreePg;
   54599         MemPage *pFreePg;
   54600         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
   54601         if( rc!=SQLITE_OK ){
   54602           return rc;
   54603         }
   54604         assert( iFreePg==iLastPg );
   54605         releasePage(pFreePg);
   54606       }
   54607     } else {
   54608       Pgno iFreePg;             /* Index of free page to move pLastPg to */
   54609       MemPage *pLastPg;
   54610       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
   54611       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
   54612 
   54613       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
   54614       if( rc!=SQLITE_OK ){
   54615         return rc;
   54616       }
   54617 
   54618       /* If bCommit is zero, this loop runs exactly once and page pLastPg
   54619       ** is swapped with the first free page pulled off the free list.
   54620       **
   54621       ** On the other hand, if bCommit is greater than zero, then keep
   54622       ** looping until a free-page located within the first nFin pages
   54623       ** of the file is found.
   54624       */
   54625       if( bCommit==0 ){
   54626         eMode = BTALLOC_LE;
   54627         iNear = nFin;
   54628       }
   54629       do {
   54630         MemPage *pFreePg;
   54631         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
   54632         if( rc!=SQLITE_OK ){
   54633           releasePage(pLastPg);
   54634           return rc;
   54635         }
   54636         releasePage(pFreePg);
   54637       }while( bCommit && iFreePg>nFin );
   54638       assert( iFreePg<iLastPg );
   54639 
   54640       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
   54641       releasePage(pLastPg);
   54642       if( rc!=SQLITE_OK ){
   54643         return rc;
   54644       }
   54645     }
   54646   }
   54647 
   54648   if( bCommit==0 ){
   54649     do {
   54650       iLastPg--;
   54651     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
   54652     pBt->bDoTruncate = 1;
   54653     pBt->nPage = iLastPg;
   54654   }
   54655   return SQLITE_OK;
   54656 }
   54657 
   54658 /*
   54659 ** The database opened by the first argument is an auto-vacuum database
   54660 ** nOrig pages in size containing nFree free pages. Return the expected
   54661 ** size of the database in pages following an auto-vacuum operation.
   54662 */
   54663 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
   54664   int nEntry;                     /* Number of entries on one ptrmap page */
   54665   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
   54666   Pgno nFin;                      /* Return value */
   54667 
   54668   nEntry = pBt->usableSize/5;
   54669   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
   54670   nFin = nOrig - nFree - nPtrmap;
   54671   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
   54672     nFin--;
   54673   }
   54674   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
   54675     nFin--;
   54676   }
   54677 
   54678   return nFin;
   54679 }
   54680 
   54681 /*
   54682 ** A write-transaction must be opened before calling this function.
   54683 ** It performs a single unit of work towards an incremental vacuum.
   54684 **
   54685 ** If the incremental vacuum is finished after this function has run,
   54686 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
   54687 ** SQLITE_OK is returned. Otherwise an SQLite error code.
   54688 */
   54689 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
   54690   int rc;
   54691   BtShared *pBt = p->pBt;
   54692 
   54693   sqlite3BtreeEnter(p);
   54694   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
   54695   if( !pBt->autoVacuum ){
   54696     rc = SQLITE_DONE;
   54697   }else{
   54698     Pgno nOrig = btreePagecount(pBt);
   54699     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
   54700     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
   54701 
   54702     if( nOrig<nFin ){
   54703       rc = SQLITE_CORRUPT_BKPT;
   54704     }else if( nFree>0 ){
   54705       rc = saveAllCursors(pBt, 0, 0);
   54706       if( rc==SQLITE_OK ){
   54707         invalidateAllOverflowCache(pBt);
   54708         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
   54709       }
   54710       if( rc==SQLITE_OK ){
   54711         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   54712         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
   54713       }
   54714     }else{
   54715       rc = SQLITE_DONE;
   54716     }
   54717   }
   54718   sqlite3BtreeLeave(p);
   54719   return rc;
   54720 }
   54721 
   54722 /*
   54723 ** This routine is called prior to sqlite3PagerCommit when a transaction
   54724 ** is committed for an auto-vacuum database.
   54725 **
   54726 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
   54727 ** the database file should be truncated to during the commit process.
   54728 ** i.e. the database has been reorganized so that only the first *pnTrunc
   54729 ** pages are in use.
   54730 */
   54731 static int autoVacuumCommit(BtShared *pBt){
   54732   int rc = SQLITE_OK;
   54733   Pager *pPager = pBt->pPager;
   54734   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
   54735 
   54736   assert( sqlite3_mutex_held(pBt->mutex) );
   54737   invalidateAllOverflowCache(pBt);
   54738   assert(pBt->autoVacuum);
   54739   if( !pBt->incrVacuum ){
   54740     Pgno nFin;         /* Number of pages in database after autovacuuming */
   54741     Pgno nFree;        /* Number of pages on the freelist initially */
   54742     Pgno iFree;        /* The next page to be freed */
   54743     Pgno nOrig;        /* Database size before freeing */
   54744 
   54745     nOrig = btreePagecount(pBt);
   54746     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
   54747       /* It is not possible to create a database for which the final page
   54748       ** is either a pointer-map page or the pending-byte page. If one
   54749       ** is encountered, this indicates corruption.
   54750       */
   54751       return SQLITE_CORRUPT_BKPT;
   54752     }
   54753 
   54754     nFree = get4byte(&pBt->pPage1->aData[36]);
   54755     nFin = finalDbSize(pBt, nOrig, nFree);
   54756     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
   54757     if( nFin<nOrig ){
   54758       rc = saveAllCursors(pBt, 0, 0);
   54759     }
   54760     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
   54761       rc = incrVacuumStep(pBt, nFin, iFree, 1);
   54762     }
   54763     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
   54764       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   54765       put4byte(&pBt->pPage1->aData[32], 0);
   54766       put4byte(&pBt->pPage1->aData[36], 0);
   54767       put4byte(&pBt->pPage1->aData[28], nFin);
   54768       pBt->bDoTruncate = 1;
   54769       pBt->nPage = nFin;
   54770     }
   54771     if( rc!=SQLITE_OK ){
   54772       sqlite3PagerRollback(pPager);
   54773     }
   54774   }
   54775 
   54776   assert( nRef>=sqlite3PagerRefcount(pPager) );
   54777   return rc;
   54778 }
   54779 
   54780 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
   54781 # define setChildPtrmaps(x) SQLITE_OK
   54782 #endif
   54783 
   54784 /*
   54785 ** This routine does the first phase of a two-phase commit.  This routine
   54786 ** causes a rollback journal to be created (if it does not already exist)
   54787 ** and populated with enough information so that if a power loss occurs
   54788 ** the database can be restored to its original state by playing back
   54789 ** the journal.  Then the contents of the journal are flushed out to
   54790 ** the disk.  After the journal is safely on oxide, the changes to the
   54791 ** database are written into the database file and flushed to oxide.
   54792 ** At the end of this call, the rollback journal still exists on the
   54793 ** disk and we are still holding all locks, so the transaction has not
   54794 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
   54795 ** commit process.
   54796 **
   54797 ** This call is a no-op if no write-transaction is currently active on pBt.
   54798 **
   54799 ** Otherwise, sync the database file for the btree pBt. zMaster points to
   54800 ** the name of a master journal file that should be written into the
   54801 ** individual journal file, or is NULL, indicating no master journal file
   54802 ** (single database transaction).
   54803 **
   54804 ** When this is called, the master journal should already have been
   54805 ** created, populated with this journal pointer and synced to disk.
   54806 **
   54807 ** Once this is routine has returned, the only thing required to commit
   54808 ** the write-transaction for this database file is to delete the journal.
   54809 */
   54810 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
   54811   int rc = SQLITE_OK;
   54812   if( p->inTrans==TRANS_WRITE ){
   54813     BtShared *pBt = p->pBt;
   54814     sqlite3BtreeEnter(p);
   54815 #ifndef SQLITE_OMIT_AUTOVACUUM
   54816     if( pBt->autoVacuum ){
   54817       rc = autoVacuumCommit(pBt);
   54818       if( rc!=SQLITE_OK ){
   54819         sqlite3BtreeLeave(p);
   54820         return rc;
   54821       }
   54822     }
   54823     if( pBt->bDoTruncate ){
   54824       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
   54825     }
   54826 #endif
   54827     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
   54828     sqlite3BtreeLeave(p);
   54829   }
   54830   return rc;
   54831 }
   54832 
   54833 /*
   54834 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
   54835 ** at the conclusion of a transaction.
   54836 */
   54837 static void btreeEndTransaction(Btree *p){
   54838   BtShared *pBt = p->pBt;
   54839   sqlite3 *db = p->db;
   54840   assert( sqlite3BtreeHoldsMutex(p) );
   54841 
   54842 #ifndef SQLITE_OMIT_AUTOVACUUM
   54843   pBt->bDoTruncate = 0;
   54844 #endif
   54845   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
   54846     /* If there are other active statements that belong to this database
   54847     ** handle, downgrade to a read-only transaction. The other statements
   54848     ** may still be reading from the database.  */
   54849     downgradeAllSharedCacheTableLocks(p);
   54850     p->inTrans = TRANS_READ;
   54851   }else{
   54852     /* If the handle had any kind of transaction open, decrement the
   54853     ** transaction count of the shared btree. If the transaction count
   54854     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
   54855     ** call below will unlock the pager.  */
   54856     if( p->inTrans!=TRANS_NONE ){
   54857       clearAllSharedCacheTableLocks(p);
   54858       pBt->nTransaction--;
   54859       if( 0==pBt->nTransaction ){
   54860         pBt->inTransaction = TRANS_NONE;
   54861       }
   54862     }
   54863 
   54864     /* Set the current transaction state to TRANS_NONE and unlock the
   54865     ** pager if this call closed the only read or write transaction.  */
   54866     p->inTrans = TRANS_NONE;
   54867     unlockBtreeIfUnused(pBt);
   54868   }
   54869 
   54870   btreeIntegrity(p);
   54871 }
   54872 
   54873 /*
   54874 ** Commit the transaction currently in progress.
   54875 **
   54876 ** This routine implements the second phase of a 2-phase commit.  The
   54877 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
   54878 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
   54879 ** routine did all the work of writing information out to disk and flushing the
   54880 ** contents so that they are written onto the disk platter.  All this
   54881 ** routine has to do is delete or truncate or zero the header in the
   54882 ** the rollback journal (which causes the transaction to commit) and
   54883 ** drop locks.
   54884 **
   54885 ** Normally, if an error occurs while the pager layer is attempting to
   54886 ** finalize the underlying journal file, this function returns an error and
   54887 ** the upper layer will attempt a rollback. However, if the second argument
   54888 ** is non-zero then this b-tree transaction is part of a multi-file
   54889 ** transaction. In this case, the transaction has already been committed
   54890 ** (by deleting a master journal file) and the caller will ignore this
   54891 ** functions return code. So, even if an error occurs in the pager layer,
   54892 ** reset the b-tree objects internal state to indicate that the write
   54893 ** transaction has been closed. This is quite safe, as the pager will have
   54894 ** transitioned to the error state.
   54895 **
   54896 ** This will release the write lock on the database file.  If there
   54897 ** are no active cursors, it also releases the read lock.
   54898 */
   54899 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
   54900 
   54901   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
   54902   sqlite3BtreeEnter(p);
   54903   btreeIntegrity(p);
   54904 
   54905   /* If the handle has a write-transaction open, commit the shared-btrees
   54906   ** transaction and set the shared state to TRANS_READ.
   54907   */
   54908   if( p->inTrans==TRANS_WRITE ){
   54909     int rc;
   54910     BtShared *pBt = p->pBt;
   54911     assert( pBt->inTransaction==TRANS_WRITE );
   54912     assert( pBt->nTransaction>0 );
   54913     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
   54914     if( rc!=SQLITE_OK && bCleanup==0 ){
   54915       sqlite3BtreeLeave(p);
   54916       return rc;
   54917     }
   54918     pBt->inTransaction = TRANS_READ;
   54919     btreeClearHasContent(pBt);
   54920   }
   54921 
   54922   btreeEndTransaction(p);
   54923   sqlite3BtreeLeave(p);
   54924   return SQLITE_OK;
   54925 }
   54926 
   54927 /*
   54928 ** Do both phases of a commit.
   54929 */
   54930 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
   54931   int rc;
   54932   sqlite3BtreeEnter(p);
   54933   rc = sqlite3BtreeCommitPhaseOne(p, 0);
   54934   if( rc==SQLITE_OK ){
   54935     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
   54936   }
   54937   sqlite3BtreeLeave(p);
   54938   return rc;
   54939 }
   54940 
   54941 /*
   54942 ** This routine sets the state to CURSOR_FAULT and the error
   54943 ** code to errCode for every cursor on BtShared that pBtree
   54944 ** references.
   54945 **
   54946 ** Every cursor is tripped, including cursors that belong
   54947 ** to other database connections that happen to be sharing
   54948 ** the cache with pBtree.
   54949 **
   54950 ** This routine gets called when a rollback occurs.
   54951 ** All cursors using the same cache must be tripped
   54952 ** to prevent them from trying to use the btree after
   54953 ** the rollback.  The rollback may have deleted tables
   54954 ** or moved root pages, so it is not sufficient to
   54955 ** save the state of the cursor.  The cursor must be
   54956 ** invalidated.
   54957 */
   54958 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
   54959   BtCursor *p;
   54960   if( pBtree==0 ) return;
   54961   sqlite3BtreeEnter(pBtree);
   54962   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   54963     int i;
   54964     sqlite3BtreeClearCursor(p);
   54965     p->eState = CURSOR_FAULT;
   54966     p->skipNext = errCode;
   54967     for(i=0; i<=p->iPage; i++){
   54968       releasePage(p->apPage[i]);
   54969       p->apPage[i] = 0;
   54970     }
   54971   }
   54972   sqlite3BtreeLeave(pBtree);
   54973 }
   54974 
   54975 /*
   54976 ** Rollback the transaction in progress.  All cursors will be
   54977 ** invalided by this operation.  Any attempt to use a cursor
   54978 ** that was open at the beginning of this operation will result
   54979 ** in an error.
   54980 **
   54981 ** This will release the write lock on the database file.  If there
   54982 ** are no active cursors, it also releases the read lock.
   54983 */
   54984 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
   54985   int rc;
   54986   BtShared *pBt = p->pBt;
   54987   MemPage *pPage1;
   54988 
   54989   sqlite3BtreeEnter(p);
   54990   if( tripCode==SQLITE_OK ){
   54991     rc = tripCode = saveAllCursors(pBt, 0, 0);
   54992   }else{
   54993     rc = SQLITE_OK;
   54994   }
   54995   if( tripCode ){
   54996     sqlite3BtreeTripAllCursors(p, tripCode);
   54997   }
   54998   btreeIntegrity(p);
   54999 
   55000   if( p->inTrans==TRANS_WRITE ){
   55001     int rc2;
   55002 
   55003     assert( TRANS_WRITE==pBt->inTransaction );
   55004     rc2 = sqlite3PagerRollback(pBt->pPager);
   55005     if( rc2!=SQLITE_OK ){
   55006       rc = rc2;
   55007     }
   55008 
   55009     /* The rollback may have destroyed the pPage1->aData value.  So
   55010     ** call btreeGetPage() on page 1 again to make
   55011     ** sure pPage1->aData is set correctly. */
   55012     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
   55013       int nPage = get4byte(28+(u8*)pPage1->aData);
   55014       testcase( nPage==0 );
   55015       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
   55016       testcase( pBt->nPage!=nPage );
   55017       pBt->nPage = nPage;
   55018       releasePage(pPage1);
   55019     }
   55020     assert( countValidCursors(pBt, 1)==0 );
   55021     pBt->inTransaction = TRANS_READ;
   55022     btreeClearHasContent(pBt);
   55023   }
   55024 
   55025   btreeEndTransaction(p);
   55026   sqlite3BtreeLeave(p);
   55027   return rc;
   55028 }
   55029 
   55030 /*
   55031 ** Start a statement subtransaction. The subtransaction can can be rolled
   55032 ** back independently of the main transaction. You must start a transaction
   55033 ** before starting a subtransaction. The subtransaction is ended automatically
   55034 ** if the main transaction commits or rolls back.
   55035 **
   55036 ** Statement subtransactions are used around individual SQL statements
   55037 ** that are contained within a BEGIN...COMMIT block.  If a constraint
   55038 ** error occurs within the statement, the effect of that one statement
   55039 ** can be rolled back without having to rollback the entire transaction.
   55040 **
   55041 ** A statement sub-transaction is implemented as an anonymous savepoint. The
   55042 ** value passed as the second parameter is the total number of savepoints,
   55043 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
   55044 ** are no active savepoints and no other statement-transactions open,
   55045 ** iStatement is 1. This anonymous savepoint can be released or rolled back
   55046 ** using the sqlite3BtreeSavepoint() function.
   55047 */
   55048 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
   55049   int rc;
   55050   BtShared *pBt = p->pBt;
   55051   sqlite3BtreeEnter(p);
   55052   assert( p->inTrans==TRANS_WRITE );
   55053   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   55054   assert( iStatement>0 );
   55055   assert( iStatement>p->db->nSavepoint );
   55056   assert( pBt->inTransaction==TRANS_WRITE );
   55057   /* At the pager level, a statement transaction is a savepoint with
   55058   ** an index greater than all savepoints created explicitly using
   55059   ** SQL statements. It is illegal to open, release or rollback any
   55060   ** such savepoints while the statement transaction savepoint is active.
   55061   */
   55062   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
   55063   sqlite3BtreeLeave(p);
   55064   return rc;
   55065 }
   55066 
   55067 /*
   55068 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
   55069 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
   55070 ** savepoint identified by parameter iSavepoint, depending on the value
   55071 ** of op.
   55072 **
   55073 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
   55074 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
   55075 ** contents of the entire transaction are rolled back. This is different
   55076 ** from a normal transaction rollback, as no locks are released and the
   55077 ** transaction remains open.
   55078 */
   55079 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
   55080   int rc = SQLITE_OK;
   55081   if( p && p->inTrans==TRANS_WRITE ){
   55082     BtShared *pBt = p->pBt;
   55083     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   55084     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
   55085     sqlite3BtreeEnter(p);
   55086     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
   55087     if( rc==SQLITE_OK ){
   55088       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
   55089         pBt->nPage = 0;
   55090       }
   55091       rc = newDatabase(pBt);
   55092       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
   55093 
   55094       /* The database size was written into the offset 28 of the header
   55095       ** when the transaction started, so we know that the value at offset
   55096       ** 28 is nonzero. */
   55097       assert( pBt->nPage>0 );
   55098     }
   55099     sqlite3BtreeLeave(p);
   55100   }
   55101   return rc;
   55102 }
   55103 
   55104 /*
   55105 ** Create a new cursor for the BTree whose root is on the page
   55106 ** iTable. If a read-only cursor is requested, it is assumed that
   55107 ** the caller already has at least a read-only transaction open
   55108 ** on the database already. If a write-cursor is requested, then
   55109 ** the caller is assumed to have an open write transaction.
   55110 **
   55111 ** If wrFlag==0, then the cursor can only be used for reading.
   55112 ** If wrFlag==1, then the cursor can be used for reading or for
   55113 ** writing if other conditions for writing are also met.  These
   55114 ** are the conditions that must be met in order for writing to
   55115 ** be allowed:
   55116 **
   55117 ** 1:  The cursor must have been opened with wrFlag==1
   55118 **
   55119 ** 2:  Other database connections that share the same pager cache
   55120 **     but which are not in the READ_UNCOMMITTED state may not have
   55121 **     cursors open with wrFlag==0 on the same table.  Otherwise
   55122 **     the changes made by this write cursor would be visible to
   55123 **     the read cursors in the other database connection.
   55124 **
   55125 ** 3:  The database must be writable (not on read-only media)
   55126 **
   55127 ** 4:  There must be an active transaction.
   55128 **
   55129 ** No checking is done to make sure that page iTable really is the
   55130 ** root page of a b-tree.  If it is not, then the cursor acquired
   55131 ** will not work correctly.
   55132 **
   55133 ** It is assumed that the sqlite3BtreeCursorZero() has been called
   55134 ** on pCur to initialize the memory space prior to invoking this routine.
   55135 */
   55136 static int btreeCursor(
   55137   Btree *p,                              /* The btree */
   55138   int iTable,                            /* Root page of table to open */
   55139   int wrFlag,                            /* 1 to write. 0 read-only */
   55140   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
   55141   BtCursor *pCur                         /* Space for new cursor */
   55142 ){
   55143   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
   55144 
   55145   assert( sqlite3BtreeHoldsMutex(p) );
   55146   assert( wrFlag==0 || wrFlag==1 );
   55147 
   55148   /* The following assert statements verify that if this is a sharable
   55149   ** b-tree database, the connection is holding the required table locks,
   55150   ** and that no other connection has any open cursor that conflicts with
   55151   ** this lock.  */
   55152   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
   55153   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
   55154 
   55155   /* Assert that the caller has opened the required transaction. */
   55156   assert( p->inTrans>TRANS_NONE );
   55157   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
   55158   assert( pBt->pPage1 && pBt->pPage1->aData );
   55159 
   55160   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
   55161     return SQLITE_READONLY;
   55162   }
   55163   if( iTable==1 && btreePagecount(pBt)==0 ){
   55164     assert( wrFlag==0 );
   55165     iTable = 0;
   55166   }
   55167 
   55168   /* Now that no other errors can occur, finish filling in the BtCursor
   55169   ** variables and link the cursor into the BtShared list.  */
   55170   pCur->pgnoRoot = (Pgno)iTable;
   55171   pCur->iPage = -1;
   55172   pCur->pKeyInfo = pKeyInfo;
   55173   pCur->pBtree = p;
   55174   pCur->pBt = pBt;
   55175   assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
   55176   pCur->curFlags = wrFlag;
   55177   pCur->pNext = pBt->pCursor;
   55178   if( pCur->pNext ){
   55179     pCur->pNext->pPrev = pCur;
   55180   }
   55181   pBt->pCursor = pCur;
   55182   pCur->eState = CURSOR_INVALID;
   55183   return SQLITE_OK;
   55184 }
   55185 SQLITE_PRIVATE int sqlite3BtreeCursor(
   55186   Btree *p,                                   /* The btree */
   55187   int iTable,                                 /* Root page of table to open */
   55188   int wrFlag,                                 /* 1 to write. 0 read-only */
   55189   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
   55190   BtCursor *pCur                              /* Write new cursor here */
   55191 ){
   55192   int rc;
   55193   sqlite3BtreeEnter(p);
   55194   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
   55195   sqlite3BtreeLeave(p);
   55196   return rc;
   55197 }
   55198 
   55199 /*
   55200 ** Return the size of a BtCursor object in bytes.
   55201 **
   55202 ** This interfaces is needed so that users of cursors can preallocate
   55203 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
   55204 ** to users so they cannot do the sizeof() themselves - they must call
   55205 ** this routine.
   55206 */
   55207 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
   55208   return ROUND8(sizeof(BtCursor));
   55209 }
   55210 
   55211 /*
   55212 ** Initialize memory that will be converted into a BtCursor object.
   55213 **
   55214 ** The simple approach here would be to memset() the entire object
   55215 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
   55216 ** do not need to be zeroed and they are large, so we can save a lot
   55217 ** of run-time by skipping the initialization of those elements.
   55218 */
   55219 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
   55220   memset(p, 0, offsetof(BtCursor, iPage));
   55221 }
   55222 
   55223 /*
   55224 ** Close a cursor.  The read lock on the database file is released
   55225 ** when the last cursor is closed.
   55226 */
   55227 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
   55228   Btree *pBtree = pCur->pBtree;
   55229   if( pBtree ){
   55230     int i;
   55231     BtShared *pBt = pCur->pBt;
   55232     sqlite3BtreeEnter(pBtree);
   55233     sqlite3BtreeClearCursor(pCur);
   55234     if( pCur->pPrev ){
   55235       pCur->pPrev->pNext = pCur->pNext;
   55236     }else{
   55237       pBt->pCursor = pCur->pNext;
   55238     }
   55239     if( pCur->pNext ){
   55240       pCur->pNext->pPrev = pCur->pPrev;
   55241     }
   55242     for(i=0; i<=pCur->iPage; i++){
   55243       releasePage(pCur->apPage[i]);
   55244     }
   55245     unlockBtreeIfUnused(pBt);
   55246     sqlite3DbFree(pBtree->db, pCur->aOverflow);
   55247     /* sqlite3_free(pCur); */
   55248     sqlite3BtreeLeave(pBtree);
   55249   }
   55250   return SQLITE_OK;
   55251 }
   55252 
   55253 /*
   55254 ** Make sure the BtCursor* given in the argument has a valid
   55255 ** BtCursor.info structure.  If it is not already valid, call
   55256 ** btreeParseCell() to fill it in.
   55257 **
   55258 ** BtCursor.info is a cache of the information in the current cell.
   55259 ** Using this cache reduces the number of calls to btreeParseCell().
   55260 **
   55261 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
   55262 ** compiler to crash when getCellInfo() is implemented as a macro.
   55263 ** But there is a measureable speed advantage to using the macro on gcc
   55264 ** (when less compiler optimizations like -Os or -O0 are used and the
   55265 ** compiler is not doing agressive inlining.)  So we use a real function
   55266 ** for MSVC and a macro for everything else.  Ticket #2457.
   55267 */
   55268 #ifndef NDEBUG
   55269   static void assertCellInfo(BtCursor *pCur){
   55270     CellInfo info;
   55271     int iPage = pCur->iPage;
   55272     memset(&info, 0, sizeof(info));
   55273     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
   55274     assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
   55275   }
   55276 #else
   55277   #define assertCellInfo(x)
   55278 #endif
   55279 #ifdef _MSC_VER
   55280   /* Use a real function in MSVC to work around bugs in that compiler. */
   55281   static void getCellInfo(BtCursor *pCur){
   55282     if( pCur->info.nSize==0 ){
   55283       int iPage = pCur->iPage;
   55284       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
   55285       pCur->curFlags |= BTCF_ValidNKey;
   55286     }else{
   55287       assertCellInfo(pCur);
   55288     }
   55289   }
   55290 #else /* if not _MSC_VER */
   55291   /* Use a macro in all other compilers so that the function is inlined */
   55292 #define getCellInfo(pCur)                                                      \
   55293   if( pCur->info.nSize==0 ){                                                   \
   55294     int iPage = pCur->iPage;                                                   \
   55295     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);        \
   55296     pCur->curFlags |= BTCF_ValidNKey;                                          \
   55297   }else{                                                                       \
   55298     assertCellInfo(pCur);                                                      \
   55299   }
   55300 #endif /* _MSC_VER */
   55301 
   55302 #ifndef NDEBUG  /* The next routine used only within assert() statements */
   55303 /*
   55304 ** Return true if the given BtCursor is valid.  A valid cursor is one
   55305 ** that is currently pointing to a row in a (non-empty) table.
   55306 ** This is a verification routine is used only within assert() statements.
   55307 */
   55308 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
   55309   return pCur && pCur->eState==CURSOR_VALID;
   55310 }
   55311 #endif /* NDEBUG */
   55312 
   55313 /*
   55314 ** Set *pSize to the size of the buffer needed to hold the value of
   55315 ** the key for the current entry.  If the cursor is not pointing
   55316 ** to a valid entry, *pSize is set to 0.
   55317 **
   55318 ** For a table with the INTKEY flag set, this routine returns the key
   55319 ** itself, not the number of bytes in the key.
   55320 **
   55321 ** The caller must position the cursor prior to invoking this routine.
   55322 **
   55323 ** This routine cannot fail.  It always returns SQLITE_OK.
   55324 */
   55325 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
   55326   assert( cursorHoldsMutex(pCur) );
   55327   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
   55328   if( pCur->eState!=CURSOR_VALID ){
   55329     *pSize = 0;
   55330   }else{
   55331     getCellInfo(pCur);
   55332     *pSize = pCur->info.nKey;
   55333   }
   55334   return SQLITE_OK;
   55335 }
   55336 
   55337 /*
   55338 ** Set *pSize to the number of bytes of data in the entry the
   55339 ** cursor currently points to.
   55340 **
   55341 ** The caller must guarantee that the cursor is pointing to a non-NULL
   55342 ** valid entry.  In other words, the calling procedure must guarantee
   55343 ** that the cursor has Cursor.eState==CURSOR_VALID.
   55344 **
   55345 ** Failure is not possible.  This function always returns SQLITE_OK.
   55346 ** It might just as well be a procedure (returning void) but we continue
   55347 ** to return an integer result code for historical reasons.
   55348 */
   55349 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
   55350   assert( cursorHoldsMutex(pCur) );
   55351   assert( pCur->eState==CURSOR_VALID );
   55352   getCellInfo(pCur);
   55353   *pSize = pCur->info.nData;
   55354   return SQLITE_OK;
   55355 }
   55356 
   55357 /*
   55358 ** Given the page number of an overflow page in the database (parameter
   55359 ** ovfl), this function finds the page number of the next page in the
   55360 ** linked list of overflow pages. If possible, it uses the auto-vacuum
   55361 ** pointer-map data instead of reading the content of page ovfl to do so.
   55362 **
   55363 ** If an error occurs an SQLite error code is returned. Otherwise:
   55364 **
   55365 ** The page number of the next overflow page in the linked list is
   55366 ** written to *pPgnoNext. If page ovfl is the last page in its linked
   55367 ** list, *pPgnoNext is set to zero.
   55368 **
   55369 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
   55370 ** to page number pOvfl was obtained, then *ppPage is set to point to that
   55371 ** reference. It is the responsibility of the caller to call releasePage()
   55372 ** on *ppPage to free the reference. In no reference was obtained (because
   55373 ** the pointer-map was used to obtain the value for *pPgnoNext), then
   55374 ** *ppPage is set to zero.
   55375 */
   55376 static int getOverflowPage(
   55377   BtShared *pBt,               /* The database file */
   55378   Pgno ovfl,                   /* Current overflow page number */
   55379   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
   55380   Pgno *pPgnoNext              /* OUT: Next overflow page number */
   55381 ){
   55382   Pgno next = 0;
   55383   MemPage *pPage = 0;
   55384   int rc = SQLITE_OK;
   55385 
   55386   assert( sqlite3_mutex_held(pBt->mutex) );
   55387   assert(pPgnoNext);
   55388 
   55389 #ifndef SQLITE_OMIT_AUTOVACUUM
   55390   /* Try to find the next page in the overflow list using the
   55391   ** autovacuum pointer-map pages. Guess that the next page in
   55392   ** the overflow list is page number (ovfl+1). If that guess turns
   55393   ** out to be wrong, fall back to loading the data of page
   55394   ** number ovfl to determine the next page number.
   55395   */
   55396   if( pBt->autoVacuum ){
   55397     Pgno pgno;
   55398     Pgno iGuess = ovfl+1;
   55399     u8 eType;
   55400 
   55401     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
   55402       iGuess++;
   55403     }
   55404 
   55405     if( iGuess<=btreePagecount(pBt) ){
   55406       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
   55407       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
   55408         next = iGuess;
   55409         rc = SQLITE_DONE;
   55410       }
   55411     }
   55412   }
   55413 #endif
   55414 
   55415   assert( next==0 || rc==SQLITE_DONE );
   55416   if( rc==SQLITE_OK ){
   55417     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
   55418     assert( rc==SQLITE_OK || pPage==0 );
   55419     if( rc==SQLITE_OK ){
   55420       next = get4byte(pPage->aData);
   55421     }
   55422   }
   55423 
   55424   *pPgnoNext = next;
   55425   if( ppPage ){
   55426     *ppPage = pPage;
   55427   }else{
   55428     releasePage(pPage);
   55429   }
   55430   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   55431 }
   55432 
   55433 /*
   55434 ** Copy data from a buffer to a page, or from a page to a buffer.
   55435 **
   55436 ** pPayload is a pointer to data stored on database page pDbPage.
   55437 ** If argument eOp is false, then nByte bytes of data are copied
   55438 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
   55439 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
   55440 ** of data are copied from the buffer pBuf to pPayload.
   55441 **
   55442 ** SQLITE_OK is returned on success, otherwise an error code.
   55443 */
   55444 static int copyPayload(
   55445   void *pPayload,           /* Pointer to page data */
   55446   void *pBuf,               /* Pointer to buffer */
   55447   int nByte,                /* Number of bytes to copy */
   55448   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
   55449   DbPage *pDbPage           /* Page containing pPayload */
   55450 ){
   55451   if( eOp ){
   55452     /* Copy data from buffer to page (a write operation) */
   55453     int rc = sqlite3PagerWrite(pDbPage);
   55454     if( rc!=SQLITE_OK ){
   55455       return rc;
   55456     }
   55457     memcpy(pPayload, pBuf, nByte);
   55458   }else{
   55459     /* Copy data from page to buffer (a read operation) */
   55460     memcpy(pBuf, pPayload, nByte);
   55461   }
   55462   return SQLITE_OK;
   55463 }
   55464 
   55465 /*
   55466 ** This function is used to read or overwrite payload information
   55467 ** for the entry that the pCur cursor is pointing to. The eOp
   55468 ** argument is interpreted as follows:
   55469 **
   55470 **   0: The operation is a read. Populate the overflow cache.
   55471 **   1: The operation is a write. Populate the overflow cache.
   55472 **   2: The operation is a read. Do not populate the overflow cache.
   55473 **
   55474 ** A total of "amt" bytes are read or written beginning at "offset".
   55475 ** Data is read to or from the buffer pBuf.
   55476 **
   55477 ** The content being read or written might appear on the main page
   55478 ** or be scattered out on multiple overflow pages.
   55479 **
   55480 ** If the current cursor entry uses one or more overflow pages and the
   55481 ** eOp argument is not 2, this function may allocate space for and lazily
   55482 ** popluates the overflow page-list cache array (BtCursor.aOverflow).
   55483 ** Subsequent calls use this cache to make seeking to the supplied offset
   55484 ** more efficient.
   55485 **
   55486 ** Once an overflow page-list cache has been allocated, it may be
   55487 ** invalidated if some other cursor writes to the same table, or if
   55488 ** the cursor is moved to a different row. Additionally, in auto-vacuum
   55489 ** mode, the following events may invalidate an overflow page-list cache.
   55490 **
   55491 **   * An incremental vacuum,
   55492 **   * A commit in auto_vacuum="full" mode,
   55493 **   * Creating a table (may require moving an overflow page).
   55494 */
   55495 static int accessPayload(
   55496   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   55497   u32 offset,          /* Begin reading this far into payload */
   55498   u32 amt,             /* Read this many bytes */
   55499   unsigned char *pBuf, /* Write the bytes into this buffer */
   55500   int eOp              /* zero to read. non-zero to write. */
   55501 ){
   55502   unsigned char *aPayload;
   55503   int rc = SQLITE_OK;
   55504   u32 nKey;
   55505   int iIdx = 0;
   55506   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
   55507   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
   55508 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   55509   int bEnd;                                   /* True if reading to end of data */
   55510 #endif
   55511 
   55512   assert( pPage );
   55513   assert( pCur->eState==CURSOR_VALID );
   55514   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   55515   assert( cursorHoldsMutex(pCur) );
   55516   assert( eOp!=2 || offset==0 );      /* Always start from beginning for eOp==2 */
   55517 
   55518   getCellInfo(pCur);
   55519   aPayload = pCur->info.pCell + pCur->info.nHeader;
   55520   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
   55521 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   55522   bEnd = (offset+amt==nKey+pCur->info.nData);
   55523 #endif
   55524 
   55525   if( NEVER(offset+amt > nKey+pCur->info.nData)
   55526    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
   55527   ){
   55528     /* Trying to read or write past the end of the data is an error */
   55529     return SQLITE_CORRUPT_BKPT;
   55530   }
   55531 
   55532   /* Check if data must be read/written to/from the btree page itself. */
   55533   if( offset<pCur->info.nLocal ){
   55534     int a = amt;
   55535     if( a+offset>pCur->info.nLocal ){
   55536       a = pCur->info.nLocal - offset;
   55537     }
   55538     rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
   55539     offset = 0;
   55540     pBuf += a;
   55541     amt -= a;
   55542   }else{
   55543     offset -= pCur->info.nLocal;
   55544   }
   55545 
   55546   if( rc==SQLITE_OK && amt>0 ){
   55547     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
   55548     Pgno nextPage;
   55549 
   55550     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
   55551 
   55552     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
   55553     ** Except, do not allocate aOverflow[] for eOp==2.
   55554     **
   55555     ** The aOverflow[] array is sized at one entry for each overflow page
   55556     ** in the overflow chain. The page number of the first overflow page is
   55557     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
   55558     ** means "not yet known" (the cache is lazily populated).
   55559     */
   55560     if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
   55561       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
   55562       if( nOvfl>pCur->nOvflAlloc ){
   55563         Pgno *aNew = (Pgno*)sqlite3DbRealloc(
   55564             pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
   55565         );
   55566         if( aNew==0 ){
   55567           rc = SQLITE_NOMEM;
   55568         }else{
   55569           pCur->nOvflAlloc = nOvfl*2;
   55570           pCur->aOverflow = aNew;
   55571         }
   55572       }
   55573       if( rc==SQLITE_OK ){
   55574         memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
   55575         pCur->curFlags |= BTCF_ValidOvfl;
   55576       }
   55577     }
   55578 
   55579     /* If the overflow page-list cache has been allocated and the
   55580     ** entry for the first required overflow page is valid, skip
   55581     ** directly to it.
   55582     */
   55583     if( (pCur->curFlags & BTCF_ValidOvfl)!=0 && pCur->aOverflow[offset/ovflSize] ){
   55584       iIdx = (offset/ovflSize);
   55585       nextPage = pCur->aOverflow[iIdx];
   55586       offset = (offset%ovflSize);
   55587     }
   55588 
   55589     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
   55590 
   55591       /* If required, populate the overflow page-list cache. */
   55592       if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
   55593         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
   55594         pCur->aOverflow[iIdx] = nextPage;
   55595       }
   55596 
   55597       if( offset>=ovflSize ){
   55598         /* The only reason to read this page is to obtain the page
   55599         ** number for the next page in the overflow chain. The page
   55600         ** data is not required. So first try to lookup the overflow
   55601         ** page-list cache, if any, then fall back to the getOverflowPage()
   55602         ** function.
   55603         **
   55604         ** Note that the aOverflow[] array must be allocated because eOp!=2
   55605         ** here.  If eOp==2, then offset==0 and this branch is never taken.
   55606         */
   55607         assert( eOp!=2 );
   55608         assert( pCur->curFlags & BTCF_ValidOvfl );
   55609         if( pCur->aOverflow[iIdx+1] ){
   55610           nextPage = pCur->aOverflow[iIdx+1];
   55611         }else{
   55612           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
   55613         }
   55614         offset -= ovflSize;
   55615       }else{
   55616         /* Need to read this page properly. It contains some of the
   55617         ** range of data that is being read (eOp==0) or written (eOp!=0).
   55618         */
   55619 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   55620         sqlite3_file *fd;
   55621 #endif
   55622         int a = amt;
   55623         if( a + offset > ovflSize ){
   55624           a = ovflSize - offset;
   55625         }
   55626 
   55627 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   55628         /* If all the following are true:
   55629         **
   55630         **   1) this is a read operation, and
   55631         **   2) data is required from the start of this overflow page, and
   55632         **   3) the database is file-backed, and
   55633         **   4) there is no open write-transaction, and
   55634         **   5) the database is not a WAL database,
   55635         **   6) all data from the page is being read.
   55636         **
   55637         ** then data can be read directly from the database file into the
   55638         ** output buffer, bypassing the page-cache altogether. This speeds
   55639         ** up loading large records that span many overflow pages.
   55640         */
   55641         if( (eOp&0x01)==0                                      /* (1) */
   55642          && offset==0                                          /* (2) */
   55643          && (bEnd || a==ovflSize)                              /* (6) */
   55644          && pBt->inTransaction==TRANS_READ                     /* (4) */
   55645          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
   55646          && pBt->pPage1->aData[19]==0x01                       /* (5) */
   55647         ){
   55648           u8 aSave[4];
   55649           u8 *aWrite = &pBuf[-4];
   55650           memcpy(aSave, aWrite, 4);
   55651           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
   55652           nextPage = get4byte(aWrite);
   55653           memcpy(aWrite, aSave, 4);
   55654         }else
   55655 #endif
   55656 
   55657         {
   55658           DbPage *pDbPage;
   55659           rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
   55660               ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
   55661           );
   55662           if( rc==SQLITE_OK ){
   55663             aPayload = sqlite3PagerGetData(pDbPage);
   55664             nextPage = get4byte(aPayload);
   55665             rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
   55666             sqlite3PagerUnref(pDbPage);
   55667             offset = 0;
   55668           }
   55669         }
   55670         amt -= a;
   55671         pBuf += a;
   55672       }
   55673     }
   55674   }
   55675 
   55676   if( rc==SQLITE_OK && amt>0 ){
   55677     return SQLITE_CORRUPT_BKPT;
   55678   }
   55679   return rc;
   55680 }
   55681 
   55682 /*
   55683 ** Read part of the key associated with cursor pCur.  Exactly
   55684 ** "amt" bytes will be transfered into pBuf[].  The transfer
   55685 ** begins at "offset".
   55686 **
   55687 ** The caller must ensure that pCur is pointing to a valid row
   55688 ** in the table.
   55689 **
   55690 ** Return SQLITE_OK on success or an error code if anything goes
   55691 ** wrong.  An error is returned if "offset+amt" is larger than
   55692 ** the available payload.
   55693 */
   55694 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   55695   assert( cursorHoldsMutex(pCur) );
   55696   assert( pCur->eState==CURSOR_VALID );
   55697   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   55698   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   55699   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
   55700 }
   55701 
   55702 /*
   55703 ** Read part of the data associated with cursor pCur.  Exactly
   55704 ** "amt" bytes will be transfered into pBuf[].  The transfer
   55705 ** begins at "offset".
   55706 **
   55707 ** Return SQLITE_OK on success or an error code if anything goes
   55708 ** wrong.  An error is returned if "offset+amt" is larger than
   55709 ** the available payload.
   55710 */
   55711 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   55712   int rc;
   55713 
   55714 #ifndef SQLITE_OMIT_INCRBLOB
   55715   if ( pCur->eState==CURSOR_INVALID ){
   55716     return SQLITE_ABORT;
   55717   }
   55718 #endif
   55719 
   55720   assert( cursorHoldsMutex(pCur) );
   55721   rc = restoreCursorPosition(pCur);
   55722   if( rc==SQLITE_OK ){
   55723     assert( pCur->eState==CURSOR_VALID );
   55724     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   55725     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   55726     rc = accessPayload(pCur, offset, amt, pBuf, 0);
   55727   }
   55728   return rc;
   55729 }
   55730 
   55731 /*
   55732 ** Return a pointer to payload information from the entry that the
   55733 ** pCur cursor is pointing to.  The pointer is to the beginning of
   55734 ** the key if index btrees (pPage->intKey==0) and is the data for
   55735 ** table btrees (pPage->intKey==1). The number of bytes of available
   55736 ** key/data is written into *pAmt.  If *pAmt==0, then the value
   55737 ** returned will not be a valid pointer.
   55738 **
   55739 ** This routine is an optimization.  It is common for the entire key
   55740 ** and data to fit on the local page and for there to be no overflow
   55741 ** pages.  When that is so, this routine can be used to access the
   55742 ** key and data without making a copy.  If the key and/or data spills
   55743 ** onto overflow pages, then accessPayload() must be used to reassemble
   55744 ** the key/data and copy it into a preallocated buffer.
   55745 **
   55746 ** The pointer returned by this routine looks directly into the cached
   55747 ** page of the database.  The data might change or move the next time
   55748 ** any btree routine is called.
   55749 */
   55750 static const void *fetchPayload(
   55751   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   55752   u32 *pAmt            /* Write the number of available bytes here */
   55753 ){
   55754   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
   55755   assert( pCur->eState==CURSOR_VALID );
   55756   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   55757   assert( cursorHoldsMutex(pCur) );
   55758   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   55759   assert( pCur->info.nSize>0 );
   55760   *pAmt = pCur->info.nLocal;
   55761   return (void*)(pCur->info.pCell + pCur->info.nHeader);
   55762 }
   55763 
   55764 
   55765 /*
   55766 ** For the entry that cursor pCur is point to, return as
   55767 ** many bytes of the key or data as are available on the local
   55768 ** b-tree page.  Write the number of available bytes into *pAmt.
   55769 **
   55770 ** The pointer returned is ephemeral.  The key/data may move
   55771 ** or be destroyed on the next call to any Btree routine,
   55772 ** including calls from other threads against the same cache.
   55773 ** Hence, a mutex on the BtShared should be held prior to calling
   55774 ** this routine.
   55775 **
   55776 ** These routines is used to get quick access to key and data
   55777 ** in the common case where no overflow pages are used.
   55778 */
   55779 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
   55780   return fetchPayload(pCur, pAmt);
   55781 }
   55782 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
   55783   return fetchPayload(pCur, pAmt);
   55784 }
   55785 
   55786 
   55787 /*
   55788 ** Move the cursor down to a new child page.  The newPgno argument is the
   55789 ** page number of the child page to move to.
   55790 **
   55791 ** This function returns SQLITE_CORRUPT if the page-header flags field of
   55792 ** the new child page does not match the flags field of the parent (i.e.
   55793 ** if an intkey page appears to be the parent of a non-intkey page, or
   55794 ** vice-versa).
   55795 */
   55796 static int moveToChild(BtCursor *pCur, u32 newPgno){
   55797   int rc;
   55798   int i = pCur->iPage;
   55799   MemPage *pNewPage;
   55800   BtShared *pBt = pCur->pBt;
   55801 
   55802   assert( cursorHoldsMutex(pCur) );
   55803   assert( pCur->eState==CURSOR_VALID );
   55804   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
   55805   assert( pCur->iPage>=0 );
   55806   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
   55807     return SQLITE_CORRUPT_BKPT;
   55808   }
   55809   rc = getAndInitPage(pBt, newPgno, &pNewPage,
   55810                (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
   55811   if( rc ) return rc;
   55812   pCur->apPage[i+1] = pNewPage;
   55813   pCur->aiIdx[i+1] = 0;
   55814   pCur->iPage++;
   55815 
   55816   pCur->info.nSize = 0;
   55817   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   55818   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
   55819     return SQLITE_CORRUPT_BKPT;
   55820   }
   55821   return SQLITE_OK;
   55822 }
   55823 
   55824 #if 0
   55825 /*
   55826 ** Page pParent is an internal (non-leaf) tree page. This function
   55827 ** asserts that page number iChild is the left-child if the iIdx'th
   55828 ** cell in page pParent. Or, if iIdx is equal to the total number of
   55829 ** cells in pParent, that page number iChild is the right-child of
   55830 ** the page.
   55831 */
   55832 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
   55833   assert( iIdx<=pParent->nCell );
   55834   if( iIdx==pParent->nCell ){
   55835     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
   55836   }else{
   55837     assert( get4byte(findCell(pParent, iIdx))==iChild );
   55838   }
   55839 }
   55840 #else
   55841 #  define assertParentIndex(x,y,z)
   55842 #endif
   55843 
   55844 /*
   55845 ** Move the cursor up to the parent page.
   55846 **
   55847 ** pCur->idx is set to the cell index that contains the pointer
   55848 ** to the page we are coming from.  If we are coming from the
   55849 ** right-most child page then pCur->idx is set to one more than
   55850 ** the largest cell index.
   55851 */
   55852 static void moveToParent(BtCursor *pCur){
   55853   assert( cursorHoldsMutex(pCur) );
   55854   assert( pCur->eState==CURSOR_VALID );
   55855   assert( pCur->iPage>0 );
   55856   assert( pCur->apPage[pCur->iPage] );
   55857 
   55858   /* UPDATE: It is actually possible for the condition tested by the assert
   55859   ** below to be untrue if the database file is corrupt. This can occur if
   55860   ** one cursor has modified page pParent while a reference to it is held
   55861   ** by a second cursor. Which can only happen if a single page is linked
   55862   ** into more than one b-tree structure in a corrupt database.  */
   55863 #if 0
   55864   assertParentIndex(
   55865     pCur->apPage[pCur->iPage-1],
   55866     pCur->aiIdx[pCur->iPage-1],
   55867     pCur->apPage[pCur->iPage]->pgno
   55868   );
   55869 #endif
   55870   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
   55871 
   55872   releasePage(pCur->apPage[pCur->iPage]);
   55873   pCur->iPage--;
   55874   pCur->info.nSize = 0;
   55875   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   55876 }
   55877 
   55878 /*
   55879 ** Move the cursor to point to the root page of its b-tree structure.
   55880 **
   55881 ** If the table has a virtual root page, then the cursor is moved to point
   55882 ** to the virtual root page instead of the actual root page. A table has a
   55883 ** virtual root page when the actual root page contains no cells and a
   55884 ** single child page. This can only happen with the table rooted at page 1.
   55885 **
   55886 ** If the b-tree structure is empty, the cursor state is set to
   55887 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
   55888 ** cell located on the root (or virtual root) page and the cursor state
   55889 ** is set to CURSOR_VALID.
   55890 **
   55891 ** If this function returns successfully, it may be assumed that the
   55892 ** page-header flags indicate that the [virtual] root-page is the expected
   55893 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
   55894 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
   55895 ** indicating a table b-tree, or if the caller did specify a KeyInfo
   55896 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
   55897 ** b-tree).
   55898 */
   55899 static int moveToRoot(BtCursor *pCur){
   55900   MemPage *pRoot;
   55901   int rc = SQLITE_OK;
   55902 
   55903   assert( cursorHoldsMutex(pCur) );
   55904   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
   55905   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
   55906   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
   55907   if( pCur->eState>=CURSOR_REQUIRESEEK ){
   55908     if( pCur->eState==CURSOR_FAULT ){
   55909       assert( pCur->skipNext!=SQLITE_OK );
   55910       return pCur->skipNext;
   55911     }
   55912     sqlite3BtreeClearCursor(pCur);
   55913   }
   55914 
   55915   if( pCur->iPage>=0 ){
   55916     while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
   55917   }else if( pCur->pgnoRoot==0 ){
   55918     pCur->eState = CURSOR_INVALID;
   55919     return SQLITE_OK;
   55920   }else{
   55921     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
   55922                  (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
   55923     if( rc!=SQLITE_OK ){
   55924       pCur->eState = CURSOR_INVALID;
   55925       return rc;
   55926     }
   55927     pCur->iPage = 0;
   55928   }
   55929   pRoot = pCur->apPage[0];
   55930   assert( pRoot->pgno==pCur->pgnoRoot );
   55931 
   55932   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   55933   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
   55934   ** NULL, the caller expects a table b-tree. If this is not the case,
   55935   ** return an SQLITE_CORRUPT error.
   55936   **
   55937   ** Earlier versions of SQLite assumed that this test could not fail
   55938   ** if the root page was already loaded when this function was called (i.e.
   55939   ** if pCur->iPage>=0). But this is not so if the database is corrupted
   55940   ** in such a way that page pRoot is linked into a second b-tree table
   55941   ** (or the freelist).  */
   55942   assert( pRoot->intKey==1 || pRoot->intKey==0 );
   55943   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
   55944     return SQLITE_CORRUPT_BKPT;
   55945   }
   55946 
   55947   pCur->aiIdx[0] = 0;
   55948   pCur->info.nSize = 0;
   55949   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
   55950 
   55951   if( pRoot->nCell>0 ){
   55952     pCur->eState = CURSOR_VALID;
   55953   }else if( !pRoot->leaf ){
   55954     Pgno subpage;
   55955     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
   55956     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
   55957     pCur->eState = CURSOR_VALID;
   55958     rc = moveToChild(pCur, subpage);
   55959   }else{
   55960     pCur->eState = CURSOR_INVALID;
   55961   }
   55962   return rc;
   55963 }
   55964 
   55965 /*
   55966 ** Move the cursor down to the left-most leaf entry beneath the
   55967 ** entry to which it is currently pointing.
   55968 **
   55969 ** The left-most leaf is the one with the smallest key - the first
   55970 ** in ascending order.
   55971 */
   55972 static int moveToLeftmost(BtCursor *pCur){
   55973   Pgno pgno;
   55974   int rc = SQLITE_OK;
   55975   MemPage *pPage;
   55976 
   55977   assert( cursorHoldsMutex(pCur) );
   55978   assert( pCur->eState==CURSOR_VALID );
   55979   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   55980     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   55981     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
   55982     rc = moveToChild(pCur, pgno);
   55983   }
   55984   return rc;
   55985 }
   55986 
   55987 /*
   55988 ** Move the cursor down to the right-most leaf entry beneath the
   55989 ** page to which it is currently pointing.  Notice the difference
   55990 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
   55991 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
   55992 ** finds the right-most entry beneath the *page*.
   55993 **
   55994 ** The right-most entry is the one with the largest key - the last
   55995 ** key in ascending order.
   55996 */
   55997 static int moveToRightmost(BtCursor *pCur){
   55998   Pgno pgno;
   55999   int rc = SQLITE_OK;
   56000   MemPage *pPage = 0;
   56001 
   56002   assert( cursorHoldsMutex(pCur) );
   56003   assert( pCur->eState==CURSOR_VALID );
   56004   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   56005     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   56006     pCur->aiIdx[pCur->iPage] = pPage->nCell;
   56007     rc = moveToChild(pCur, pgno);
   56008   }
   56009   if( rc==SQLITE_OK ){
   56010     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
   56011     pCur->info.nSize = 0;
   56012     pCur->curFlags &= ~BTCF_ValidNKey;
   56013   }
   56014   return rc;
   56015 }
   56016 
   56017 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
   56018 ** on success.  Set *pRes to 0 if the cursor actually points to something
   56019 ** or set *pRes to 1 if the table is empty.
   56020 */
   56021 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
   56022   int rc;
   56023 
   56024   assert( cursorHoldsMutex(pCur) );
   56025   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   56026   rc = moveToRoot(pCur);
   56027   if( rc==SQLITE_OK ){
   56028     if( pCur->eState==CURSOR_INVALID ){
   56029       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   56030       *pRes = 1;
   56031     }else{
   56032       assert( pCur->apPage[pCur->iPage]->nCell>0 );
   56033       *pRes = 0;
   56034       rc = moveToLeftmost(pCur);
   56035     }
   56036   }
   56037   return rc;
   56038 }
   56039 
   56040 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
   56041 ** on success.  Set *pRes to 0 if the cursor actually points to something
   56042 ** or set *pRes to 1 if the table is empty.
   56043 */
   56044 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   56045   int rc;
   56046 
   56047   assert( cursorHoldsMutex(pCur) );
   56048   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   56049 
   56050   /* If the cursor already points to the last entry, this is a no-op. */
   56051   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
   56052 #ifdef SQLITE_DEBUG
   56053     /* This block serves to assert() that the cursor really does point
   56054     ** to the last entry in the b-tree. */
   56055     int ii;
   56056     for(ii=0; ii<pCur->iPage; ii++){
   56057       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
   56058     }
   56059     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
   56060     assert( pCur->apPage[pCur->iPage]->leaf );
   56061 #endif
   56062     return SQLITE_OK;
   56063   }
   56064 
   56065   rc = moveToRoot(pCur);
   56066   if( rc==SQLITE_OK ){
   56067     if( CURSOR_INVALID==pCur->eState ){
   56068       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   56069       *pRes = 1;
   56070     }else{
   56071       assert( pCur->eState==CURSOR_VALID );
   56072       *pRes = 0;
   56073       rc = moveToRightmost(pCur);
   56074       if( rc==SQLITE_OK ){
   56075         pCur->curFlags |= BTCF_AtLast;
   56076       }else{
   56077         pCur->curFlags &= ~BTCF_AtLast;
   56078       }
   56079 
   56080     }
   56081   }
   56082   return rc;
   56083 }
   56084 
   56085 /* Move the cursor so that it points to an entry near the key
   56086 ** specified by pIdxKey or intKey.   Return a success code.
   56087 **
   56088 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
   56089 ** must be NULL.  For index tables, pIdxKey is used and intKey
   56090 ** is ignored.
   56091 **
   56092 ** If an exact match is not found, then the cursor is always
   56093 ** left pointing at a leaf page which would hold the entry if it
   56094 ** were present.  The cursor might point to an entry that comes
   56095 ** before or after the key.
   56096 **
   56097 ** An integer is written into *pRes which is the result of
   56098 ** comparing the key with the entry to which the cursor is
   56099 ** pointing.  The meaning of the integer written into
   56100 ** *pRes is as follows:
   56101 **
   56102 **     *pRes<0      The cursor is left pointing at an entry that
   56103 **                  is smaller than intKey/pIdxKey or if the table is empty
   56104 **                  and the cursor is therefore left point to nothing.
   56105 **
   56106 **     *pRes==0     The cursor is left pointing at an entry that
   56107 **                  exactly matches intKey/pIdxKey.
   56108 **
   56109 **     *pRes>0      The cursor is left pointing at an entry that
   56110 **                  is larger than intKey/pIdxKey.
   56111 **
   56112 */
   56113 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   56114   BtCursor *pCur,          /* The cursor to be moved */
   56115   UnpackedRecord *pIdxKey, /* Unpacked index key */
   56116   i64 intKey,              /* The table key */
   56117   int biasRight,           /* If true, bias the search to the high end */
   56118   int *pRes                /* Write search results here */
   56119 ){
   56120   int rc;
   56121   RecordCompare xRecordCompare;
   56122 
   56123   assert( cursorHoldsMutex(pCur) );
   56124   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   56125   assert( pRes );
   56126   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
   56127 
   56128   /* If the cursor is already positioned at the point we are trying
   56129   ** to move to, then just return without doing any work */
   56130   if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
   56131    && pCur->apPage[0]->intKey
   56132   ){
   56133     if( pCur->info.nKey==intKey ){
   56134       *pRes = 0;
   56135       return SQLITE_OK;
   56136     }
   56137     if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
   56138       *pRes = -1;
   56139       return SQLITE_OK;
   56140     }
   56141   }
   56142 
   56143   if( pIdxKey ){
   56144     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
   56145     pIdxKey->isCorrupt = 0;
   56146     assert( pIdxKey->default_rc==1
   56147          || pIdxKey->default_rc==0
   56148          || pIdxKey->default_rc==-1
   56149     );
   56150   }else{
   56151     xRecordCompare = 0; /* All keys are integers */
   56152   }
   56153 
   56154   rc = moveToRoot(pCur);
   56155   if( rc ){
   56156     return rc;
   56157   }
   56158   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
   56159   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
   56160   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
   56161   if( pCur->eState==CURSOR_INVALID ){
   56162     *pRes = -1;
   56163     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   56164     return SQLITE_OK;
   56165   }
   56166   assert( pCur->apPage[0]->intKey || pIdxKey );
   56167   for(;;){
   56168     int lwr, upr, idx, c;
   56169     Pgno chldPg;
   56170     MemPage *pPage = pCur->apPage[pCur->iPage];
   56171     u8 *pCell;                          /* Pointer to current cell in pPage */
   56172 
   56173     /* pPage->nCell must be greater than zero. If this is the root-page
   56174     ** the cursor would have been INVALID above and this for(;;) loop
   56175     ** not run. If this is not the root-page, then the moveToChild() routine
   56176     ** would have already detected db corruption. Similarly, pPage must
   56177     ** be the right kind (index or table) of b-tree page. Otherwise
   56178     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
   56179     assert( pPage->nCell>0 );
   56180     assert( pPage->intKey==(pIdxKey==0) );
   56181     lwr = 0;
   56182     upr = pPage->nCell-1;
   56183     assert( biasRight==0 || biasRight==1 );
   56184     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
   56185     pCur->aiIdx[pCur->iPage] = (u16)idx;
   56186     if( xRecordCompare==0 ){
   56187       for(;;){
   56188         i64 nCellKey;
   56189         pCell = findCell(pPage, idx) + pPage->childPtrSize;
   56190         if( pPage->hasData ){
   56191           while( 0x80 <= *(pCell++) ){
   56192             if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
   56193           }
   56194         }
   56195         getVarint(pCell, (u64*)&nCellKey);
   56196         if( nCellKey<intKey ){
   56197           lwr = idx+1;
   56198           if( lwr>upr ){ c = -1; break; }
   56199         }else if( nCellKey>intKey ){
   56200           upr = idx-1;
   56201           if( lwr>upr ){ c = +1; break; }
   56202         }else{
   56203           assert( nCellKey==intKey );
   56204           pCur->curFlags |= BTCF_ValidNKey;
   56205           pCur->info.nKey = nCellKey;
   56206           pCur->aiIdx[pCur->iPage] = (u16)idx;
   56207           if( !pPage->leaf ){
   56208             lwr = idx;
   56209             goto moveto_next_layer;
   56210           }else{
   56211             *pRes = 0;
   56212             rc = SQLITE_OK;
   56213             goto moveto_finish;
   56214           }
   56215         }
   56216         assert( lwr+upr>=0 );
   56217         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
   56218       }
   56219     }else{
   56220       for(;;){
   56221         int nCell;
   56222         pCell = findCell(pPage, idx) + pPage->childPtrSize;
   56223 
   56224         /* The maximum supported page-size is 65536 bytes. This means that
   56225         ** the maximum number of record bytes stored on an index B-Tree
   56226         ** page is less than 16384 bytes and may be stored as a 2-byte
   56227         ** varint. This information is used to attempt to avoid parsing
   56228         ** the entire cell by checking for the cases where the record is
   56229         ** stored entirely within the b-tree page by inspecting the first
   56230         ** 2 bytes of the cell.
   56231         */
   56232         nCell = pCell[0];
   56233         if( nCell<=pPage->max1bytePayload ){
   56234           /* This branch runs if the record-size field of the cell is a
   56235           ** single byte varint and the record fits entirely on the main
   56236           ** b-tree page.  */
   56237           testcase( pCell+nCell+1==pPage->aDataEnd );
   56238           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey, 0);
   56239         }else if( !(pCell[1] & 0x80)
   56240           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
   56241         ){
   56242           /* The record-size field is a 2 byte varint and the record
   56243           ** fits entirely on the main b-tree page.  */
   56244           testcase( pCell+nCell+2==pPage->aDataEnd );
   56245           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey, 0);
   56246         }else{
   56247           /* The record flows over onto one or more overflow pages. In
   56248           ** this case the whole cell needs to be parsed, a buffer allocated
   56249           ** and accessPayload() used to retrieve the record into the
   56250           ** buffer before VdbeRecordCompare() can be called. */
   56251           void *pCellKey;
   56252           u8 * const pCellBody = pCell - pPage->childPtrSize;
   56253           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
   56254           nCell = (int)pCur->info.nKey;
   56255           pCellKey = sqlite3Malloc( nCell );
   56256           if( pCellKey==0 ){
   56257             rc = SQLITE_NOMEM;
   56258             goto moveto_finish;
   56259           }
   56260           pCur->aiIdx[pCur->iPage] = (u16)idx;
   56261           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
   56262           if( rc ){
   56263             sqlite3_free(pCellKey);
   56264             goto moveto_finish;
   56265           }
   56266           c = xRecordCompare(nCell, pCellKey, pIdxKey, 0);
   56267           sqlite3_free(pCellKey);
   56268         }
   56269         assert( pIdxKey->isCorrupt==0 || c==0 );
   56270         if( c<0 ){
   56271           lwr = idx+1;
   56272         }else if( c>0 ){
   56273           upr = idx-1;
   56274         }else{
   56275           assert( c==0 );
   56276           *pRes = 0;
   56277           rc = SQLITE_OK;
   56278           pCur->aiIdx[pCur->iPage] = (u16)idx;
   56279           if( pIdxKey->isCorrupt ) rc = SQLITE_CORRUPT;
   56280           goto moveto_finish;
   56281         }
   56282         if( lwr>upr ) break;
   56283         assert( lwr+upr>=0 );
   56284         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
   56285       }
   56286     }
   56287     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
   56288     assert( pPage->isInit );
   56289     if( pPage->leaf ){
   56290       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   56291       pCur->aiIdx[pCur->iPage] = (u16)idx;
   56292       *pRes = c;
   56293       rc = SQLITE_OK;
   56294       goto moveto_finish;
   56295     }
   56296 moveto_next_layer:
   56297     if( lwr>=pPage->nCell ){
   56298       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   56299     }else{
   56300       chldPg = get4byte(findCell(pPage, lwr));
   56301     }
   56302     pCur->aiIdx[pCur->iPage] = (u16)lwr;
   56303     rc = moveToChild(pCur, chldPg);
   56304     if( rc ) break;
   56305   }
   56306 moveto_finish:
   56307   pCur->info.nSize = 0;
   56308   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   56309   return rc;
   56310 }
   56311 
   56312 
   56313 /*
   56314 ** Return TRUE if the cursor is not pointing at an entry of the table.
   56315 **
   56316 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
   56317 ** past the last entry in the table or sqlite3BtreePrev() moves past
   56318 ** the first entry.  TRUE is also returned if the table is empty.
   56319 */
   56320 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
   56321   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
   56322   ** have been deleted? This API will need to change to return an error code
   56323   ** as well as the boolean result value.
   56324   */
   56325   return (CURSOR_VALID!=pCur->eState);
   56326 }
   56327 
   56328 /*
   56329 ** Advance the cursor to the next entry in the database.  If
   56330 ** successful then set *pRes=0.  If the cursor
   56331 ** was already pointing to the last entry in the database before
   56332 ** this routine was called, then set *pRes=1.
   56333 **
   56334 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
   56335 ** will be 1 if the cursor being stepped corresponds to an SQL index and
   56336 ** if this routine could have been skipped if that SQL index had been
   56337 ** a unique index.  Otherwise the caller will have set *pRes to zero.
   56338 ** Zero is the common case. The btree implementation is free to use the
   56339 ** initial *pRes value as a hint to improve performance, but the current
   56340 ** SQLite btree implementation does not. (Note that the comdb2 btree
   56341 ** implementation does use this hint, however.)
   56342 */
   56343 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
   56344   int rc;
   56345   int idx;
   56346   MemPage *pPage;
   56347 
   56348   assert( cursorHoldsMutex(pCur) );
   56349   assert( pRes!=0 );
   56350   assert( *pRes==0 || *pRes==1 );
   56351   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
   56352   if( pCur->eState!=CURSOR_VALID ){
   56353     invalidateOverflowCache(pCur);
   56354     rc = restoreCursorPosition(pCur);
   56355     if( rc!=SQLITE_OK ){
   56356       *pRes = 0;
   56357       return rc;
   56358     }
   56359     if( CURSOR_INVALID==pCur->eState ){
   56360       *pRes = 1;
   56361       return SQLITE_OK;
   56362     }
   56363     if( pCur->skipNext ){
   56364       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
   56365       pCur->eState = CURSOR_VALID;
   56366       if( pCur->skipNext>0 ){
   56367         pCur->skipNext = 0;
   56368         *pRes = 0;
   56369         return SQLITE_OK;
   56370       }
   56371       pCur->skipNext = 0;
   56372     }
   56373   }
   56374 
   56375   pPage = pCur->apPage[pCur->iPage];
   56376   idx = ++pCur->aiIdx[pCur->iPage];
   56377   assert( pPage->isInit );
   56378 
   56379   /* If the database file is corrupt, it is possible for the value of idx
   56380   ** to be invalid here. This can only occur if a second cursor modifies
   56381   ** the page while cursor pCur is holding a reference to it. Which can
   56382   ** only happen if the database is corrupt in such a way as to link the
   56383   ** page into more than one b-tree structure. */
   56384   testcase( idx>pPage->nCell );
   56385 
   56386   pCur->info.nSize = 0;
   56387   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   56388   if( idx>=pPage->nCell ){
   56389     if( !pPage->leaf ){
   56390       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   56391       if( rc ){
   56392         *pRes = 0;
   56393         return rc;
   56394       }
   56395       rc = moveToLeftmost(pCur);
   56396       *pRes = 0;
   56397       return rc;
   56398     }
   56399     do{
   56400       if( pCur->iPage==0 ){
   56401         *pRes = 1;
   56402         pCur->eState = CURSOR_INVALID;
   56403         return SQLITE_OK;
   56404       }
   56405       moveToParent(pCur);
   56406       pPage = pCur->apPage[pCur->iPage];
   56407     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
   56408     *pRes = 0;
   56409     if( pPage->intKey ){
   56410       rc = sqlite3BtreeNext(pCur, pRes);
   56411     }else{
   56412       rc = SQLITE_OK;
   56413     }
   56414     return rc;
   56415   }
   56416   *pRes = 0;
   56417   if( pPage->leaf ){
   56418     return SQLITE_OK;
   56419   }
   56420   rc = moveToLeftmost(pCur);
   56421   return rc;
   56422 }
   56423 
   56424 
   56425 /*
   56426 ** Step the cursor to the back to the previous entry in the database.  If
   56427 ** successful then set *pRes=0.  If the cursor
   56428 ** was already pointing to the first entry in the database before
   56429 ** this routine was called, then set *pRes=1.
   56430 **
   56431 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
   56432 ** will be 1 if the cursor being stepped corresponds to an SQL index and
   56433 ** if this routine could have been skipped if that SQL index had been
   56434 ** a unique index.  Otherwise the caller will have set *pRes to zero.
   56435 ** Zero is the common case. The btree implementation is free to use the
   56436 ** initial *pRes value as a hint to improve performance, but the current
   56437 ** SQLite btree implementation does not. (Note that the comdb2 btree
   56438 ** implementation does use this hint, however.)
   56439 */
   56440 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
   56441   int rc;
   56442   MemPage *pPage;
   56443 
   56444   assert( cursorHoldsMutex(pCur) );
   56445   assert( pRes!=0 );
   56446   assert( *pRes==0 || *pRes==1 );
   56447   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
   56448   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl);
   56449   if( pCur->eState!=CURSOR_VALID ){
   56450     if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
   56451       rc = btreeRestoreCursorPosition(pCur);
   56452       if( rc!=SQLITE_OK ){
   56453         *pRes = 0;
   56454         return rc;
   56455       }
   56456     }
   56457     if( CURSOR_INVALID==pCur->eState ){
   56458       *pRes = 1;
   56459       return SQLITE_OK;
   56460     }
   56461     if( pCur->skipNext ){
   56462       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
   56463       pCur->eState = CURSOR_VALID;
   56464       if( pCur->skipNext<0 ){
   56465         pCur->skipNext = 0;
   56466         *pRes = 0;
   56467         return SQLITE_OK;
   56468       }
   56469       pCur->skipNext = 0;
   56470     }
   56471   }
   56472 
   56473   pPage = pCur->apPage[pCur->iPage];
   56474   assert( pPage->isInit );
   56475   if( !pPage->leaf ){
   56476     int idx = pCur->aiIdx[pCur->iPage];
   56477     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
   56478     if( rc ){
   56479       *pRes = 0;
   56480       return rc;
   56481     }
   56482     rc = moveToRightmost(pCur);
   56483   }else{
   56484     while( pCur->aiIdx[pCur->iPage]==0 ){
   56485       if( pCur->iPage==0 ){
   56486         pCur->eState = CURSOR_INVALID;
   56487         *pRes = 1;
   56488         return SQLITE_OK;
   56489       }
   56490       moveToParent(pCur);
   56491     }
   56492     pCur->info.nSize = 0;
   56493     pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   56494 
   56495     pCur->aiIdx[pCur->iPage]--;
   56496     pPage = pCur->apPage[pCur->iPage];
   56497     if( pPage->intKey && !pPage->leaf ){
   56498       rc = sqlite3BtreePrevious(pCur, pRes);
   56499     }else{
   56500       rc = SQLITE_OK;
   56501     }
   56502   }
   56503   *pRes = 0;
   56504   return rc;
   56505 }
   56506 
   56507 /*
   56508 ** Allocate a new page from the database file.
   56509 **
   56510 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
   56511 ** has already been called on the new page.)  The new page has also
   56512 ** been referenced and the calling routine is responsible for calling
   56513 ** sqlite3PagerUnref() on the new page when it is done.
   56514 **
   56515 ** SQLITE_OK is returned on success.  Any other return value indicates
   56516 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
   56517 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
   56518 **
   56519 ** If the "nearby" parameter is not 0, then an effort is made to
   56520 ** locate a page close to the page number "nearby".  This can be used in an
   56521 ** attempt to keep related pages close to each other in the database file,
   56522 ** which in turn can make database access faster.
   56523 **
   56524 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
   56525 ** anywhere on the free-list, then it is guaranteed to be returned.  If
   56526 ** eMode is BTALLOC_LT then the page returned will be less than or equal
   56527 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
   56528 ** are no restrictions on which page is returned.
   56529 */
   56530 static int allocateBtreePage(
   56531   BtShared *pBt,         /* The btree */
   56532   MemPage **ppPage,      /* Store pointer to the allocated page here */
   56533   Pgno *pPgno,           /* Store the page number here */
   56534   Pgno nearby,           /* Search for a page near this one */
   56535   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
   56536 ){
   56537   MemPage *pPage1;
   56538   int rc;
   56539   u32 n;     /* Number of pages on the freelist */
   56540   u32 k;     /* Number of leaves on the trunk of the freelist */
   56541   MemPage *pTrunk = 0;
   56542   MemPage *pPrevTrunk = 0;
   56543   Pgno mxPage;     /* Total size of the database file */
   56544 
   56545   assert( sqlite3_mutex_held(pBt->mutex) );
   56546   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
   56547   pPage1 = pBt->pPage1;
   56548   mxPage = btreePagecount(pBt);
   56549   n = get4byte(&pPage1->aData[36]);
   56550   testcase( n==mxPage-1 );
   56551   if( n>=mxPage ){
   56552     return SQLITE_CORRUPT_BKPT;
   56553   }
   56554   if( n>0 ){
   56555     /* There are pages on the freelist.  Reuse one of those pages. */
   56556     Pgno iTrunk;
   56557     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
   56558 
   56559     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
   56560     ** shows that the page 'nearby' is somewhere on the free-list, then
   56561     ** the entire-list will be searched for that page.
   56562     */
   56563 #ifndef SQLITE_OMIT_AUTOVACUUM
   56564     if( eMode==BTALLOC_EXACT ){
   56565       if( nearby<=mxPage ){
   56566         u8 eType;
   56567         assert( nearby>0 );
   56568         assert( pBt->autoVacuum );
   56569         rc = ptrmapGet(pBt, nearby, &eType, 0);
   56570         if( rc ) return rc;
   56571         if( eType==PTRMAP_FREEPAGE ){
   56572           searchList = 1;
   56573         }
   56574       }
   56575     }else if( eMode==BTALLOC_LE ){
   56576       searchList = 1;
   56577     }
   56578 #endif
   56579 
   56580     /* Decrement the free-list count by 1. Set iTrunk to the index of the
   56581     ** first free-list trunk page. iPrevTrunk is initially 1.
   56582     */
   56583     rc = sqlite3PagerWrite(pPage1->pDbPage);
   56584     if( rc ) return rc;
   56585     put4byte(&pPage1->aData[36], n-1);
   56586 
   56587     /* The code within this loop is run only once if the 'searchList' variable
   56588     ** is not true. Otherwise, it runs once for each trunk-page on the
   56589     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
   56590     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
   56591     */
   56592     do {
   56593       pPrevTrunk = pTrunk;
   56594       if( pPrevTrunk ){
   56595         iTrunk = get4byte(&pPrevTrunk->aData[0]);
   56596       }else{
   56597         iTrunk = get4byte(&pPage1->aData[32]);
   56598       }
   56599       testcase( iTrunk==mxPage );
   56600       if( iTrunk>mxPage ){
   56601         rc = SQLITE_CORRUPT_BKPT;
   56602       }else{
   56603         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   56604       }
   56605       if( rc ){
   56606         pTrunk = 0;
   56607         goto end_allocate_page;
   56608       }
   56609       assert( pTrunk!=0 );
   56610       assert( pTrunk->aData!=0 );
   56611 
   56612       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
   56613       if( k==0 && !searchList ){
   56614         /* The trunk has no leaves and the list is not being searched.
   56615         ** So extract the trunk page itself and use it as the newly
   56616         ** allocated page */
   56617         assert( pPrevTrunk==0 );
   56618         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   56619         if( rc ){
   56620           goto end_allocate_page;
   56621         }
   56622         *pPgno = iTrunk;
   56623         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   56624         *ppPage = pTrunk;
   56625         pTrunk = 0;
   56626         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   56627       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
   56628         /* Value of k is out of range.  Database corruption */
   56629         rc = SQLITE_CORRUPT_BKPT;
   56630         goto end_allocate_page;
   56631 #ifndef SQLITE_OMIT_AUTOVACUUM
   56632       }else if( searchList
   56633             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
   56634       ){
   56635         /* The list is being searched and this trunk page is the page
   56636         ** to allocate, regardless of whether it has leaves.
   56637         */
   56638         *pPgno = iTrunk;
   56639         *ppPage = pTrunk;
   56640         searchList = 0;
   56641         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   56642         if( rc ){
   56643           goto end_allocate_page;
   56644         }
   56645         if( k==0 ){
   56646           if( !pPrevTrunk ){
   56647             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   56648           }else{
   56649             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   56650             if( rc!=SQLITE_OK ){
   56651               goto end_allocate_page;
   56652             }
   56653             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
   56654           }
   56655         }else{
   56656           /* The trunk page is required by the caller but it contains
   56657           ** pointers to free-list leaves. The first leaf becomes a trunk
   56658           ** page in this case.
   56659           */
   56660           MemPage *pNewTrunk;
   56661           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
   56662           if( iNewTrunk>mxPage ){
   56663             rc = SQLITE_CORRUPT_BKPT;
   56664             goto end_allocate_page;
   56665           }
   56666           testcase( iNewTrunk==mxPage );
   56667           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
   56668           if( rc!=SQLITE_OK ){
   56669             goto end_allocate_page;
   56670           }
   56671           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
   56672           if( rc!=SQLITE_OK ){
   56673             releasePage(pNewTrunk);
   56674             goto end_allocate_page;
   56675           }
   56676           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
   56677           put4byte(&pNewTrunk->aData[4], k-1);
   56678           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
   56679           releasePage(pNewTrunk);
   56680           if( !pPrevTrunk ){
   56681             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
   56682             put4byte(&pPage1->aData[32], iNewTrunk);
   56683           }else{
   56684             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   56685             if( rc ){
   56686               goto end_allocate_page;
   56687             }
   56688             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
   56689           }
   56690         }
   56691         pTrunk = 0;
   56692         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   56693 #endif
   56694       }else if( k>0 ){
   56695         /* Extract a leaf from the trunk */
   56696         u32 closest;
   56697         Pgno iPage;
   56698         unsigned char *aData = pTrunk->aData;
   56699         if( nearby>0 ){
   56700           u32 i;
   56701           closest = 0;
   56702           if( eMode==BTALLOC_LE ){
   56703             for(i=0; i<k; i++){
   56704               iPage = get4byte(&aData[8+i*4]);
   56705               if( iPage<=nearby ){
   56706                 closest = i;
   56707                 break;
   56708               }
   56709             }
   56710           }else{
   56711             int dist;
   56712             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
   56713             for(i=1; i<k; i++){
   56714               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
   56715               if( d2<dist ){
   56716                 closest = i;
   56717                 dist = d2;
   56718               }
   56719             }
   56720           }
   56721         }else{
   56722           closest = 0;
   56723         }
   56724 
   56725         iPage = get4byte(&aData[8+closest*4]);
   56726         testcase( iPage==mxPage );
   56727         if( iPage>mxPage ){
   56728           rc = SQLITE_CORRUPT_BKPT;
   56729           goto end_allocate_page;
   56730         }
   56731         testcase( iPage==mxPage );
   56732         if( !searchList
   56733          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
   56734         ){
   56735           int noContent;
   56736           *pPgno = iPage;
   56737           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
   56738                  ": %d more free pages\n",
   56739                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
   56740           rc = sqlite3PagerWrite(pTrunk->pDbPage);
   56741           if( rc ) goto end_allocate_page;
   56742           if( closest<k-1 ){
   56743             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
   56744           }
   56745           put4byte(&aData[4], k-1);
   56746           noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
   56747           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
   56748           if( rc==SQLITE_OK ){
   56749             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   56750             if( rc!=SQLITE_OK ){
   56751               releasePage(*ppPage);
   56752             }
   56753           }
   56754           searchList = 0;
   56755         }
   56756       }
   56757       releasePage(pPrevTrunk);
   56758       pPrevTrunk = 0;
   56759     }while( searchList );
   56760   }else{
   56761     /* There are no pages on the freelist, so append a new page to the
   56762     ** database image.
   56763     **
   56764     ** Normally, new pages allocated by this block can be requested from the
   56765     ** pager layer with the 'no-content' flag set. This prevents the pager
   56766     ** from trying to read the pages content from disk. However, if the
   56767     ** current transaction has already run one or more incremental-vacuum
   56768     ** steps, then the page we are about to allocate may contain content
   56769     ** that is required in the event of a rollback. In this case, do
   56770     ** not set the no-content flag. This causes the pager to load and journal
   56771     ** the current page content before overwriting it.
   56772     **
   56773     ** Note that the pager will not actually attempt to load or journal
   56774     ** content for any page that really does lie past the end of the database
   56775     ** file on disk. So the effects of disabling the no-content optimization
   56776     ** here are confined to those pages that lie between the end of the
   56777     ** database image and the end of the database file.
   56778     */
   56779     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
   56780 
   56781     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   56782     if( rc ) return rc;
   56783     pBt->nPage++;
   56784     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
   56785 
   56786 #ifndef SQLITE_OMIT_AUTOVACUUM
   56787     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
   56788       /* If *pPgno refers to a pointer-map page, allocate two new pages
   56789       ** at the end of the file instead of one. The first allocated page
   56790       ** becomes a new pointer-map page, the second is used by the caller.
   56791       */
   56792       MemPage *pPg = 0;
   56793       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
   56794       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
   56795       rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
   56796       if( rc==SQLITE_OK ){
   56797         rc = sqlite3PagerWrite(pPg->pDbPage);
   56798         releasePage(pPg);
   56799       }
   56800       if( rc ) return rc;
   56801       pBt->nPage++;
   56802       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
   56803     }
   56804 #endif
   56805     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
   56806     *pPgno = pBt->nPage;
   56807 
   56808     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   56809     rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
   56810     if( rc ) return rc;
   56811     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   56812     if( rc!=SQLITE_OK ){
   56813       releasePage(*ppPage);
   56814     }
   56815     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
   56816   }
   56817 
   56818   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   56819 
   56820 end_allocate_page:
   56821   releasePage(pTrunk);
   56822   releasePage(pPrevTrunk);
   56823   if( rc==SQLITE_OK ){
   56824     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
   56825       releasePage(*ppPage);
   56826       *ppPage = 0;
   56827       return SQLITE_CORRUPT_BKPT;
   56828     }
   56829     (*ppPage)->isInit = 0;
   56830   }else{
   56831     *ppPage = 0;
   56832   }
   56833   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
   56834   return rc;
   56835 }
   56836 
   56837 /*
   56838 ** This function is used to add page iPage to the database file free-list.
   56839 ** It is assumed that the page is not already a part of the free-list.
   56840 **
   56841 ** The value passed as the second argument to this function is optional.
   56842 ** If the caller happens to have a pointer to the MemPage object
   56843 ** corresponding to page iPage handy, it may pass it as the second value.
   56844 ** Otherwise, it may pass NULL.
   56845 **
   56846 ** If a pointer to a MemPage object is passed as the second argument,
   56847 ** its reference count is not altered by this function.
   56848 */
   56849 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
   56850   MemPage *pTrunk = 0;                /* Free-list trunk page */
   56851   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
   56852   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
   56853   MemPage *pPage;                     /* Page being freed. May be NULL. */
   56854   int rc;                             /* Return Code */
   56855   int nFree;                          /* Initial number of pages on free-list */
   56856 
   56857   assert( sqlite3_mutex_held(pBt->mutex) );
   56858   assert( iPage>1 );
   56859   assert( !pMemPage || pMemPage->pgno==iPage );
   56860 
   56861   if( pMemPage ){
   56862     pPage = pMemPage;
   56863     sqlite3PagerRef(pPage->pDbPage);
   56864   }else{
   56865     pPage = btreePageLookup(pBt, iPage);
   56866   }
   56867 
   56868   /* Increment the free page count on pPage1 */
   56869   rc = sqlite3PagerWrite(pPage1->pDbPage);
   56870   if( rc ) goto freepage_out;
   56871   nFree = get4byte(&pPage1->aData[36]);
   56872   put4byte(&pPage1->aData[36], nFree+1);
   56873 
   56874   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   56875     /* If the secure_delete option is enabled, then
   56876     ** always fully overwrite deleted information with zeros.
   56877     */
   56878     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
   56879      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
   56880     ){
   56881       goto freepage_out;
   56882     }
   56883     memset(pPage->aData, 0, pPage->pBt->pageSize);
   56884   }
   56885 
   56886   /* If the database supports auto-vacuum, write an entry in the pointer-map
   56887   ** to indicate that the page is free.
   56888   */
   56889   if( ISAUTOVACUUM ){
   56890     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
   56891     if( rc ) goto freepage_out;
   56892   }
   56893 
   56894   /* Now manipulate the actual database free-list structure. There are two
   56895   ** possibilities. If the free-list is currently empty, or if the first
   56896   ** trunk page in the free-list is full, then this page will become a
   56897   ** new free-list trunk page. Otherwise, it will become a leaf of the
   56898   ** first trunk page in the current free-list. This block tests if it
   56899   ** is possible to add the page as a new free-list leaf.
   56900   */
   56901   if( nFree!=0 ){
   56902     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
   56903 
   56904     iTrunk = get4byte(&pPage1->aData[32]);
   56905     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   56906     if( rc!=SQLITE_OK ){
   56907       goto freepage_out;
   56908     }
   56909 
   56910     nLeaf = get4byte(&pTrunk->aData[4]);
   56911     assert( pBt->usableSize>32 );
   56912     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
   56913       rc = SQLITE_CORRUPT_BKPT;
   56914       goto freepage_out;
   56915     }
   56916     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
   56917       /* In this case there is room on the trunk page to insert the page
   56918       ** being freed as a new leaf.
   56919       **
   56920       ** Note that the trunk page is not really full until it contains
   56921       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
   56922       ** coded.  But due to a coding error in versions of SQLite prior to
   56923       ** 3.6.0, databases with freelist trunk pages holding more than
   56924       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
   56925       ** to maintain backwards compatibility with older versions of SQLite,
   56926       ** we will continue to restrict the number of entries to usableSize/4 - 8
   56927       ** for now.  At some point in the future (once everyone has upgraded
   56928       ** to 3.6.0 or later) we should consider fixing the conditional above
   56929       ** to read "usableSize/4-2" instead of "usableSize/4-8".
   56930       */
   56931       rc = sqlite3PagerWrite(pTrunk->pDbPage);
   56932       if( rc==SQLITE_OK ){
   56933         put4byte(&pTrunk->aData[4], nLeaf+1);
   56934         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
   56935         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
   56936           sqlite3PagerDontWrite(pPage->pDbPage);
   56937         }
   56938         rc = btreeSetHasContent(pBt, iPage);
   56939       }
   56940       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
   56941       goto freepage_out;
   56942     }
   56943   }
   56944 
   56945   /* If control flows to this point, then it was not possible to add the
   56946   ** the page being freed as a leaf page of the first trunk in the free-list.
   56947   ** Possibly because the free-list is empty, or possibly because the
   56948   ** first trunk in the free-list is full. Either way, the page being freed
   56949   ** will become the new first trunk page in the free-list.
   56950   */
   56951   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
   56952     goto freepage_out;
   56953   }
   56954   rc = sqlite3PagerWrite(pPage->pDbPage);
   56955   if( rc!=SQLITE_OK ){
   56956     goto freepage_out;
   56957   }
   56958   put4byte(pPage->aData, iTrunk);
   56959   put4byte(&pPage->aData[4], 0);
   56960   put4byte(&pPage1->aData[32], iPage);
   56961   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
   56962 
   56963 freepage_out:
   56964   if( pPage ){
   56965     pPage->isInit = 0;
   56966   }
   56967   releasePage(pPage);
   56968   releasePage(pTrunk);
   56969   return rc;
   56970 }
   56971 static void freePage(MemPage *pPage, int *pRC){
   56972   if( (*pRC)==SQLITE_OK ){
   56973     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
   56974   }
   56975 }
   56976 
   56977 /*
   56978 ** Free any overflow pages associated with the given Cell.
   56979 */
   56980 static int clearCell(MemPage *pPage, unsigned char *pCell){
   56981   BtShared *pBt = pPage->pBt;
   56982   CellInfo info;
   56983   Pgno ovflPgno;
   56984   int rc;
   56985   int nOvfl;
   56986   u32 ovflPageSize;
   56987 
   56988   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   56989   btreeParseCellPtr(pPage, pCell, &info);
   56990   if( info.iOverflow==0 ){
   56991     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
   56992   }
   56993   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
   56994     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
   56995   }
   56996   ovflPgno = get4byte(&pCell[info.iOverflow]);
   56997   assert( pBt->usableSize > 4 );
   56998   ovflPageSize = pBt->usableSize - 4;
   56999   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
   57000   assert( ovflPgno==0 || nOvfl>0 );
   57001   while( nOvfl-- ){
   57002     Pgno iNext = 0;
   57003     MemPage *pOvfl = 0;
   57004     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
   57005       /* 0 is not a legal page number and page 1 cannot be an
   57006       ** overflow page. Therefore if ovflPgno<2 or past the end of the
   57007       ** file the database must be corrupt. */
   57008       return SQLITE_CORRUPT_BKPT;
   57009     }
   57010     if( nOvfl ){
   57011       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
   57012       if( rc ) return rc;
   57013     }
   57014 
   57015     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
   57016      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
   57017     ){
   57018       /* There is no reason any cursor should have an outstanding reference
   57019       ** to an overflow page belonging to a cell that is being deleted/updated.
   57020       ** So if there exists more than one reference to this page, then it
   57021       ** must not really be an overflow page and the database must be corrupt.
   57022       ** It is helpful to detect this before calling freePage2(), as
   57023       ** freePage2() may zero the page contents if secure-delete mode is
   57024       ** enabled. If this 'overflow' page happens to be a page that the
   57025       ** caller is iterating through or using in some other way, this
   57026       ** can be problematic.
   57027       */
   57028       rc = SQLITE_CORRUPT_BKPT;
   57029     }else{
   57030       rc = freePage2(pBt, pOvfl, ovflPgno);
   57031     }
   57032 
   57033     if( pOvfl ){
   57034       sqlite3PagerUnref(pOvfl->pDbPage);
   57035     }
   57036     if( rc ) return rc;
   57037     ovflPgno = iNext;
   57038   }
   57039   return SQLITE_OK;
   57040 }
   57041 
   57042 /*
   57043 ** Create the byte sequence used to represent a cell on page pPage
   57044 ** and write that byte sequence into pCell[].  Overflow pages are
   57045 ** allocated and filled in as necessary.  The calling procedure
   57046 ** is responsible for making sure sufficient space has been allocated
   57047 ** for pCell[].
   57048 **
   57049 ** Note that pCell does not necessary need to point to the pPage->aData
   57050 ** area.  pCell might point to some temporary storage.  The cell will
   57051 ** be constructed in this temporary area then copied into pPage->aData
   57052 ** later.
   57053 */
   57054 static int fillInCell(
   57055   MemPage *pPage,                /* The page that contains the cell */
   57056   unsigned char *pCell,          /* Complete text of the cell */
   57057   const void *pKey, i64 nKey,    /* The key */
   57058   const void *pData,int nData,   /* The data */
   57059   int nZero,                     /* Extra zero bytes to append to pData */
   57060   int *pnSize                    /* Write cell size here */
   57061 ){
   57062   int nPayload;
   57063   const u8 *pSrc;
   57064   int nSrc, n, rc;
   57065   int spaceLeft;
   57066   MemPage *pOvfl = 0;
   57067   MemPage *pToRelease = 0;
   57068   unsigned char *pPrior;
   57069   unsigned char *pPayload;
   57070   BtShared *pBt = pPage->pBt;
   57071   Pgno pgnoOvfl = 0;
   57072   int nHeader;
   57073   CellInfo info;
   57074 
   57075   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57076 
   57077   /* pPage is not necessarily writeable since pCell might be auxiliary
   57078   ** buffer space that is separate from the pPage buffer area */
   57079   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
   57080             || sqlite3PagerIswriteable(pPage->pDbPage) );
   57081 
   57082   /* Fill in the header. */
   57083   nHeader = 0;
   57084   if( !pPage->leaf ){
   57085     nHeader += 4;
   57086   }
   57087   if( pPage->hasData ){
   57088     nHeader += putVarint32(&pCell[nHeader], nData+nZero);
   57089   }else{
   57090     nData = nZero = 0;
   57091   }
   57092   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
   57093   btreeParseCellPtr(pPage, pCell, &info);
   57094   assert( info.nHeader==nHeader );
   57095   assert( info.nKey==nKey );
   57096   assert( info.nData==(u32)(nData+nZero) );
   57097 
   57098   /* Fill in the payload */
   57099   nPayload = nData + nZero;
   57100   if( pPage->intKey ){
   57101     pSrc = pData;
   57102     nSrc = nData;
   57103     nData = 0;
   57104   }else{
   57105     if( NEVER(nKey>0x7fffffff || pKey==0) ){
   57106       return SQLITE_CORRUPT_BKPT;
   57107     }
   57108     nPayload += (int)nKey;
   57109     pSrc = pKey;
   57110     nSrc = (int)nKey;
   57111   }
   57112   *pnSize = info.nSize;
   57113   spaceLeft = info.nLocal;
   57114   pPayload = &pCell[nHeader];
   57115   pPrior = &pCell[info.iOverflow];
   57116 
   57117   while( nPayload>0 ){
   57118     if( spaceLeft==0 ){
   57119 #ifndef SQLITE_OMIT_AUTOVACUUM
   57120       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
   57121       if( pBt->autoVacuum ){
   57122         do{
   57123           pgnoOvfl++;
   57124         } while(
   57125           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
   57126         );
   57127       }
   57128 #endif
   57129       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
   57130 #ifndef SQLITE_OMIT_AUTOVACUUM
   57131       /* If the database supports auto-vacuum, and the second or subsequent
   57132       ** overflow page is being allocated, add an entry to the pointer-map
   57133       ** for that page now.
   57134       **
   57135       ** If this is the first overflow page, then write a partial entry
   57136       ** to the pointer-map. If we write nothing to this pointer-map slot,
   57137       ** then the optimistic overflow chain processing in clearCell()
   57138       ** may misinterpret the uninitialized values and delete the
   57139       ** wrong pages from the database.
   57140       */
   57141       if( pBt->autoVacuum && rc==SQLITE_OK ){
   57142         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
   57143         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
   57144         if( rc ){
   57145           releasePage(pOvfl);
   57146         }
   57147       }
   57148 #endif
   57149       if( rc ){
   57150         releasePage(pToRelease);
   57151         return rc;
   57152       }
   57153 
   57154       /* If pToRelease is not zero than pPrior points into the data area
   57155       ** of pToRelease.  Make sure pToRelease is still writeable. */
   57156       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   57157 
   57158       /* If pPrior is part of the data area of pPage, then make sure pPage
   57159       ** is still writeable */
   57160       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
   57161             || sqlite3PagerIswriteable(pPage->pDbPage) );
   57162 
   57163       put4byte(pPrior, pgnoOvfl);
   57164       releasePage(pToRelease);
   57165       pToRelease = pOvfl;
   57166       pPrior = pOvfl->aData;
   57167       put4byte(pPrior, 0);
   57168       pPayload = &pOvfl->aData[4];
   57169       spaceLeft = pBt->usableSize - 4;
   57170     }
   57171     n = nPayload;
   57172     if( n>spaceLeft ) n = spaceLeft;
   57173 
   57174     /* If pToRelease is not zero than pPayload points into the data area
   57175     ** of pToRelease.  Make sure pToRelease is still writeable. */
   57176     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   57177 
   57178     /* If pPayload is part of the data area of pPage, then make sure pPage
   57179     ** is still writeable */
   57180     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
   57181             || sqlite3PagerIswriteable(pPage->pDbPage) );
   57182 
   57183     if( nSrc>0 ){
   57184       if( n>nSrc ) n = nSrc;
   57185       assert( pSrc );
   57186       memcpy(pPayload, pSrc, n);
   57187     }else{
   57188       memset(pPayload, 0, n);
   57189     }
   57190     nPayload -= n;
   57191     pPayload += n;
   57192     pSrc += n;
   57193     nSrc -= n;
   57194     spaceLeft -= n;
   57195     if( nSrc==0 ){
   57196       nSrc = nData;
   57197       pSrc = pData;
   57198     }
   57199   }
   57200   releasePage(pToRelease);
   57201   return SQLITE_OK;
   57202 }
   57203 
   57204 /*
   57205 ** Remove the i-th cell from pPage.  This routine effects pPage only.
   57206 ** The cell content is not freed or deallocated.  It is assumed that
   57207 ** the cell content has been copied someplace else.  This routine just
   57208 ** removes the reference to the cell from pPage.
   57209 **
   57210 ** "sz" must be the number of bytes in the cell.
   57211 */
   57212 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
   57213   u32 pc;         /* Offset to cell content of cell being deleted */
   57214   u8 *data;       /* pPage->aData */
   57215   u8 *ptr;        /* Used to move bytes around within data[] */
   57216   int rc;         /* The return code */
   57217   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
   57218 
   57219   if( *pRC ) return;
   57220 
   57221   assert( idx>=0 && idx<pPage->nCell );
   57222   assert( sz==cellSize(pPage, idx) );
   57223   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   57224   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57225   data = pPage->aData;
   57226   ptr = &pPage->aCellIdx[2*idx];
   57227   pc = get2byte(ptr);
   57228   hdr = pPage->hdrOffset;
   57229   testcase( pc==get2byte(&data[hdr+5]) );
   57230   testcase( pc+sz==pPage->pBt->usableSize );
   57231   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
   57232     *pRC = SQLITE_CORRUPT_BKPT;
   57233     return;
   57234   }
   57235   rc = freeSpace(pPage, pc, sz);
   57236   if( rc ){
   57237     *pRC = rc;
   57238     return;
   57239   }
   57240   pPage->nCell--;
   57241   memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
   57242   put2byte(&data[hdr+3], pPage->nCell);
   57243   pPage->nFree += 2;
   57244 }
   57245 
   57246 /*
   57247 ** Insert a new cell on pPage at cell index "i".  pCell points to the
   57248 ** content of the cell.
   57249 **
   57250 ** If the cell content will fit on the page, then put it there.  If it
   57251 ** will not fit, then make a copy of the cell content into pTemp if
   57252 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
   57253 ** in pPage->apOvfl[] and make it point to the cell content (either
   57254 ** in pTemp or the original pCell) and also record its index.
   57255 ** Allocating a new entry in pPage->aCell[] implies that
   57256 ** pPage->nOverflow is incremented.
   57257 **
   57258 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
   57259 ** cell. The caller will overwrite them after this function returns. If
   57260 ** nSkip is non-zero, then pCell may not point to an invalid memory location
   57261 ** (but pCell+nSkip is always valid).
   57262 */
   57263 static void insertCell(
   57264   MemPage *pPage,   /* Page into which we are copying */
   57265   int i,            /* New cell becomes the i-th cell of the page */
   57266   u8 *pCell,        /* Content of the new cell */
   57267   int sz,           /* Bytes of content in pCell */
   57268   u8 *pTemp,        /* Temp storage space for pCell, if needed */
   57269   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
   57270   int *pRC          /* Read and write return code from here */
   57271 ){
   57272   int idx = 0;      /* Where to write new cell content in data[] */
   57273   int j;            /* Loop counter */
   57274   int end;          /* First byte past the last cell pointer in data[] */
   57275   int ins;          /* Index in data[] where new cell pointer is inserted */
   57276   int cellOffset;   /* Address of first cell pointer in data[] */
   57277   u8 *data;         /* The content of the whole page */
   57278   int nSkip = (iChild ? 4 : 0);
   57279 
   57280   if( *pRC ) return;
   57281 
   57282   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
   57283   assert( MX_CELL(pPage->pBt)<=10921 );
   57284   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
   57285   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
   57286   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
   57287   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57288   /* The cell should normally be sized correctly.  However, when moving a
   57289   ** malformed cell from a leaf page to an interior page, if the cell size
   57290   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
   57291   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
   57292   ** the term after the || in the following assert(). */
   57293   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
   57294   if( pPage->nOverflow || sz+2>pPage->nFree ){
   57295     if( pTemp ){
   57296       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
   57297       pCell = pTemp;
   57298     }
   57299     if( iChild ){
   57300       put4byte(pCell, iChild);
   57301     }
   57302     j = pPage->nOverflow++;
   57303     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
   57304     pPage->apOvfl[j] = pCell;
   57305     pPage->aiOvfl[j] = (u16)i;
   57306   }else{
   57307     int rc = sqlite3PagerWrite(pPage->pDbPage);
   57308     if( rc!=SQLITE_OK ){
   57309       *pRC = rc;
   57310       return;
   57311     }
   57312     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   57313     data = pPage->aData;
   57314     cellOffset = pPage->cellOffset;
   57315     end = cellOffset + 2*pPage->nCell;
   57316     ins = cellOffset + 2*i;
   57317     rc = allocateSpace(pPage, sz, &idx);
   57318     if( rc ){ *pRC = rc; return; }
   57319     /* The allocateSpace() routine guarantees the following two properties
   57320     ** if it returns success */
   57321     assert( idx >= end+2 );
   57322     assert( idx+sz <= (int)pPage->pBt->usableSize );
   57323     pPage->nCell++;
   57324     pPage->nFree -= (u16)(2 + sz);
   57325     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
   57326     if( iChild ){
   57327       put4byte(&data[idx], iChild);
   57328     }
   57329     memmove(&data[ins+2], &data[ins], end-ins);
   57330     put2byte(&data[ins], idx);
   57331     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
   57332 #ifndef SQLITE_OMIT_AUTOVACUUM
   57333     if( pPage->pBt->autoVacuum ){
   57334       /* The cell may contain a pointer to an overflow page. If so, write
   57335       ** the entry for the overflow page into the pointer map.
   57336       */
   57337       ptrmapPutOvflPtr(pPage, pCell, pRC);
   57338     }
   57339 #endif
   57340   }
   57341 }
   57342 
   57343 /*
   57344 ** Add a list of cells to a page.  The page should be initially empty.
   57345 ** The cells are guaranteed to fit on the page.
   57346 */
   57347 static void assemblePage(
   57348   MemPage *pPage,   /* The page to be assemblied */
   57349   int nCell,        /* The number of cells to add to this page */
   57350   u8 **apCell,      /* Pointers to cell bodies */
   57351   u16 *aSize        /* Sizes of the cells */
   57352 ){
   57353   int i;            /* Loop counter */
   57354   u8 *pCellptr;     /* Address of next cell pointer */
   57355   int cellbody;     /* Address of next cell body */
   57356   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
   57357   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
   57358   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
   57359 
   57360   assert( pPage->nOverflow==0 );
   57361   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57362   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
   57363             && (int)MX_CELL(pPage->pBt)<=10921);
   57364   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   57365 
   57366   /* Check that the page has just been zeroed by zeroPage() */
   57367   assert( pPage->nCell==0 );
   57368   assert( get2byteNotZero(&data[hdr+5])==nUsable );
   57369 
   57370   pCellptr = &pPage->aCellIdx[nCell*2];
   57371   cellbody = nUsable;
   57372   for(i=nCell-1; i>=0; i--){
   57373     u16 sz = aSize[i];
   57374     pCellptr -= 2;
   57375     cellbody -= sz;
   57376     put2byte(pCellptr, cellbody);
   57377     memcpy(&data[cellbody], apCell[i], sz);
   57378   }
   57379   put2byte(&data[hdr+3], nCell);
   57380   put2byte(&data[hdr+5], cellbody);
   57381   pPage->nFree -= (nCell*2 + nUsable - cellbody);
   57382   pPage->nCell = (u16)nCell;
   57383 }
   57384 
   57385 /*
   57386 ** The following parameters determine how many adjacent pages get involved
   57387 ** in a balancing operation.  NN is the number of neighbors on either side
   57388 ** of the page that participate in the balancing operation.  NB is the
   57389 ** total number of pages that participate, including the target page and
   57390 ** NN neighbors on either side.
   57391 **
   57392 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
   57393 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
   57394 ** in exchange for a larger degradation in INSERT and UPDATE performance.
   57395 ** The value of NN appears to give the best results overall.
   57396 */
   57397 #define NN 1             /* Number of neighbors on either side of pPage */
   57398 #define NB (NN*2+1)      /* Total pages involved in the balance */
   57399 
   57400 
   57401 #ifndef SQLITE_OMIT_QUICKBALANCE
   57402 /*
   57403 ** This version of balance() handles the common special case where
   57404 ** a new entry is being inserted on the extreme right-end of the
   57405 ** tree, in other words, when the new entry will become the largest
   57406 ** entry in the tree.
   57407 **
   57408 ** Instead of trying to balance the 3 right-most leaf pages, just add
   57409 ** a new page to the right-hand side and put the one new entry in
   57410 ** that page.  This leaves the right side of the tree somewhat
   57411 ** unbalanced.  But odds are that we will be inserting new entries
   57412 ** at the end soon afterwards so the nearly empty page will quickly
   57413 ** fill up.  On average.
   57414 **
   57415 ** pPage is the leaf page which is the right-most page in the tree.
   57416 ** pParent is its parent.  pPage must have a single overflow entry
   57417 ** which is also the right-most entry on the page.
   57418 **
   57419 ** The pSpace buffer is used to store a temporary copy of the divider
   57420 ** cell that will be inserted into pParent. Such a cell consists of a 4
   57421 ** byte page number followed by a variable length integer. In other
   57422 ** words, at most 13 bytes. Hence the pSpace buffer must be at
   57423 ** least 13 bytes in size.
   57424 */
   57425 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
   57426   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
   57427   MemPage *pNew;                       /* Newly allocated page */
   57428   int rc;                              /* Return Code */
   57429   Pgno pgnoNew;                        /* Page number of pNew */
   57430 
   57431   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   57432   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   57433   assert( pPage->nOverflow==1 );
   57434 
   57435   /* This error condition is now caught prior to reaching this function */
   57436   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
   57437 
   57438   /* Allocate a new page. This page will become the right-sibling of
   57439   ** pPage. Make the parent page writable, so that the new divider cell
   57440   ** may be inserted. If both these operations are successful, proceed.
   57441   */
   57442   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
   57443 
   57444   if( rc==SQLITE_OK ){
   57445 
   57446     u8 *pOut = &pSpace[4];
   57447     u8 *pCell = pPage->apOvfl[0];
   57448     u16 szCell = cellSizePtr(pPage, pCell);
   57449     u8 *pStop;
   57450 
   57451     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
   57452     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
   57453     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
   57454     assemblePage(pNew, 1, &pCell, &szCell);
   57455 
   57456     /* If this is an auto-vacuum database, update the pointer map
   57457     ** with entries for the new page, and any pointer from the
   57458     ** cell on the page to an overflow page. If either of these
   57459     ** operations fails, the return code is set, but the contents
   57460     ** of the parent page are still manipulated by thh code below.
   57461     ** That is Ok, at this point the parent page is guaranteed to
   57462     ** be marked as dirty. Returning an error code will cause a
   57463     ** rollback, undoing any changes made to the parent page.
   57464     */
   57465     if( ISAUTOVACUUM ){
   57466       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
   57467       if( szCell>pNew->minLocal ){
   57468         ptrmapPutOvflPtr(pNew, pCell, &rc);
   57469       }
   57470     }
   57471 
   57472     /* Create a divider cell to insert into pParent. The divider cell
   57473     ** consists of a 4-byte page number (the page number of pPage) and
   57474     ** a variable length key value (which must be the same value as the
   57475     ** largest key on pPage).
   57476     **
   57477     ** To find the largest key value on pPage, first find the right-most
   57478     ** cell on pPage. The first two fields of this cell are the
   57479     ** record-length (a variable length integer at most 32-bits in size)
   57480     ** and the key value (a variable length integer, may have any value).
   57481     ** The first of the while(...) loops below skips over the record-length
   57482     ** field. The second while(...) loop copies the key value from the
   57483     ** cell on pPage into the pSpace buffer.
   57484     */
   57485     pCell = findCell(pPage, pPage->nCell-1);
   57486     pStop = &pCell[9];
   57487     while( (*(pCell++)&0x80) && pCell<pStop );
   57488     pStop = &pCell[9];
   57489     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
   57490 
   57491     /* Insert the new divider cell into pParent. */
   57492     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
   57493                0, pPage->pgno, &rc);
   57494 
   57495     /* Set the right-child pointer of pParent to point to the new page. */
   57496     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
   57497 
   57498     /* Release the reference to the new page. */
   57499     releasePage(pNew);
   57500   }
   57501 
   57502   return rc;
   57503 }
   57504 #endif /* SQLITE_OMIT_QUICKBALANCE */
   57505 
   57506 #if 0
   57507 /*
   57508 ** This function does not contribute anything to the operation of SQLite.
   57509 ** it is sometimes activated temporarily while debugging code responsible
   57510 ** for setting pointer-map entries.
   57511 */
   57512 static int ptrmapCheckPages(MemPage **apPage, int nPage){
   57513   int i, j;
   57514   for(i=0; i<nPage; i++){
   57515     Pgno n;
   57516     u8 e;
   57517     MemPage *pPage = apPage[i];
   57518     BtShared *pBt = pPage->pBt;
   57519     assert( pPage->isInit );
   57520 
   57521     for(j=0; j<pPage->nCell; j++){
   57522       CellInfo info;
   57523       u8 *z;
   57524 
   57525       z = findCell(pPage, j);
   57526       btreeParseCellPtr(pPage, z, &info);
   57527       if( info.iOverflow ){
   57528         Pgno ovfl = get4byte(&z[info.iOverflow]);
   57529         ptrmapGet(pBt, ovfl, &e, &n);
   57530         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
   57531       }
   57532       if( !pPage->leaf ){
   57533         Pgno child = get4byte(z);
   57534         ptrmapGet(pBt, child, &e, &n);
   57535         assert( n==pPage->pgno && e==PTRMAP_BTREE );
   57536       }
   57537     }
   57538     if( !pPage->leaf ){
   57539       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   57540       ptrmapGet(pBt, child, &e, &n);
   57541       assert( n==pPage->pgno && e==PTRMAP_BTREE );
   57542     }
   57543   }
   57544   return 1;
   57545 }
   57546 #endif
   57547 
   57548 /*
   57549 ** This function is used to copy the contents of the b-tree node stored
   57550 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
   57551 ** the pointer-map entries for each child page are updated so that the
   57552 ** parent page stored in the pointer map is page pTo. If pFrom contained
   57553 ** any cells with overflow page pointers, then the corresponding pointer
   57554 ** map entries are also updated so that the parent page is page pTo.
   57555 **
   57556 ** If pFrom is currently carrying any overflow cells (entries in the
   57557 ** MemPage.apOvfl[] array), they are not copied to pTo.
   57558 **
   57559 ** Before returning, page pTo is reinitialized using btreeInitPage().
   57560 **
   57561 ** The performance of this function is not critical. It is only used by
   57562 ** the balance_shallower() and balance_deeper() procedures, neither of
   57563 ** which are called often under normal circumstances.
   57564 */
   57565 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
   57566   if( (*pRC)==SQLITE_OK ){
   57567     BtShared * const pBt = pFrom->pBt;
   57568     u8 * const aFrom = pFrom->aData;
   57569     u8 * const aTo = pTo->aData;
   57570     int const iFromHdr = pFrom->hdrOffset;
   57571     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
   57572     int rc;
   57573     int iData;
   57574 
   57575 
   57576     assert( pFrom->isInit );
   57577     assert( pFrom->nFree>=iToHdr );
   57578     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
   57579 
   57580     /* Copy the b-tree node content from page pFrom to page pTo. */
   57581     iData = get2byte(&aFrom[iFromHdr+5]);
   57582     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
   57583     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
   57584 
   57585     /* Reinitialize page pTo so that the contents of the MemPage structure
   57586     ** match the new data. The initialization of pTo can actually fail under
   57587     ** fairly obscure circumstances, even though it is a copy of initialized
   57588     ** page pFrom.
   57589     */
   57590     pTo->isInit = 0;
   57591     rc = btreeInitPage(pTo);
   57592     if( rc!=SQLITE_OK ){
   57593       *pRC = rc;
   57594       return;
   57595     }
   57596 
   57597     /* If this is an auto-vacuum database, update the pointer-map entries
   57598     ** for any b-tree or overflow pages that pTo now contains the pointers to.
   57599     */
   57600     if( ISAUTOVACUUM ){
   57601       *pRC = setChildPtrmaps(pTo);
   57602     }
   57603   }
   57604 }
   57605 
   57606 /*
   57607 ** This routine redistributes cells on the iParentIdx'th child of pParent
   57608 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
   57609 ** same amount of free space. Usually a single sibling on either side of the
   57610 ** page are used in the balancing, though both siblings might come from one
   57611 ** side if the page is the first or last child of its parent. If the page
   57612 ** has fewer than 2 siblings (something which can only happen if the page
   57613 ** is a root page or a child of a root page) then all available siblings
   57614 ** participate in the balancing.
   57615 **
   57616 ** The number of siblings of the page might be increased or decreased by
   57617 ** one or two in an effort to keep pages nearly full but not over full.
   57618 **
   57619 ** Note that when this routine is called, some of the cells on the page
   57620 ** might not actually be stored in MemPage.aData[]. This can happen
   57621 ** if the page is overfull. This routine ensures that all cells allocated
   57622 ** to the page and its siblings fit into MemPage.aData[] before returning.
   57623 **
   57624 ** In the course of balancing the page and its siblings, cells may be
   57625 ** inserted into or removed from the parent page (pParent). Doing so
   57626 ** may cause the parent page to become overfull or underfull. If this
   57627 ** happens, it is the responsibility of the caller to invoke the correct
   57628 ** balancing routine to fix this problem (see the balance() routine).
   57629 **
   57630 ** If this routine fails for any reason, it might leave the database
   57631 ** in a corrupted state. So if this routine fails, the database should
   57632 ** be rolled back.
   57633 **
   57634 ** The third argument to this function, aOvflSpace, is a pointer to a
   57635 ** buffer big enough to hold one page. If while inserting cells into the parent
   57636 ** page (pParent) the parent page becomes overfull, this buffer is
   57637 ** used to store the parent's overflow cells. Because this function inserts
   57638 ** a maximum of four divider cells into the parent page, and the maximum
   57639 ** size of a cell stored within an internal node is always less than 1/4
   57640 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
   57641 ** enough for all overflow cells.
   57642 **
   57643 ** If aOvflSpace is set to a null pointer, this function returns
   57644 ** SQLITE_NOMEM.
   57645 */
   57646 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
   57647 #pragma optimize("", off)
   57648 #endif
   57649 static int balance_nonroot(
   57650   MemPage *pParent,               /* Parent page of siblings being balanced */
   57651   int iParentIdx,                 /* Index of "the page" in pParent */
   57652   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
   57653   int isRoot,                     /* True if pParent is a root-page */
   57654   int bBulk                       /* True if this call is part of a bulk load */
   57655 ){
   57656   BtShared *pBt;               /* The whole database */
   57657   int nCell = 0;               /* Number of cells in apCell[] */
   57658   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
   57659   int nNew = 0;                /* Number of pages in apNew[] */
   57660   int nOld;                    /* Number of pages in apOld[] */
   57661   int i, j, k;                 /* Loop counters */
   57662   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
   57663   int rc = SQLITE_OK;          /* The return code */
   57664   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
   57665   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
   57666   int usableSpace;             /* Bytes in pPage beyond the header */
   57667   int pageFlags;               /* Value of pPage->aData[0] */
   57668   int subtotal;                /* Subtotal of bytes in cells on one page */
   57669   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
   57670   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
   57671   int szScratch;               /* Size of scratch memory requested */
   57672   MemPage *apOld[NB];          /* pPage and up to two siblings */
   57673   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
   57674   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
   57675   u8 *pRight;                  /* Location in parent of right-sibling pointer */
   57676   u8 *apDiv[NB-1];             /* Divider cells in pParent */
   57677   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
   57678   int szNew[NB+2];             /* Combined size of cells place on i-th page */
   57679   u8 **apCell = 0;             /* All cells begin balanced */
   57680   u16 *szCell;                 /* Local size of all cells in apCell[] */
   57681   u8 *aSpace1;                 /* Space for copies of dividers cells */
   57682   Pgno pgno;                   /* Temp var to store a page number in */
   57683 
   57684   pBt = pParent->pBt;
   57685   assert( sqlite3_mutex_held(pBt->mutex) );
   57686   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   57687 
   57688 #if 0
   57689   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
   57690 #endif
   57691 
   57692   /* At this point pParent may have at most one overflow cell. And if
   57693   ** this overflow cell is present, it must be the cell with
   57694   ** index iParentIdx. This scenario comes about when this function
   57695   ** is called (indirectly) from sqlite3BtreeDelete().
   57696   */
   57697   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
   57698   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
   57699 
   57700   if( !aOvflSpace ){
   57701     return SQLITE_NOMEM;
   57702   }
   57703 
   57704   /* Find the sibling pages to balance. Also locate the cells in pParent
   57705   ** that divide the siblings. An attempt is made to find NN siblings on
   57706   ** either side of pPage. More siblings are taken from one side, however,
   57707   ** if there are fewer than NN siblings on the other side. If pParent
   57708   ** has NB or fewer children then all children of pParent are taken.
   57709   **
   57710   ** This loop also drops the divider cells from the parent page. This
   57711   ** way, the remainder of the function does not have to deal with any
   57712   ** overflow cells in the parent page, since if any existed they will
   57713   ** have already been removed.
   57714   */
   57715   i = pParent->nOverflow + pParent->nCell;
   57716   if( i<2 ){
   57717     nxDiv = 0;
   57718   }else{
   57719     assert( bBulk==0 || bBulk==1 );
   57720     if( iParentIdx==0 ){
   57721       nxDiv = 0;
   57722     }else if( iParentIdx==i ){
   57723       nxDiv = i-2+bBulk;
   57724     }else{
   57725       assert( bBulk==0 );
   57726       nxDiv = iParentIdx-1;
   57727     }
   57728     i = 2-bBulk;
   57729   }
   57730   nOld = i+1;
   57731   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
   57732     pRight = &pParent->aData[pParent->hdrOffset+8];
   57733   }else{
   57734     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
   57735   }
   57736   pgno = get4byte(pRight);
   57737   while( 1 ){
   57738     rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
   57739     if( rc ){
   57740       memset(apOld, 0, (i+1)*sizeof(MemPage*));
   57741       goto balance_cleanup;
   57742     }
   57743     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
   57744     if( (i--)==0 ) break;
   57745 
   57746     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
   57747       apDiv[i] = pParent->apOvfl[0];
   57748       pgno = get4byte(apDiv[i]);
   57749       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   57750       pParent->nOverflow = 0;
   57751     }else{
   57752       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
   57753       pgno = get4byte(apDiv[i]);
   57754       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   57755 
   57756       /* Drop the cell from the parent page. apDiv[i] still points to
   57757       ** the cell within the parent, even though it has been dropped.
   57758       ** This is safe because dropping a cell only overwrites the first
   57759       ** four bytes of it, and this function does not need the first
   57760       ** four bytes of the divider cell. So the pointer is safe to use
   57761       ** later on.
   57762       **
   57763       ** But not if we are in secure-delete mode. In secure-delete mode,
   57764       ** the dropCell() routine will overwrite the entire cell with zeroes.
   57765       ** In this case, temporarily copy the cell into the aOvflSpace[]
   57766       ** buffer. It will be copied out again as soon as the aSpace[] buffer
   57767       ** is allocated.  */
   57768       if( pBt->btsFlags & BTS_SECURE_DELETE ){
   57769         int iOff;
   57770 
   57771         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
   57772         if( (iOff+szNew[i])>(int)pBt->usableSize ){
   57773           rc = SQLITE_CORRUPT_BKPT;
   57774           memset(apOld, 0, (i+1)*sizeof(MemPage*));
   57775           goto balance_cleanup;
   57776         }else{
   57777           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
   57778           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
   57779         }
   57780       }
   57781       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
   57782     }
   57783   }
   57784 
   57785   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
   57786   ** alignment */
   57787   nMaxCells = (nMaxCells + 3)&~3;
   57788 
   57789   /*
   57790   ** Allocate space for memory structures
   57791   */
   57792   k = pBt->pageSize + ROUND8(sizeof(MemPage));
   57793   szScratch =
   57794        nMaxCells*sizeof(u8*)                       /* apCell */
   57795      + nMaxCells*sizeof(u16)                       /* szCell */
   57796      + pBt->pageSize                               /* aSpace1 */
   57797      + k*nOld;                                     /* Page copies (apCopy) */
   57798   apCell = sqlite3ScratchMalloc( szScratch );
   57799   if( apCell==0 ){
   57800     rc = SQLITE_NOMEM;
   57801     goto balance_cleanup;
   57802   }
   57803   szCell = (u16*)&apCell[nMaxCells];
   57804   aSpace1 = (u8*)&szCell[nMaxCells];
   57805   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
   57806 
   57807   /*
   57808   ** Load pointers to all cells on sibling pages and the divider cells
   57809   ** into the local apCell[] array.  Make copies of the divider cells
   57810   ** into space obtained from aSpace1[] and remove the divider cells
   57811   ** from pParent.
   57812   **
   57813   ** If the siblings are on leaf pages, then the child pointers of the
   57814   ** divider cells are stripped from the cells before they are copied
   57815   ** into aSpace1[].  In this way, all cells in apCell[] are without
   57816   ** child pointers.  If siblings are not leaves, then all cell in
   57817   ** apCell[] include child pointers.  Either way, all cells in apCell[]
   57818   ** are alike.
   57819   **
   57820   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
   57821   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
   57822   */
   57823   leafCorrection = apOld[0]->leaf*4;
   57824   leafData = apOld[0]->hasData;
   57825   for(i=0; i<nOld; i++){
   57826     int limit;
   57827 
   57828     /* Before doing anything else, take a copy of the i'th original sibling
   57829     ** The rest of this function will use data from the copies rather
   57830     ** that the original pages since the original pages will be in the
   57831     ** process of being overwritten.  */
   57832     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
   57833     memcpy(pOld, apOld[i], sizeof(MemPage));
   57834     pOld->aData = (void*)&pOld[1];
   57835     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
   57836 
   57837     limit = pOld->nCell+pOld->nOverflow;
   57838     if( pOld->nOverflow>0 ){
   57839       for(j=0; j<limit; j++){
   57840         assert( nCell<nMaxCells );
   57841         apCell[nCell] = findOverflowCell(pOld, j);
   57842         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   57843         nCell++;
   57844       }
   57845     }else{
   57846       u8 *aData = pOld->aData;
   57847       u16 maskPage = pOld->maskPage;
   57848       u16 cellOffset = pOld->cellOffset;
   57849       for(j=0; j<limit; j++){
   57850         assert( nCell<nMaxCells );
   57851         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
   57852         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   57853         nCell++;
   57854       }
   57855     }
   57856     if( i<nOld-1 && !leafData){
   57857       u16 sz = (u16)szNew[i];
   57858       u8 *pTemp;
   57859       assert( nCell<nMaxCells );
   57860       szCell[nCell] = sz;
   57861       pTemp = &aSpace1[iSpace1];
   57862       iSpace1 += sz;
   57863       assert( sz<=pBt->maxLocal+23 );
   57864       assert( iSpace1 <= (int)pBt->pageSize );
   57865       memcpy(pTemp, apDiv[i], sz);
   57866       apCell[nCell] = pTemp+leafCorrection;
   57867       assert( leafCorrection==0 || leafCorrection==4 );
   57868       szCell[nCell] = szCell[nCell] - leafCorrection;
   57869       if( !pOld->leaf ){
   57870         assert( leafCorrection==0 );
   57871         assert( pOld->hdrOffset==0 );
   57872         /* The right pointer of the child page pOld becomes the left
   57873         ** pointer of the divider cell */
   57874         memcpy(apCell[nCell], &pOld->aData[8], 4);
   57875       }else{
   57876         assert( leafCorrection==4 );
   57877         if( szCell[nCell]<4 ){
   57878           /* Do not allow any cells smaller than 4 bytes. */
   57879           szCell[nCell] = 4;
   57880         }
   57881       }
   57882       nCell++;
   57883     }
   57884   }
   57885 
   57886   /*
   57887   ** Figure out the number of pages needed to hold all nCell cells.
   57888   ** Store this number in "k".  Also compute szNew[] which is the total
   57889   ** size of all cells on the i-th page and cntNew[] which is the index
   57890   ** in apCell[] of the cell that divides page i from page i+1.
   57891   ** cntNew[k] should equal nCell.
   57892   **
   57893   ** Values computed by this block:
   57894   **
   57895   **           k: The total number of sibling pages
   57896   **    szNew[i]: Spaced used on the i-th sibling page.
   57897   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
   57898   **              the right of the i-th sibling page.
   57899   ** usableSpace: Number of bytes of space available on each sibling.
   57900   **
   57901   */
   57902   usableSpace = pBt->usableSize - 12 + leafCorrection;
   57903   for(subtotal=k=i=0; i<nCell; i++){
   57904     assert( i<nMaxCells );
   57905     subtotal += szCell[i] + 2;
   57906     if( subtotal > usableSpace ){
   57907       szNew[k] = subtotal - szCell[i];
   57908       cntNew[k] = i;
   57909       if( leafData ){ i--; }
   57910       subtotal = 0;
   57911       k++;
   57912       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
   57913     }
   57914   }
   57915   szNew[k] = subtotal;
   57916   cntNew[k] = nCell;
   57917   k++;
   57918 
   57919   /*
   57920   ** The packing computed by the previous block is biased toward the siblings
   57921   ** on the left side.  The left siblings are always nearly full, while the
   57922   ** right-most sibling might be nearly empty.  This block of code attempts
   57923   ** to adjust the packing of siblings to get a better balance.
   57924   **
   57925   ** This adjustment is more than an optimization.  The packing above might
   57926   ** be so out of balance as to be illegal.  For example, the right-most
   57927   ** sibling might be completely empty.  This adjustment is not optional.
   57928   */
   57929   for(i=k-1; i>0; i--){
   57930     int szRight = szNew[i];  /* Size of sibling on the right */
   57931     int szLeft = szNew[i-1]; /* Size of sibling on the left */
   57932     int r;              /* Index of right-most cell in left sibling */
   57933     int d;              /* Index of first cell to the left of right sibling */
   57934 
   57935     r = cntNew[i-1] - 1;
   57936     d = r + 1 - leafData;
   57937     assert( d<nMaxCells );
   57938     assert( r<nMaxCells );
   57939     while( szRight==0
   57940        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
   57941     ){
   57942       szRight += szCell[d] + 2;
   57943       szLeft -= szCell[r] + 2;
   57944       cntNew[i-1]--;
   57945       r = cntNew[i-1] - 1;
   57946       d = r + 1 - leafData;
   57947     }
   57948     szNew[i] = szRight;
   57949     szNew[i-1] = szLeft;
   57950   }
   57951 
   57952   /* Either we found one or more cells (cntnew[0])>0) or pPage is
   57953   ** a virtual root page.  A virtual root page is when the real root
   57954   ** page is page 1 and we are the only child of that page.
   57955   **
   57956   ** UPDATE:  The assert() below is not necessarily true if the database
   57957   ** file is corrupt.  The corruption will be detected and reported later
   57958   ** in this procedure so there is no need to act upon it now.
   57959   */
   57960 #if 0
   57961   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
   57962 #endif
   57963 
   57964   TRACE(("BALANCE: old: %d %d %d  ",
   57965     apOld[0]->pgno,
   57966     nOld>=2 ? apOld[1]->pgno : 0,
   57967     nOld>=3 ? apOld[2]->pgno : 0
   57968   ));
   57969 
   57970   /*
   57971   ** Allocate k new pages.  Reuse old pages where possible.
   57972   */
   57973   if( apOld[0]->pgno<=1 ){
   57974     rc = SQLITE_CORRUPT_BKPT;
   57975     goto balance_cleanup;
   57976   }
   57977   pageFlags = apOld[0]->aData[0];
   57978   for(i=0; i<k; i++){
   57979     MemPage *pNew;
   57980     if( i<nOld ){
   57981       pNew = apNew[i] = apOld[i];
   57982       apOld[i] = 0;
   57983       rc = sqlite3PagerWrite(pNew->pDbPage);
   57984       nNew++;
   57985       if( rc ) goto balance_cleanup;
   57986     }else{
   57987       assert( i>0 );
   57988       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
   57989       if( rc ) goto balance_cleanup;
   57990       apNew[i] = pNew;
   57991       nNew++;
   57992 
   57993       /* Set the pointer-map entry for the new sibling page. */
   57994       if( ISAUTOVACUUM ){
   57995         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
   57996         if( rc!=SQLITE_OK ){
   57997           goto balance_cleanup;
   57998         }
   57999       }
   58000     }
   58001   }
   58002 
   58003   /* Free any old pages that were not reused as new pages.
   58004   */
   58005   while( i<nOld ){
   58006     freePage(apOld[i], &rc);
   58007     if( rc ) goto balance_cleanup;
   58008     releasePage(apOld[i]);
   58009     apOld[i] = 0;
   58010     i++;
   58011   }
   58012 
   58013   /*
   58014   ** Put the new pages in accending order.  This helps to
   58015   ** keep entries in the disk file in order so that a scan
   58016   ** of the table is a linear scan through the file.  That
   58017   ** in turn helps the operating system to deliver pages
   58018   ** from the disk more rapidly.
   58019   **
   58020   ** An O(n^2) insertion sort algorithm is used, but since
   58021   ** n is never more than NB (a small constant), that should
   58022   ** not be a problem.
   58023   **
   58024   ** When NB==3, this one optimization makes the database
   58025   ** about 25% faster for large insertions and deletions.
   58026   */
   58027   for(i=0; i<k-1; i++){
   58028     int minV = apNew[i]->pgno;
   58029     int minI = i;
   58030     for(j=i+1; j<k; j++){
   58031       if( apNew[j]->pgno<(unsigned)minV ){
   58032         minI = j;
   58033         minV = apNew[j]->pgno;
   58034       }
   58035     }
   58036     if( minI>i ){
   58037       MemPage *pT;
   58038       pT = apNew[i];
   58039       apNew[i] = apNew[minI];
   58040       apNew[minI] = pT;
   58041     }
   58042   }
   58043   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
   58044     apNew[0]->pgno, szNew[0],
   58045     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
   58046     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
   58047     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
   58048     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
   58049 
   58050   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   58051   put4byte(pRight, apNew[nNew-1]->pgno);
   58052 
   58053   /*
   58054   ** Evenly distribute the data in apCell[] across the new pages.
   58055   ** Insert divider cells into pParent as necessary.
   58056   */
   58057   j = 0;
   58058   for(i=0; i<nNew; i++){
   58059     /* Assemble the new sibling page. */
   58060     MemPage *pNew = apNew[i];
   58061     assert( j<nMaxCells );
   58062     zeroPage(pNew, pageFlags);
   58063     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
   58064     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
   58065     assert( pNew->nOverflow==0 );
   58066 
   58067     j = cntNew[i];
   58068 
   58069     /* If the sibling page assembled above was not the right-most sibling,
   58070     ** insert a divider cell into the parent page.
   58071     */
   58072     assert( i<nNew-1 || j==nCell );
   58073     if( j<nCell ){
   58074       u8 *pCell;
   58075       u8 *pTemp;
   58076       int sz;
   58077 
   58078       assert( j<nMaxCells );
   58079       pCell = apCell[j];
   58080       sz = szCell[j] + leafCorrection;
   58081       pTemp = &aOvflSpace[iOvflSpace];
   58082       if( !pNew->leaf ){
   58083         memcpy(&pNew->aData[8], pCell, 4);
   58084       }else if( leafData ){
   58085         /* If the tree is a leaf-data tree, and the siblings are leaves,
   58086         ** then there is no divider cell in apCell[]. Instead, the divider
   58087         ** cell consists of the integer key for the right-most cell of
   58088         ** the sibling-page assembled above only.
   58089         */
   58090         CellInfo info;
   58091         j--;
   58092         btreeParseCellPtr(pNew, apCell[j], &info);
   58093         pCell = pTemp;
   58094         sz = 4 + putVarint(&pCell[4], info.nKey);
   58095         pTemp = 0;
   58096       }else{
   58097         pCell -= 4;
   58098         /* Obscure case for non-leaf-data trees: If the cell at pCell was
   58099         ** previously stored on a leaf node, and its reported size was 4
   58100         ** bytes, then it may actually be smaller than this
   58101         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
   58102         ** any cell). But it is important to pass the correct size to
   58103         ** insertCell(), so reparse the cell now.
   58104         **
   58105         ** Note that this can never happen in an SQLite data file, as all
   58106         ** cells are at least 4 bytes. It only happens in b-trees used
   58107         ** to evaluate "IN (SELECT ...)" and similar clauses.
   58108         */
   58109         if( szCell[j]==4 ){
   58110           assert(leafCorrection==4);
   58111           sz = cellSizePtr(pParent, pCell);
   58112         }
   58113       }
   58114       iOvflSpace += sz;
   58115       assert( sz<=pBt->maxLocal+23 );
   58116       assert( iOvflSpace <= (int)pBt->pageSize );
   58117       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
   58118       if( rc!=SQLITE_OK ) goto balance_cleanup;
   58119       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   58120 
   58121       j++;
   58122       nxDiv++;
   58123     }
   58124   }
   58125   assert( j==nCell );
   58126   assert( nOld>0 );
   58127   assert( nNew>0 );
   58128   if( (pageFlags & PTF_LEAF)==0 ){
   58129     u8 *zChild = &apCopy[nOld-1]->aData[8];
   58130     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
   58131   }
   58132 
   58133   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
   58134     /* The root page of the b-tree now contains no cells. The only sibling
   58135     ** page is the right-child of the parent. Copy the contents of the
   58136     ** child page into the parent, decreasing the overall height of the
   58137     ** b-tree structure by one. This is described as the "balance-shallower"
   58138     ** sub-algorithm in some documentation.
   58139     **
   58140     ** If this is an auto-vacuum database, the call to copyNodeContent()
   58141     ** sets all pointer-map entries corresponding to database image pages
   58142     ** for which the pointer is stored within the content being copied.
   58143     **
   58144     ** The second assert below verifies that the child page is defragmented
   58145     ** (it must be, as it was just reconstructed using assemblePage()). This
   58146     ** is important if the parent page happens to be page 1 of the database
   58147     ** image.  */
   58148     assert( nNew==1 );
   58149     assert( apNew[0]->nFree ==
   58150         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
   58151     );
   58152     copyNodeContent(apNew[0], pParent, &rc);
   58153     freePage(apNew[0], &rc);
   58154   }else if( ISAUTOVACUUM ){
   58155     /* Fix the pointer-map entries for all the cells that were shifted around.
   58156     ** There are several different types of pointer-map entries that need to
   58157     ** be dealt with by this routine. Some of these have been set already, but
   58158     ** many have not. The following is a summary:
   58159     **
   58160     **   1) The entries associated with new sibling pages that were not
   58161     **      siblings when this function was called. These have already
   58162     **      been set. We don't need to worry about old siblings that were
   58163     **      moved to the free-list - the freePage() code has taken care
   58164     **      of those.
   58165     **
   58166     **   2) The pointer-map entries associated with the first overflow
   58167     **      page in any overflow chains used by new divider cells. These
   58168     **      have also already been taken care of by the insertCell() code.
   58169     **
   58170     **   3) If the sibling pages are not leaves, then the child pages of
   58171     **      cells stored on the sibling pages may need to be updated.
   58172     **
   58173     **   4) If the sibling pages are not internal intkey nodes, then any
   58174     **      overflow pages used by these cells may need to be updated
   58175     **      (internal intkey nodes never contain pointers to overflow pages).
   58176     **
   58177     **   5) If the sibling pages are not leaves, then the pointer-map
   58178     **      entries for the right-child pages of each sibling may need
   58179     **      to be updated.
   58180     **
   58181     ** Cases 1 and 2 are dealt with above by other code. The next
   58182     ** block deals with cases 3 and 4 and the one after that, case 5. Since
   58183     ** setting a pointer map entry is a relatively expensive operation, this
   58184     ** code only sets pointer map entries for child or overflow pages that have
   58185     ** actually moved between pages.  */
   58186     MemPage *pNew = apNew[0];
   58187     MemPage *pOld = apCopy[0];
   58188     int nOverflow = pOld->nOverflow;
   58189     int iNextOld = pOld->nCell + nOverflow;
   58190     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
   58191     j = 0;                             /* Current 'old' sibling page */
   58192     k = 0;                             /* Current 'new' sibling page */
   58193     for(i=0; i<nCell; i++){
   58194       int isDivider = 0;
   58195       while( i==iNextOld ){
   58196         /* Cell i is the cell immediately following the last cell on old
   58197         ** sibling page j. If the siblings are not leaf pages of an
   58198         ** intkey b-tree, then cell i was a divider cell. */
   58199         assert( j+1 < ArraySize(apCopy) );
   58200         assert( j+1 < nOld );
   58201         pOld = apCopy[++j];
   58202         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
   58203         if( pOld->nOverflow ){
   58204           nOverflow = pOld->nOverflow;
   58205           iOverflow = i + !leafData + pOld->aiOvfl[0];
   58206         }
   58207         isDivider = !leafData;
   58208       }
   58209 
   58210       assert(nOverflow>0 || iOverflow<i );
   58211       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
   58212       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
   58213       if( i==iOverflow ){
   58214         isDivider = 1;
   58215         if( (--nOverflow)>0 ){
   58216           iOverflow++;
   58217         }
   58218       }
   58219 
   58220       if( i==cntNew[k] ){
   58221         /* Cell i is the cell immediately following the last cell on new
   58222         ** sibling page k. If the siblings are not leaf pages of an
   58223         ** intkey b-tree, then cell i is a divider cell.  */
   58224         pNew = apNew[++k];
   58225         if( !leafData ) continue;
   58226       }
   58227       assert( j<nOld );
   58228       assert( k<nNew );
   58229 
   58230       /* If the cell was originally divider cell (and is not now) or
   58231       ** an overflow cell, or if the cell was located on a different sibling
   58232       ** page before the balancing, then the pointer map entries associated
   58233       ** with any child or overflow pages need to be updated.  */
   58234       if( isDivider || pOld->pgno!=pNew->pgno ){
   58235         if( !leafCorrection ){
   58236           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
   58237         }
   58238         if( szCell[i]>pNew->minLocal ){
   58239           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
   58240         }
   58241       }
   58242     }
   58243 
   58244     if( !leafCorrection ){
   58245       for(i=0; i<nNew; i++){
   58246         u32 key = get4byte(&apNew[i]->aData[8]);
   58247         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
   58248       }
   58249     }
   58250 
   58251 #if 0
   58252     /* The ptrmapCheckPages() contains assert() statements that verify that
   58253     ** all pointer map pages are set correctly. This is helpful while
   58254     ** debugging. This is usually disabled because a corrupt database may
   58255     ** cause an assert() statement to fail.  */
   58256     ptrmapCheckPages(apNew, nNew);
   58257     ptrmapCheckPages(&pParent, 1);
   58258 #endif
   58259   }
   58260 
   58261   assert( pParent->isInit );
   58262   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
   58263           nOld, nNew, nCell));
   58264 
   58265   /*
   58266   ** Cleanup before returning.
   58267   */
   58268 balance_cleanup:
   58269   sqlite3ScratchFree(apCell);
   58270   for(i=0; i<nOld; i++){
   58271     releasePage(apOld[i]);
   58272   }
   58273   for(i=0; i<nNew; i++){
   58274     releasePage(apNew[i]);
   58275   }
   58276 
   58277   return rc;
   58278 }
   58279 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
   58280 #pragma optimize("", on)
   58281 #endif
   58282 
   58283 
   58284 /*
   58285 ** This function is called when the root page of a b-tree structure is
   58286 ** overfull (has one or more overflow pages).
   58287 **
   58288 ** A new child page is allocated and the contents of the current root
   58289 ** page, including overflow cells, are copied into the child. The root
   58290 ** page is then overwritten to make it an empty page with the right-child
   58291 ** pointer pointing to the new page.
   58292 **
   58293 ** Before returning, all pointer-map entries corresponding to pages
   58294 ** that the new child-page now contains pointers to are updated. The
   58295 ** entry corresponding to the new right-child pointer of the root
   58296 ** page is also updated.
   58297 **
   58298 ** If successful, *ppChild is set to contain a reference to the child
   58299 ** page and SQLITE_OK is returned. In this case the caller is required
   58300 ** to call releasePage() on *ppChild exactly once. If an error occurs,
   58301 ** an error code is returned and *ppChild is set to 0.
   58302 */
   58303 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
   58304   int rc;                        /* Return value from subprocedures */
   58305   MemPage *pChild = 0;           /* Pointer to a new child page */
   58306   Pgno pgnoChild = 0;            /* Page number of the new child page */
   58307   BtShared *pBt = pRoot->pBt;    /* The BTree */
   58308 
   58309   assert( pRoot->nOverflow>0 );
   58310   assert( sqlite3_mutex_held(pBt->mutex) );
   58311 
   58312   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
   58313   ** page that will become the new right-child of pPage. Copy the contents
   58314   ** of the node stored on pRoot into the new child page.
   58315   */
   58316   rc = sqlite3PagerWrite(pRoot->pDbPage);
   58317   if( rc==SQLITE_OK ){
   58318     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
   58319     copyNodeContent(pRoot, pChild, &rc);
   58320     if( ISAUTOVACUUM ){
   58321       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
   58322     }
   58323   }
   58324   if( rc ){
   58325     *ppChild = 0;
   58326     releasePage(pChild);
   58327     return rc;
   58328   }
   58329   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
   58330   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   58331   assert( pChild->nCell==pRoot->nCell );
   58332 
   58333   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
   58334 
   58335   /* Copy the overflow cells from pRoot to pChild */
   58336   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
   58337          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
   58338   memcpy(pChild->apOvfl, pRoot->apOvfl,
   58339          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
   58340   pChild->nOverflow = pRoot->nOverflow;
   58341 
   58342   /* Zero the contents of pRoot. Then install pChild as the right-child. */
   58343   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
   58344   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
   58345 
   58346   *ppChild = pChild;
   58347   return SQLITE_OK;
   58348 }
   58349 
   58350 /*
   58351 ** The page that pCur currently points to has just been modified in
   58352 ** some way. This function figures out if this modification means the
   58353 ** tree needs to be balanced, and if so calls the appropriate balancing
   58354 ** routine. Balancing routines are:
   58355 **
   58356 **   balance_quick()
   58357 **   balance_deeper()
   58358 **   balance_nonroot()
   58359 */
   58360 static int balance(BtCursor *pCur){
   58361   int rc = SQLITE_OK;
   58362   const int nMin = pCur->pBt->usableSize * 2 / 3;
   58363   u8 aBalanceQuickSpace[13];
   58364   u8 *pFree = 0;
   58365 
   58366   TESTONLY( int balance_quick_called = 0 );
   58367   TESTONLY( int balance_deeper_called = 0 );
   58368 
   58369   do {
   58370     int iPage = pCur->iPage;
   58371     MemPage *pPage = pCur->apPage[iPage];
   58372 
   58373     if( iPage==0 ){
   58374       if( pPage->nOverflow ){
   58375         /* The root page of the b-tree is overfull. In this case call the
   58376         ** balance_deeper() function to create a new child for the root-page
   58377         ** and copy the current contents of the root-page to it. The
   58378         ** next iteration of the do-loop will balance the child page.
   58379         */
   58380         assert( (balance_deeper_called++)==0 );
   58381         rc = balance_deeper(pPage, &pCur->apPage[1]);
   58382         if( rc==SQLITE_OK ){
   58383           pCur->iPage = 1;
   58384           pCur->aiIdx[0] = 0;
   58385           pCur->aiIdx[1] = 0;
   58386           assert( pCur->apPage[1]->nOverflow );
   58387         }
   58388       }else{
   58389         break;
   58390       }
   58391     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
   58392       break;
   58393     }else{
   58394       MemPage * const pParent = pCur->apPage[iPage-1];
   58395       int const iIdx = pCur->aiIdx[iPage-1];
   58396 
   58397       rc = sqlite3PagerWrite(pParent->pDbPage);
   58398       if( rc==SQLITE_OK ){
   58399 #ifndef SQLITE_OMIT_QUICKBALANCE
   58400         if( pPage->hasData
   58401          && pPage->nOverflow==1
   58402          && pPage->aiOvfl[0]==pPage->nCell
   58403          && pParent->pgno!=1
   58404          && pParent->nCell==iIdx
   58405         ){
   58406           /* Call balance_quick() to create a new sibling of pPage on which
   58407           ** to store the overflow cell. balance_quick() inserts a new cell
   58408           ** into pParent, which may cause pParent overflow. If this
   58409           ** happens, the next interation of the do-loop will balance pParent
   58410           ** use either balance_nonroot() or balance_deeper(). Until this
   58411           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
   58412           ** buffer.
   58413           **
   58414           ** The purpose of the following assert() is to check that only a
   58415           ** single call to balance_quick() is made for each call to this
   58416           ** function. If this were not verified, a subtle bug involving reuse
   58417           ** of the aBalanceQuickSpace[] might sneak in.
   58418           */
   58419           assert( (balance_quick_called++)==0 );
   58420           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
   58421         }else
   58422 #endif
   58423         {
   58424           /* In this case, call balance_nonroot() to redistribute cells
   58425           ** between pPage and up to 2 of its sibling pages. This involves
   58426           ** modifying the contents of pParent, which may cause pParent to
   58427           ** become overfull or underfull. The next iteration of the do-loop
   58428           ** will balance the parent page to correct this.
   58429           **
   58430           ** If the parent page becomes overfull, the overflow cell or cells
   58431           ** are stored in the pSpace buffer allocated immediately below.
   58432           ** A subsequent iteration of the do-loop will deal with this by
   58433           ** calling balance_nonroot() (balance_deeper() may be called first,
   58434           ** but it doesn't deal with overflow cells - just moves them to a
   58435           ** different page). Once this subsequent call to balance_nonroot()
   58436           ** has completed, it is safe to release the pSpace buffer used by
   58437           ** the previous call, as the overflow cell data will have been
   58438           ** copied either into the body of a database page or into the new
   58439           ** pSpace buffer passed to the latter call to balance_nonroot().
   58440           */
   58441           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
   58442           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
   58443           if( pFree ){
   58444             /* If pFree is not NULL, it points to the pSpace buffer used
   58445             ** by a previous call to balance_nonroot(). Its contents are
   58446             ** now stored either on real database pages or within the
   58447             ** new pSpace buffer, so it may be safely freed here. */
   58448             sqlite3PageFree(pFree);
   58449           }
   58450 
   58451           /* The pSpace buffer will be freed after the next call to
   58452           ** balance_nonroot(), or just before this function returns, whichever
   58453           ** comes first. */
   58454           pFree = pSpace;
   58455         }
   58456       }
   58457 
   58458       pPage->nOverflow = 0;
   58459 
   58460       /* The next iteration of the do-loop balances the parent page. */
   58461       releasePage(pPage);
   58462       pCur->iPage--;
   58463     }
   58464   }while( rc==SQLITE_OK );
   58465 
   58466   if( pFree ){
   58467     sqlite3PageFree(pFree);
   58468   }
   58469   return rc;
   58470 }
   58471 
   58472 
   58473 /*
   58474 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
   58475 ** and the data is given by (pData,nData).  The cursor is used only to
   58476 ** define what table the record should be inserted into.  The cursor
   58477 ** is left pointing at a random location.
   58478 **
   58479 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
   58480 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
   58481 **
   58482 ** If the seekResult parameter is non-zero, then a successful call to
   58483 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
   58484 ** been performed. seekResult is the search result returned (a negative
   58485 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
   58486 ** a positive value if pCur points at an etry that is larger than
   58487 ** (pKey, nKey)).
   58488 **
   58489 ** If the seekResult parameter is non-zero, then the caller guarantees that
   58490 ** cursor pCur is pointing at the existing copy of a row that is to be
   58491 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
   58492 ** point to any entry or to no entry at all and so this function has to seek
   58493 ** the cursor before the new key can be inserted.
   58494 */
   58495 SQLITE_PRIVATE int sqlite3BtreeInsert(
   58496   BtCursor *pCur,                /* Insert data into the table of this cursor */
   58497   const void *pKey, i64 nKey,    /* The key of the new record */
   58498   const void *pData, int nData,  /* The data of the new record */
   58499   int nZero,                     /* Number of extra 0 bytes to append to data */
   58500   int appendBias,                /* True if this is likely an append */
   58501   int seekResult                 /* Result of prior MovetoUnpacked() call */
   58502 ){
   58503   int rc;
   58504   int loc = seekResult;          /* -1: before desired location  +1: after */
   58505   int szNew = 0;
   58506   int idx;
   58507   MemPage *pPage;
   58508   Btree *p = pCur->pBtree;
   58509   BtShared *pBt = p->pBt;
   58510   unsigned char *oldCell;
   58511   unsigned char *newCell = 0;
   58512 
   58513   if( pCur->eState==CURSOR_FAULT ){
   58514     assert( pCur->skipNext!=SQLITE_OK );
   58515     return pCur->skipNext;
   58516   }
   58517 
   58518   assert( cursorHoldsMutex(pCur) );
   58519   assert( (pCur->curFlags & BTCF_WriteFlag)!=0 && pBt->inTransaction==TRANS_WRITE
   58520               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
   58521   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   58522 
   58523   /* Assert that the caller has been consistent. If this cursor was opened
   58524   ** expecting an index b-tree, then the caller should be inserting blob
   58525   ** keys with no associated data. If the cursor was opened expecting an
   58526   ** intkey table, the caller should be inserting integer keys with a
   58527   ** blob of associated data.  */
   58528   assert( (pKey==0)==(pCur->pKeyInfo==0) );
   58529 
   58530   /* Save the positions of any other cursors open on this table.
   58531   **
   58532   ** In some cases, the call to btreeMoveto() below is a no-op. For
   58533   ** example, when inserting data into a table with auto-generated integer
   58534   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
   58535   ** integer key to use. It then calls this function to actually insert the
   58536   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
   58537   ** that the cursor is already where it needs to be and returns without
   58538   ** doing any work. To avoid thwarting these optimizations, it is important
   58539   ** not to clear the cursor here.
   58540   */
   58541   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   58542   if( rc ) return rc;
   58543 
   58544   if( pCur->pKeyInfo==0 ){
   58545     /* If this is an insert into a table b-tree, invalidate any incrblob
   58546     ** cursors open on the row being replaced */
   58547     invalidateIncrblobCursors(p, nKey, 0);
   58548 
   58549     /* If the cursor is currently on the last row and we are appending a
   58550     ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
   58551     ** call */
   58552     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0 && pCur->info.nKey==nKey-1 ){
   58553       loc = -1;
   58554     }
   58555   }
   58556 
   58557   if( !loc ){
   58558     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
   58559     if( rc ) return rc;
   58560   }
   58561   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
   58562 
   58563   pPage = pCur->apPage[pCur->iPage];
   58564   assert( pPage->intKey || nKey>=0 );
   58565   assert( pPage->leaf || !pPage->intKey );
   58566 
   58567   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
   58568           pCur->pgnoRoot, nKey, nData, pPage->pgno,
   58569           loc==0 ? "overwrite" : "new entry"));
   58570   assert( pPage->isInit );
   58571   allocateTempSpace(pBt);
   58572   newCell = pBt->pTmpSpace;
   58573   if( newCell==0 ) return SQLITE_NOMEM;
   58574   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
   58575   if( rc ) goto end_insert;
   58576   assert( szNew==cellSizePtr(pPage, newCell) );
   58577   assert( szNew <= MX_CELL_SIZE(pBt) );
   58578   idx = pCur->aiIdx[pCur->iPage];
   58579   if( loc==0 ){
   58580     u16 szOld;
   58581     assert( idx<pPage->nCell );
   58582     rc = sqlite3PagerWrite(pPage->pDbPage);
   58583     if( rc ){
   58584       goto end_insert;
   58585     }
   58586     oldCell = findCell(pPage, idx);
   58587     if( !pPage->leaf ){
   58588       memcpy(newCell, oldCell, 4);
   58589     }
   58590     szOld = cellSizePtr(pPage, oldCell);
   58591     rc = clearCell(pPage, oldCell);
   58592     dropCell(pPage, idx, szOld, &rc);
   58593     if( rc ) goto end_insert;
   58594   }else if( loc<0 && pPage->nCell>0 ){
   58595     assert( pPage->leaf );
   58596     idx = ++pCur->aiIdx[pCur->iPage];
   58597   }else{
   58598     assert( pPage->leaf );
   58599   }
   58600   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
   58601   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
   58602 
   58603   /* If no error has occurred and pPage has an overflow cell, call balance()
   58604   ** to redistribute the cells within the tree. Since balance() may move
   58605   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
   58606   ** variables.
   58607   **
   58608   ** Previous versions of SQLite called moveToRoot() to move the cursor
   58609   ** back to the root page as balance() used to invalidate the contents
   58610   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
   58611   ** set the cursor state to "invalid". This makes common insert operations
   58612   ** slightly faster.
   58613   **
   58614   ** There is a subtle but important optimization here too. When inserting
   58615   ** multiple records into an intkey b-tree using a single cursor (as can
   58616   ** happen while processing an "INSERT INTO ... SELECT" statement), it
   58617   ** is advantageous to leave the cursor pointing to the last entry in
   58618   ** the b-tree if possible. If the cursor is left pointing to the last
   58619   ** entry in the table, and the next row inserted has an integer key
   58620   ** larger than the largest existing key, it is possible to insert the
   58621   ** row without seeking the cursor. This can be a big performance boost.
   58622   */
   58623   pCur->info.nSize = 0;
   58624   if( rc==SQLITE_OK && pPage->nOverflow ){
   58625     pCur->curFlags &= ~(BTCF_ValidNKey);
   58626     rc = balance(pCur);
   58627 
   58628     /* Must make sure nOverflow is reset to zero even if the balance()
   58629     ** fails. Internal data structure corruption will result otherwise.
   58630     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
   58631     ** from trying to save the current position of the cursor.  */
   58632     pCur->apPage[pCur->iPage]->nOverflow = 0;
   58633     pCur->eState = CURSOR_INVALID;
   58634   }
   58635   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
   58636 
   58637 end_insert:
   58638   return rc;
   58639 }
   58640 
   58641 /*
   58642 ** Delete the entry that the cursor is pointing to.  The cursor
   58643 ** is left pointing at a arbitrary location.
   58644 */
   58645 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
   58646   Btree *p = pCur->pBtree;
   58647   BtShared *pBt = p->pBt;
   58648   int rc;                              /* Return code */
   58649   MemPage *pPage;                      /* Page to delete cell from */
   58650   unsigned char *pCell;                /* Pointer to cell to delete */
   58651   int iCellIdx;                        /* Index of cell to delete */
   58652   int iCellDepth;                      /* Depth of node containing pCell */
   58653 
   58654   assert( cursorHoldsMutex(pCur) );
   58655   assert( pBt->inTransaction==TRANS_WRITE );
   58656   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   58657   assert( pCur->curFlags & BTCF_WriteFlag );
   58658   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   58659   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
   58660 
   58661   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
   58662    || NEVER(pCur->eState!=CURSOR_VALID)
   58663   ){
   58664     return SQLITE_ERROR;  /* Something has gone awry. */
   58665   }
   58666 
   58667   iCellDepth = pCur->iPage;
   58668   iCellIdx = pCur->aiIdx[iCellDepth];
   58669   pPage = pCur->apPage[iCellDepth];
   58670   pCell = findCell(pPage, iCellIdx);
   58671 
   58672   /* If the page containing the entry to delete is not a leaf page, move
   58673   ** the cursor to the largest entry in the tree that is smaller than
   58674   ** the entry being deleted. This cell will replace the cell being deleted
   58675   ** from the internal node. The 'previous' entry is used for this instead
   58676   ** of the 'next' entry, as the previous entry is always a part of the
   58677   ** sub-tree headed by the child page of the cell being deleted. This makes
   58678   ** balancing the tree following the delete operation easier.  */
   58679   if( !pPage->leaf ){
   58680     int notUsed = 0;
   58681     rc = sqlite3BtreePrevious(pCur, &notUsed);
   58682     if( rc ) return rc;
   58683   }
   58684 
   58685   /* Save the positions of any other cursors open on this table before
   58686   ** making any modifications. Make the page containing the entry to be
   58687   ** deleted writable. Then free any overflow pages associated with the
   58688   ** entry and finally remove the cell itself from within the page.
   58689   */
   58690   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   58691   if( rc ) return rc;
   58692 
   58693   /* If this is a delete operation to remove a row from a table b-tree,
   58694   ** invalidate any incrblob cursors open on the row being deleted.  */
   58695   if( pCur->pKeyInfo==0 ){
   58696     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
   58697   }
   58698 
   58699   rc = sqlite3PagerWrite(pPage->pDbPage);
   58700   if( rc ) return rc;
   58701   rc = clearCell(pPage, pCell);
   58702   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
   58703   if( rc ) return rc;
   58704 
   58705   /* If the cell deleted was not located on a leaf page, then the cursor
   58706   ** is currently pointing to the largest entry in the sub-tree headed
   58707   ** by the child-page of the cell that was just deleted from an internal
   58708   ** node. The cell from the leaf node needs to be moved to the internal
   58709   ** node to replace the deleted cell.  */
   58710   if( !pPage->leaf ){
   58711     MemPage *pLeaf = pCur->apPage[pCur->iPage];
   58712     int nCell;
   58713     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
   58714     unsigned char *pTmp;
   58715 
   58716     pCell = findCell(pLeaf, pLeaf->nCell-1);
   58717     nCell = cellSizePtr(pLeaf, pCell);
   58718     assert( MX_CELL_SIZE(pBt) >= nCell );
   58719 
   58720     allocateTempSpace(pBt);
   58721     pTmp = pBt->pTmpSpace;
   58722 
   58723     rc = sqlite3PagerWrite(pLeaf->pDbPage);
   58724     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
   58725     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
   58726     if( rc ) return rc;
   58727   }
   58728 
   58729   /* Balance the tree. If the entry deleted was located on a leaf page,
   58730   ** then the cursor still points to that page. In this case the first
   58731   ** call to balance() repairs the tree, and the if(...) condition is
   58732   ** never true.
   58733   **
   58734   ** Otherwise, if the entry deleted was on an internal node page, then
   58735   ** pCur is pointing to the leaf page from which a cell was removed to
   58736   ** replace the cell deleted from the internal node. This is slightly
   58737   ** tricky as the leaf node may be underfull, and the internal node may
   58738   ** be either under or overfull. In this case run the balancing algorithm
   58739   ** on the leaf node first. If the balance proceeds far enough up the
   58740   ** tree that we can be sure that any problem in the internal node has
   58741   ** been corrected, so be it. Otherwise, after balancing the leaf node,
   58742   ** walk the cursor up the tree to the internal node and balance it as
   58743   ** well.  */
   58744   rc = balance(pCur);
   58745   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
   58746     while( pCur->iPage>iCellDepth ){
   58747       releasePage(pCur->apPage[pCur->iPage--]);
   58748     }
   58749     rc = balance(pCur);
   58750   }
   58751 
   58752   if( rc==SQLITE_OK ){
   58753     moveToRoot(pCur);
   58754   }
   58755   return rc;
   58756 }
   58757 
   58758 /*
   58759 ** Create a new BTree table.  Write into *piTable the page
   58760 ** number for the root page of the new table.
   58761 **
   58762 ** The type of type is determined by the flags parameter.  Only the
   58763 ** following values of flags are currently in use.  Other values for
   58764 ** flags might not work:
   58765 **
   58766 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
   58767 **     BTREE_ZERODATA                  Used for SQL indices
   58768 */
   58769 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
   58770   BtShared *pBt = p->pBt;
   58771   MemPage *pRoot;
   58772   Pgno pgnoRoot;
   58773   int rc;
   58774   int ptfFlags;          /* Page-type flage for the root page of new table */
   58775 
   58776   assert( sqlite3BtreeHoldsMutex(p) );
   58777   assert( pBt->inTransaction==TRANS_WRITE );
   58778   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   58779 
   58780 #ifdef SQLITE_OMIT_AUTOVACUUM
   58781   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   58782   if( rc ){
   58783     return rc;
   58784   }
   58785 #else
   58786   if( pBt->autoVacuum ){
   58787     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
   58788     MemPage *pPageMove; /* The page to move to. */
   58789 
   58790     /* Creating a new table may probably require moving an existing database
   58791     ** to make room for the new tables root page. In case this page turns
   58792     ** out to be an overflow page, delete all overflow page-map caches
   58793     ** held by open cursors.
   58794     */
   58795     invalidateAllOverflowCache(pBt);
   58796 
   58797     /* Read the value of meta[3] from the database to determine where the
   58798     ** root page of the new table should go. meta[3] is the largest root-page
   58799     ** created so far, so the new root-page is (meta[3]+1).
   58800     */
   58801     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
   58802     pgnoRoot++;
   58803 
   58804     /* The new root-page may not be allocated on a pointer-map page, or the
   58805     ** PENDING_BYTE page.
   58806     */
   58807     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
   58808         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
   58809       pgnoRoot++;
   58810     }
   58811     assert( pgnoRoot>=3 );
   58812 
   58813     /* Allocate a page. The page that currently resides at pgnoRoot will
   58814     ** be moved to the allocated page (unless the allocated page happens
   58815     ** to reside at pgnoRoot).
   58816     */
   58817     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
   58818     if( rc!=SQLITE_OK ){
   58819       return rc;
   58820     }
   58821 
   58822     if( pgnoMove!=pgnoRoot ){
   58823       /* pgnoRoot is the page that will be used for the root-page of
   58824       ** the new table (assuming an error did not occur). But we were
   58825       ** allocated pgnoMove. If required (i.e. if it was not allocated
   58826       ** by extending the file), the current page at position pgnoMove
   58827       ** is already journaled.
   58828       */
   58829       u8 eType = 0;
   58830       Pgno iPtrPage = 0;
   58831 
   58832       /* Save the positions of any open cursors. This is required in
   58833       ** case they are holding a reference to an xFetch reference
   58834       ** corresponding to page pgnoRoot.  */
   58835       rc = saveAllCursors(pBt, 0, 0);
   58836       releasePage(pPageMove);
   58837       if( rc!=SQLITE_OK ){
   58838         return rc;
   58839       }
   58840 
   58841       /* Move the page currently at pgnoRoot to pgnoMove. */
   58842       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   58843       if( rc!=SQLITE_OK ){
   58844         return rc;
   58845       }
   58846       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
   58847       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
   58848         rc = SQLITE_CORRUPT_BKPT;
   58849       }
   58850       if( rc!=SQLITE_OK ){
   58851         releasePage(pRoot);
   58852         return rc;
   58853       }
   58854       assert( eType!=PTRMAP_ROOTPAGE );
   58855       assert( eType!=PTRMAP_FREEPAGE );
   58856       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
   58857       releasePage(pRoot);
   58858 
   58859       /* Obtain the page at pgnoRoot */
   58860       if( rc!=SQLITE_OK ){
   58861         return rc;
   58862       }
   58863       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   58864       if( rc!=SQLITE_OK ){
   58865         return rc;
   58866       }
   58867       rc = sqlite3PagerWrite(pRoot->pDbPage);
   58868       if( rc!=SQLITE_OK ){
   58869         releasePage(pRoot);
   58870         return rc;
   58871       }
   58872     }else{
   58873       pRoot = pPageMove;
   58874     }
   58875 
   58876     /* Update the pointer-map and meta-data with the new root-page number. */
   58877     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
   58878     if( rc ){
   58879       releasePage(pRoot);
   58880       return rc;
   58881     }
   58882 
   58883     /* When the new root page was allocated, page 1 was made writable in
   58884     ** order either to increase the database filesize, or to decrement the
   58885     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
   58886     */
   58887     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
   58888     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
   58889     if( NEVER(rc) ){
   58890       releasePage(pRoot);
   58891       return rc;
   58892     }
   58893 
   58894   }else{
   58895     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   58896     if( rc ) return rc;
   58897   }
   58898 #endif
   58899   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   58900   if( createTabFlags & BTREE_INTKEY ){
   58901     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
   58902   }else{
   58903     ptfFlags = PTF_ZERODATA | PTF_LEAF;
   58904   }
   58905   zeroPage(pRoot, ptfFlags);
   58906   sqlite3PagerUnref(pRoot->pDbPage);
   58907   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
   58908   *piTable = (int)pgnoRoot;
   58909   return SQLITE_OK;
   58910 }
   58911 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
   58912   int rc;
   58913   sqlite3BtreeEnter(p);
   58914   rc = btreeCreateTable(p, piTable, flags);
   58915   sqlite3BtreeLeave(p);
   58916   return rc;
   58917 }
   58918 
   58919 /*
   58920 ** Erase the given database page and all its children.  Return
   58921 ** the page to the freelist.
   58922 */
   58923 static int clearDatabasePage(
   58924   BtShared *pBt,           /* The BTree that contains the table */
   58925   Pgno pgno,               /* Page number to clear */
   58926   int freePageFlag,        /* Deallocate page if true */
   58927   int *pnChange            /* Add number of Cells freed to this counter */
   58928 ){
   58929   MemPage *pPage;
   58930   int rc;
   58931   unsigned char *pCell;
   58932   int i;
   58933   int hdr;
   58934 
   58935   assert( sqlite3_mutex_held(pBt->mutex) );
   58936   if( pgno>btreePagecount(pBt) ){
   58937     return SQLITE_CORRUPT_BKPT;
   58938   }
   58939 
   58940   rc = getAndInitPage(pBt, pgno, &pPage, 0);
   58941   if( rc ) return rc;
   58942   hdr = pPage->hdrOffset;
   58943   for(i=0; i<pPage->nCell; i++){
   58944     pCell = findCell(pPage, i);
   58945     if( !pPage->leaf ){
   58946       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
   58947       if( rc ) goto cleardatabasepage_out;
   58948     }
   58949     rc = clearCell(pPage, pCell);
   58950     if( rc ) goto cleardatabasepage_out;
   58951   }
   58952   if( !pPage->leaf ){
   58953     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
   58954     if( rc ) goto cleardatabasepage_out;
   58955   }else if( pnChange ){
   58956     assert( pPage->intKey );
   58957     *pnChange += pPage->nCell;
   58958   }
   58959   if( freePageFlag ){
   58960     freePage(pPage, &rc);
   58961   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
   58962     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
   58963   }
   58964 
   58965 cleardatabasepage_out:
   58966   releasePage(pPage);
   58967   return rc;
   58968 }
   58969 
   58970 /*
   58971 ** Delete all information from a single table in the database.  iTable is
   58972 ** the page number of the root of the table.  After this routine returns,
   58973 ** the root page is empty, but still exists.
   58974 **
   58975 ** This routine will fail with SQLITE_LOCKED if there are any open
   58976 ** read cursors on the table.  Open write cursors are moved to the
   58977 ** root of the table.
   58978 **
   58979 ** If pnChange is not NULL, then table iTable must be an intkey table. The
   58980 ** integer value pointed to by pnChange is incremented by the number of
   58981 ** entries in the table.
   58982 */
   58983 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
   58984   int rc;
   58985   BtShared *pBt = p->pBt;
   58986   sqlite3BtreeEnter(p);
   58987   assert( p->inTrans==TRANS_WRITE );
   58988 
   58989   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
   58990 
   58991   if( SQLITE_OK==rc ){
   58992     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
   58993     ** is the root of a table b-tree - if it is not, the following call is
   58994     ** a no-op).  */
   58995     invalidateIncrblobCursors(p, 0, 1);
   58996     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
   58997   }
   58998   sqlite3BtreeLeave(p);
   58999   return rc;
   59000 }
   59001 
   59002 /*
   59003 ** Delete all information from the single table that pCur is open on.
   59004 **
   59005 ** This routine only work for pCur on an ephemeral table.
   59006 */
   59007 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
   59008   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
   59009 }
   59010 
   59011 /*
   59012 ** Erase all information in a table and add the root of the table to
   59013 ** the freelist.  Except, the root of the principle table (the one on
   59014 ** page 1) is never added to the freelist.
   59015 **
   59016 ** This routine will fail with SQLITE_LOCKED if there are any open
   59017 ** cursors on the table.
   59018 **
   59019 ** If AUTOVACUUM is enabled and the page at iTable is not the last
   59020 ** root page in the database file, then the last root page
   59021 ** in the database file is moved into the slot formerly occupied by
   59022 ** iTable and that last slot formerly occupied by the last root page
   59023 ** is added to the freelist instead of iTable.  In this say, all
   59024 ** root pages are kept at the beginning of the database file, which
   59025 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
   59026 ** page number that used to be the last root page in the file before
   59027 ** the move.  If no page gets moved, *piMoved is set to 0.
   59028 ** The last root page is recorded in meta[3] and the value of
   59029 ** meta[3] is updated by this procedure.
   59030 */
   59031 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
   59032   int rc;
   59033   MemPage *pPage = 0;
   59034   BtShared *pBt = p->pBt;
   59035 
   59036   assert( sqlite3BtreeHoldsMutex(p) );
   59037   assert( p->inTrans==TRANS_WRITE );
   59038 
   59039   /* It is illegal to drop a table if any cursors are open on the
   59040   ** database. This is because in auto-vacuum mode the backend may
   59041   ** need to move another root-page to fill a gap left by the deleted
   59042   ** root page. If an open cursor was using this page a problem would
   59043   ** occur.
   59044   **
   59045   ** This error is caught long before control reaches this point.
   59046   */
   59047   if( NEVER(pBt->pCursor) ){
   59048     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
   59049     return SQLITE_LOCKED_SHAREDCACHE;
   59050   }
   59051 
   59052   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
   59053   if( rc ) return rc;
   59054   rc = sqlite3BtreeClearTable(p, iTable, 0);
   59055   if( rc ){
   59056     releasePage(pPage);
   59057     return rc;
   59058   }
   59059 
   59060   *piMoved = 0;
   59061 
   59062   if( iTable>1 ){
   59063 #ifdef SQLITE_OMIT_AUTOVACUUM
   59064     freePage(pPage, &rc);
   59065     releasePage(pPage);
   59066 #else
   59067     if( pBt->autoVacuum ){
   59068       Pgno maxRootPgno;
   59069       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
   59070 
   59071       if( iTable==maxRootPgno ){
   59072         /* If the table being dropped is the table with the largest root-page
   59073         ** number in the database, put the root page on the free list.
   59074         */
   59075         freePage(pPage, &rc);
   59076         releasePage(pPage);
   59077         if( rc!=SQLITE_OK ){
   59078           return rc;
   59079         }
   59080       }else{
   59081         /* The table being dropped does not have the largest root-page
   59082         ** number in the database. So move the page that does into the
   59083         ** gap left by the deleted root-page.
   59084         */
   59085         MemPage *pMove;
   59086         releasePage(pPage);
   59087         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   59088         if( rc!=SQLITE_OK ){
   59089           return rc;
   59090         }
   59091         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
   59092         releasePage(pMove);
   59093         if( rc!=SQLITE_OK ){
   59094           return rc;
   59095         }
   59096         pMove = 0;
   59097         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   59098         freePage(pMove, &rc);
   59099         releasePage(pMove);
   59100         if( rc!=SQLITE_OK ){
   59101           return rc;
   59102         }
   59103         *piMoved = maxRootPgno;
   59104       }
   59105 
   59106       /* Set the new 'max-root-page' value in the database header. This
   59107       ** is the old value less one, less one more if that happens to
   59108       ** be a root-page number, less one again if that is the
   59109       ** PENDING_BYTE_PAGE.
   59110       */
   59111       maxRootPgno--;
   59112       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
   59113              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
   59114         maxRootPgno--;
   59115       }
   59116       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
   59117 
   59118       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
   59119     }else{
   59120       freePage(pPage, &rc);
   59121       releasePage(pPage);
   59122     }
   59123 #endif
   59124   }else{
   59125     /* If sqlite3BtreeDropTable was called on page 1.
   59126     ** This really never should happen except in a corrupt
   59127     ** database.
   59128     */
   59129     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
   59130     releasePage(pPage);
   59131   }
   59132   return rc;
   59133 }
   59134 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
   59135   int rc;
   59136   sqlite3BtreeEnter(p);
   59137   rc = btreeDropTable(p, iTable, piMoved);
   59138   sqlite3BtreeLeave(p);
   59139   return rc;
   59140 }
   59141 
   59142 
   59143 /*
   59144 ** This function may only be called if the b-tree connection already
   59145 ** has a read or write transaction open on the database.
   59146 **
   59147 ** Read the meta-information out of a database file.  Meta[0]
   59148 ** is the number of free pages currently in the database.  Meta[1]
   59149 ** through meta[15] are available for use by higher layers.  Meta[0]
   59150 ** is read-only, the others are read/write.
   59151 **
   59152 ** The schema layer numbers meta values differently.  At the schema
   59153 ** layer (and the SetCookie and ReadCookie opcodes) the number of
   59154 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
   59155 */
   59156 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
   59157   BtShared *pBt = p->pBt;
   59158 
   59159   sqlite3BtreeEnter(p);
   59160   assert( p->inTrans>TRANS_NONE );
   59161   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
   59162   assert( pBt->pPage1 );
   59163   assert( idx>=0 && idx<=15 );
   59164 
   59165   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
   59166 
   59167   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
   59168   ** database, mark the database as read-only.  */
   59169 #ifdef SQLITE_OMIT_AUTOVACUUM
   59170   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
   59171     pBt->btsFlags |= BTS_READ_ONLY;
   59172   }
   59173 #endif
   59174 
   59175   sqlite3BtreeLeave(p);
   59176 }
   59177 
   59178 /*
   59179 ** Write meta-information back into the database.  Meta[0] is
   59180 ** read-only and may not be written.
   59181 */
   59182 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
   59183   BtShared *pBt = p->pBt;
   59184   unsigned char *pP1;
   59185   int rc;
   59186   assert( idx>=1 && idx<=15 );
   59187   sqlite3BtreeEnter(p);
   59188   assert( p->inTrans==TRANS_WRITE );
   59189   assert( pBt->pPage1!=0 );
   59190   pP1 = pBt->pPage1->aData;
   59191   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   59192   if( rc==SQLITE_OK ){
   59193     put4byte(&pP1[36 + idx*4], iMeta);
   59194 #ifndef SQLITE_OMIT_AUTOVACUUM
   59195     if( idx==BTREE_INCR_VACUUM ){
   59196       assert( pBt->autoVacuum || iMeta==0 );
   59197       assert( iMeta==0 || iMeta==1 );
   59198       pBt->incrVacuum = (u8)iMeta;
   59199     }
   59200 #endif
   59201   }
   59202   sqlite3BtreeLeave(p);
   59203   return rc;
   59204 }
   59205 
   59206 #ifndef SQLITE_OMIT_BTREECOUNT
   59207 /*
   59208 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
   59209 ** number of entries in the b-tree and write the result to *pnEntry.
   59210 **
   59211 ** SQLITE_OK is returned if the operation is successfully executed.
   59212 ** Otherwise, if an error is encountered (i.e. an IO error or database
   59213 ** corruption) an SQLite error code is returned.
   59214 */
   59215 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   59216   i64 nEntry = 0;                      /* Value to return in *pnEntry */
   59217   int rc;                              /* Return code */
   59218 
   59219   if( pCur->pgnoRoot==0 ){
   59220     *pnEntry = 0;
   59221     return SQLITE_OK;
   59222   }
   59223   rc = moveToRoot(pCur);
   59224 
   59225   /* Unless an error occurs, the following loop runs one iteration for each
   59226   ** page in the B-Tree structure (not including overflow pages).
   59227   */
   59228   while( rc==SQLITE_OK ){
   59229     int iIdx;                          /* Index of child node in parent */
   59230     MemPage *pPage;                    /* Current page of the b-tree */
   59231 
   59232     /* If this is a leaf page or the tree is not an int-key tree, then
   59233     ** this page contains countable entries. Increment the entry counter
   59234     ** accordingly.
   59235     */
   59236     pPage = pCur->apPage[pCur->iPage];
   59237     if( pPage->leaf || !pPage->intKey ){
   59238       nEntry += pPage->nCell;
   59239     }
   59240 
   59241     /* pPage is a leaf node. This loop navigates the cursor so that it
   59242     ** points to the first interior cell that it points to the parent of
   59243     ** the next page in the tree that has not yet been visited. The
   59244     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
   59245     ** of the page, or to the number of cells in the page if the next page
   59246     ** to visit is the right-child of its parent.
   59247     **
   59248     ** If all pages in the tree have been visited, return SQLITE_OK to the
   59249     ** caller.
   59250     */
   59251     if( pPage->leaf ){
   59252       do {
   59253         if( pCur->iPage==0 ){
   59254           /* All pages of the b-tree have been visited. Return successfully. */
   59255           *pnEntry = nEntry;
   59256           return SQLITE_OK;
   59257         }
   59258         moveToParent(pCur);
   59259       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
   59260 
   59261       pCur->aiIdx[pCur->iPage]++;
   59262       pPage = pCur->apPage[pCur->iPage];
   59263     }
   59264 
   59265     /* Descend to the child node of the cell that the cursor currently
   59266     ** points at. This is the right-child if (iIdx==pPage->nCell).
   59267     */
   59268     iIdx = pCur->aiIdx[pCur->iPage];
   59269     if( iIdx==pPage->nCell ){
   59270       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   59271     }else{
   59272       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
   59273     }
   59274   }
   59275 
   59276   /* An error has occurred. Return an error code. */
   59277   return rc;
   59278 }
   59279 #endif
   59280 
   59281 /*
   59282 ** Return the pager associated with a BTree.  This routine is used for
   59283 ** testing and debugging only.
   59284 */
   59285 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
   59286   return p->pBt->pPager;
   59287 }
   59288 
   59289 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   59290 /*
   59291 ** Append a message to the error message string.
   59292 */
   59293 static void checkAppendMsg(
   59294   IntegrityCk *pCheck,
   59295   char *zMsg1,
   59296   const char *zFormat,
   59297   ...
   59298 ){
   59299   va_list ap;
   59300   if( !pCheck->mxErr ) return;
   59301   pCheck->mxErr--;
   59302   pCheck->nErr++;
   59303   va_start(ap, zFormat);
   59304   if( pCheck->errMsg.nChar ){
   59305     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
   59306   }
   59307   if( zMsg1 ){
   59308     sqlite3StrAccumAppendAll(&pCheck->errMsg, zMsg1);
   59309   }
   59310   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
   59311   va_end(ap);
   59312   if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
   59313     pCheck->mallocFailed = 1;
   59314   }
   59315 }
   59316 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   59317 
   59318 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   59319 
   59320 /*
   59321 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
   59322 ** corresponds to page iPg is already set.
   59323 */
   59324 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
   59325   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
   59326   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
   59327 }
   59328 
   59329 /*
   59330 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
   59331 */
   59332 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
   59333   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
   59334   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
   59335 }
   59336 
   59337 
   59338 /*
   59339 ** Add 1 to the reference count for page iPage.  If this is the second
   59340 ** reference to the page, add an error message to pCheck->zErrMsg.
   59341 ** Return 1 if there are 2 ore more references to the page and 0 if
   59342 ** if this is the first reference to the page.
   59343 **
   59344 ** Also check that the page number is in bounds.
   59345 */
   59346 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
   59347   if( iPage==0 ) return 1;
   59348   if( iPage>pCheck->nPage ){
   59349     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
   59350     return 1;
   59351   }
   59352   if( getPageReferenced(pCheck, iPage) ){
   59353     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
   59354     return 1;
   59355   }
   59356   setPageReferenced(pCheck, iPage);
   59357   return 0;
   59358 }
   59359 
   59360 #ifndef SQLITE_OMIT_AUTOVACUUM
   59361 /*
   59362 ** Check that the entry in the pointer-map for page iChild maps to
   59363 ** page iParent, pointer type ptrType. If not, append an error message
   59364 ** to pCheck.
   59365 */
   59366 static void checkPtrmap(
   59367   IntegrityCk *pCheck,   /* Integrity check context */
   59368   Pgno iChild,           /* Child page number */
   59369   u8 eType,              /* Expected pointer map type */
   59370   Pgno iParent,          /* Expected pointer map parent page number */
   59371   char *zContext         /* Context description (used for error msg) */
   59372 ){
   59373   int rc;
   59374   u8 ePtrmapType;
   59375   Pgno iPtrmapParent;
   59376 
   59377   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
   59378   if( rc!=SQLITE_OK ){
   59379     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
   59380     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
   59381     return;
   59382   }
   59383 
   59384   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
   59385     checkAppendMsg(pCheck, zContext,
   59386       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
   59387       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
   59388   }
   59389 }
   59390 #endif
   59391 
   59392 /*
   59393 ** Check the integrity of the freelist or of an overflow page list.
   59394 ** Verify that the number of pages on the list is N.
   59395 */
   59396 static void checkList(
   59397   IntegrityCk *pCheck,  /* Integrity checking context */
   59398   int isFreeList,       /* True for a freelist.  False for overflow page list */
   59399   int iPage,            /* Page number for first page in the list */
   59400   int N,                /* Expected number of pages in the list */
   59401   char *zContext        /* Context for error messages */
   59402 ){
   59403   int i;
   59404   int expected = N;
   59405   int iFirst = iPage;
   59406   while( N-- > 0 && pCheck->mxErr ){
   59407     DbPage *pOvflPage;
   59408     unsigned char *pOvflData;
   59409     if( iPage<1 ){
   59410       checkAppendMsg(pCheck, zContext,
   59411          "%d of %d pages missing from overflow list starting at %d",
   59412           N+1, expected, iFirst);
   59413       break;
   59414     }
   59415     if( checkRef(pCheck, iPage, zContext) ) break;
   59416     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
   59417       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
   59418       break;
   59419     }
   59420     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
   59421     if( isFreeList ){
   59422       int n = get4byte(&pOvflData[4]);
   59423 #ifndef SQLITE_OMIT_AUTOVACUUM
   59424       if( pCheck->pBt->autoVacuum ){
   59425         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
   59426       }
   59427 #endif
   59428       if( n>(int)pCheck->pBt->usableSize/4-2 ){
   59429         checkAppendMsg(pCheck, zContext,
   59430            "freelist leaf count too big on page %d", iPage);
   59431         N--;
   59432       }else{
   59433         for(i=0; i<n; i++){
   59434           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
   59435 #ifndef SQLITE_OMIT_AUTOVACUUM
   59436           if( pCheck->pBt->autoVacuum ){
   59437             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
   59438           }
   59439 #endif
   59440           checkRef(pCheck, iFreePage, zContext);
   59441         }
   59442         N -= n;
   59443       }
   59444     }
   59445 #ifndef SQLITE_OMIT_AUTOVACUUM
   59446     else{
   59447       /* If this database supports auto-vacuum and iPage is not the last
   59448       ** page in this overflow list, check that the pointer-map entry for
   59449       ** the following page matches iPage.
   59450       */
   59451       if( pCheck->pBt->autoVacuum && N>0 ){
   59452         i = get4byte(pOvflData);
   59453         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
   59454       }
   59455     }
   59456 #endif
   59457     iPage = get4byte(pOvflData);
   59458     sqlite3PagerUnref(pOvflPage);
   59459   }
   59460 }
   59461 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   59462 
   59463 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   59464 /*
   59465 ** Do various sanity checks on a single page of a tree.  Return
   59466 ** the tree depth.  Root pages return 0.  Parents of root pages
   59467 ** return 1, and so forth.
   59468 **
   59469 ** These checks are done:
   59470 **
   59471 **      1.  Make sure that cells and freeblocks do not overlap
   59472 **          but combine to completely cover the page.
   59473 **  NO  2.  Make sure cell keys are in order.
   59474 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
   59475 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
   59476 **      5.  Check the integrity of overflow pages.
   59477 **      6.  Recursively call checkTreePage on all children.
   59478 **      7.  Verify that the depth of all children is the same.
   59479 **      8.  Make sure this page is at least 33% full or else it is
   59480 **          the root of the tree.
   59481 */
   59482 static int checkTreePage(
   59483   IntegrityCk *pCheck,  /* Context for the sanity check */
   59484   int iPage,            /* Page number of the page to check */
   59485   char *zParentContext, /* Parent context */
   59486   i64 *pnParentMinKey,
   59487   i64 *pnParentMaxKey
   59488 ){
   59489   MemPage *pPage;
   59490   int i, rc, depth, d2, pgno, cnt;
   59491   int hdr, cellStart;
   59492   int nCell;
   59493   u8 *data;
   59494   BtShared *pBt;
   59495   int usableSize;
   59496   char zContext[100];
   59497   char *hit = 0;
   59498   i64 nMinKey = 0;
   59499   i64 nMaxKey = 0;
   59500 
   59501   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
   59502 
   59503   /* Check that the page exists
   59504   */
   59505   pBt = pCheck->pBt;
   59506   usableSize = pBt->usableSize;
   59507   if( iPage==0 ) return 0;
   59508   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
   59509   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
   59510     checkAppendMsg(pCheck, zContext,
   59511        "unable to get the page. error code=%d", rc);
   59512     return 0;
   59513   }
   59514 
   59515   /* Clear MemPage.isInit to make sure the corruption detection code in
   59516   ** btreeInitPage() is executed.  */
   59517   pPage->isInit = 0;
   59518   if( (rc = btreeInitPage(pPage))!=0 ){
   59519     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
   59520     checkAppendMsg(pCheck, zContext,
   59521                    "btreeInitPage() returns error code %d", rc);
   59522     releasePage(pPage);
   59523     return 0;
   59524   }
   59525 
   59526   /* Check out all the cells.
   59527   */
   59528   depth = 0;
   59529   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
   59530     u8 *pCell;
   59531     u32 sz;
   59532     CellInfo info;
   59533 
   59534     /* Check payload overflow pages
   59535     */
   59536     sqlite3_snprintf(sizeof(zContext), zContext,
   59537              "On tree page %d cell %d: ", iPage, i);
   59538     pCell = findCell(pPage,i);
   59539     btreeParseCellPtr(pPage, pCell, &info);
   59540     sz = info.nData;
   59541     if( !pPage->intKey ) sz += (int)info.nKey;
   59542     /* For intKey pages, check that the keys are in order.
   59543     */
   59544     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
   59545     else{
   59546       if( info.nKey <= nMaxKey ){
   59547         checkAppendMsg(pCheck, zContext,
   59548             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
   59549       }
   59550       nMaxKey = info.nKey;
   59551     }
   59552     assert( sz==info.nPayload );
   59553     if( (sz>info.nLocal)
   59554      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
   59555     ){
   59556       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
   59557       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
   59558 #ifndef SQLITE_OMIT_AUTOVACUUM
   59559       if( pBt->autoVacuum ){
   59560         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
   59561       }
   59562 #endif
   59563       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
   59564     }
   59565 
   59566     /* Check sanity of left child page.
   59567     */
   59568     if( !pPage->leaf ){
   59569       pgno = get4byte(pCell);
   59570 #ifndef SQLITE_OMIT_AUTOVACUUM
   59571       if( pBt->autoVacuum ){
   59572         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   59573       }
   59574 #endif
   59575       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
   59576       if( i>0 && d2!=depth ){
   59577         checkAppendMsg(pCheck, zContext, "Child page depth differs");
   59578       }
   59579       depth = d2;
   59580     }
   59581   }
   59582 
   59583   if( !pPage->leaf ){
   59584     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   59585     sqlite3_snprintf(sizeof(zContext), zContext,
   59586                      "On page %d at right child: ", iPage);
   59587 #ifndef SQLITE_OMIT_AUTOVACUUM
   59588     if( pBt->autoVacuum ){
   59589       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   59590     }
   59591 #endif
   59592     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
   59593   }
   59594 
   59595   /* For intKey leaf pages, check that the min/max keys are in order
   59596   ** with any left/parent/right pages.
   59597   */
   59598   if( pPage->leaf && pPage->intKey ){
   59599     /* if we are a left child page */
   59600     if( pnParentMinKey ){
   59601       /* if we are the left most child page */
   59602       if( !pnParentMaxKey ){
   59603         if( nMaxKey > *pnParentMinKey ){
   59604           checkAppendMsg(pCheck, zContext,
   59605               "Rowid %lld out of order (max larger than parent min of %lld)",
   59606               nMaxKey, *pnParentMinKey);
   59607         }
   59608       }else{
   59609         if( nMinKey <= *pnParentMinKey ){
   59610           checkAppendMsg(pCheck, zContext,
   59611               "Rowid %lld out of order (min less than parent min of %lld)",
   59612               nMinKey, *pnParentMinKey);
   59613         }
   59614         if( nMaxKey > *pnParentMaxKey ){
   59615           checkAppendMsg(pCheck, zContext,
   59616               "Rowid %lld out of order (max larger than parent max of %lld)",
   59617               nMaxKey, *pnParentMaxKey);
   59618         }
   59619         *pnParentMinKey = nMaxKey;
   59620       }
   59621     /* else if we're a right child page */
   59622     } else if( pnParentMaxKey ){
   59623       if( nMinKey <= *pnParentMaxKey ){
   59624         checkAppendMsg(pCheck, zContext,
   59625             "Rowid %lld out of order (min less than parent max of %lld)",
   59626             nMinKey, *pnParentMaxKey);
   59627       }
   59628     }
   59629   }
   59630 
   59631   /* Check for complete coverage of the page
   59632   */
   59633   data = pPage->aData;
   59634   hdr = pPage->hdrOffset;
   59635   hit = sqlite3PageMalloc( pBt->pageSize );
   59636   if( hit==0 ){
   59637     pCheck->mallocFailed = 1;
   59638   }else{
   59639     int contentOffset = get2byteNotZero(&data[hdr+5]);
   59640     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
   59641     memset(hit+contentOffset, 0, usableSize-contentOffset);
   59642     memset(hit, 1, contentOffset);
   59643     nCell = get2byte(&data[hdr+3]);
   59644     cellStart = hdr + 12 - 4*pPage->leaf;
   59645     for(i=0; i<nCell; i++){
   59646       int pc = get2byte(&data[cellStart+i*2]);
   59647       u32 size = 65536;
   59648       int j;
   59649       if( pc<=usableSize-4 ){
   59650         size = cellSizePtr(pPage, &data[pc]);
   59651       }
   59652       if( (int)(pc+size-1)>=usableSize ){
   59653         checkAppendMsg(pCheck, 0,
   59654             "Corruption detected in cell %d on page %d",i,iPage);
   59655       }else{
   59656         for(j=pc+size-1; j>=pc; j--) hit[j]++;
   59657       }
   59658     }
   59659     i = get2byte(&data[hdr+1]);
   59660     while( i>0 ){
   59661       int size, j;
   59662       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
   59663       size = get2byte(&data[i+2]);
   59664       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
   59665       for(j=i+size-1; j>=i; j--) hit[j]++;
   59666       j = get2byte(&data[i]);
   59667       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
   59668       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
   59669       i = j;
   59670     }
   59671     for(i=cnt=0; i<usableSize; i++){
   59672       if( hit[i]==0 ){
   59673         cnt++;
   59674       }else if( hit[i]>1 ){
   59675         checkAppendMsg(pCheck, 0,
   59676           "Multiple uses for byte %d of page %d", i, iPage);
   59677         break;
   59678       }
   59679     }
   59680     if( cnt!=data[hdr+7] ){
   59681       checkAppendMsg(pCheck, 0,
   59682           "Fragmentation of %d bytes reported as %d on page %d",
   59683           cnt, data[hdr+7], iPage);
   59684     }
   59685   }
   59686   sqlite3PageFree(hit);
   59687   releasePage(pPage);
   59688   return depth+1;
   59689 }
   59690 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   59691 
   59692 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   59693 /*
   59694 ** This routine does a complete check of the given BTree file.  aRoot[] is
   59695 ** an array of pages numbers were each page number is the root page of
   59696 ** a table.  nRoot is the number of entries in aRoot.
   59697 **
   59698 ** A read-only or read-write transaction must be opened before calling
   59699 ** this function.
   59700 **
   59701 ** Write the number of error seen in *pnErr.  Except for some memory
   59702 ** allocation errors,  an error message held in memory obtained from
   59703 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
   59704 ** returned.  If a memory allocation error occurs, NULL is returned.
   59705 */
   59706 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
   59707   Btree *p,     /* The btree to be checked */
   59708   int *aRoot,   /* An array of root pages numbers for individual trees */
   59709   int nRoot,    /* Number of entries in aRoot[] */
   59710   int mxErr,    /* Stop reporting errors after this many */
   59711   int *pnErr    /* Write number of errors seen to this variable */
   59712 ){
   59713   Pgno i;
   59714   int nRef;
   59715   IntegrityCk sCheck;
   59716   BtShared *pBt = p->pBt;
   59717   char zErr[100];
   59718 
   59719   sqlite3BtreeEnter(p);
   59720   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
   59721   nRef = sqlite3PagerRefcount(pBt->pPager);
   59722   sCheck.pBt = pBt;
   59723   sCheck.pPager = pBt->pPager;
   59724   sCheck.nPage = btreePagecount(sCheck.pBt);
   59725   sCheck.mxErr = mxErr;
   59726   sCheck.nErr = 0;
   59727   sCheck.mallocFailed = 0;
   59728   *pnErr = 0;
   59729   if( sCheck.nPage==0 ){
   59730     sqlite3BtreeLeave(p);
   59731     return 0;
   59732   }
   59733 
   59734   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
   59735   if( !sCheck.aPgRef ){
   59736     *pnErr = 1;
   59737     sqlite3BtreeLeave(p);
   59738     return 0;
   59739   }
   59740   i = PENDING_BYTE_PAGE(pBt);
   59741   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
   59742   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
   59743   sCheck.errMsg.useMalloc = 2;
   59744 
   59745   /* Check the integrity of the freelist
   59746   */
   59747   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
   59748             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
   59749 
   59750   /* Check all the tables.
   59751   */
   59752   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
   59753     if( aRoot[i]==0 ) continue;
   59754 #ifndef SQLITE_OMIT_AUTOVACUUM
   59755     if( pBt->autoVacuum && aRoot[i]>1 ){
   59756       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
   59757     }
   59758 #endif
   59759     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
   59760   }
   59761 
   59762   /* Make sure every page in the file is referenced
   59763   */
   59764   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
   59765 #ifdef SQLITE_OMIT_AUTOVACUUM
   59766     if( getPageReferenced(&sCheck, i)==0 ){
   59767       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   59768     }
   59769 #else
   59770     /* If the database supports auto-vacuum, make sure no tables contain
   59771     ** references to pointer-map pages.
   59772     */
   59773     if( getPageReferenced(&sCheck, i)==0 &&
   59774        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
   59775       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   59776     }
   59777     if( getPageReferenced(&sCheck, i)!=0 &&
   59778        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
   59779       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
   59780     }
   59781 #endif
   59782   }
   59783 
   59784   /* Make sure this analysis did not leave any unref() pages.
   59785   ** This is an internal consistency check; an integrity check
   59786   ** of the integrity check.
   59787   */
   59788   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
   59789     checkAppendMsg(&sCheck, 0,
   59790       "Outstanding page count goes from %d to %d during this analysis",
   59791       nRef, sqlite3PagerRefcount(pBt->pPager)
   59792     );
   59793   }
   59794 
   59795   /* Clean  up and report errors.
   59796   */
   59797   sqlite3BtreeLeave(p);
   59798   sqlite3_free(sCheck.aPgRef);
   59799   if( sCheck.mallocFailed ){
   59800     sqlite3StrAccumReset(&sCheck.errMsg);
   59801     *pnErr = sCheck.nErr+1;
   59802     return 0;
   59803   }
   59804   *pnErr = sCheck.nErr;
   59805   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
   59806   return sqlite3StrAccumFinish(&sCheck.errMsg);
   59807 }
   59808 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   59809 
   59810 /*
   59811 ** Return the full pathname of the underlying database file.  Return
   59812 ** an empty string if the database is in-memory or a TEMP database.
   59813 **
   59814 ** The pager filename is invariant as long as the pager is
   59815 ** open so it is safe to access without the BtShared mutex.
   59816 */
   59817 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
   59818   assert( p->pBt->pPager!=0 );
   59819   return sqlite3PagerFilename(p->pBt->pPager, 1);
   59820 }
   59821 
   59822 /*
   59823 ** Return the pathname of the journal file for this database. The return
   59824 ** value of this routine is the same regardless of whether the journal file
   59825 ** has been created or not.
   59826 **
   59827 ** The pager journal filename is invariant as long as the pager is
   59828 ** open so it is safe to access without the BtShared mutex.
   59829 */
   59830 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
   59831   assert( p->pBt->pPager!=0 );
   59832   return sqlite3PagerJournalname(p->pBt->pPager);
   59833 }
   59834 
   59835 /*
   59836 ** Return non-zero if a transaction is active.
   59837 */
   59838 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
   59839   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
   59840   return (p && (p->inTrans==TRANS_WRITE));
   59841 }
   59842 
   59843 #ifndef SQLITE_OMIT_WAL
   59844 /*
   59845 ** Run a checkpoint on the Btree passed as the first argument.
   59846 **
   59847 ** Return SQLITE_LOCKED if this or any other connection has an open
   59848 ** transaction on the shared-cache the argument Btree is connected to.
   59849 **
   59850 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   59851 */
   59852 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
   59853   int rc = SQLITE_OK;
   59854   if( p ){
   59855     BtShared *pBt = p->pBt;
   59856     sqlite3BtreeEnter(p);
   59857     if( pBt->inTransaction!=TRANS_NONE ){
   59858       rc = SQLITE_LOCKED;
   59859     }else{
   59860       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
   59861     }
   59862     sqlite3BtreeLeave(p);
   59863   }
   59864   return rc;
   59865 }
   59866 #endif
   59867 
   59868 /*
   59869 ** Return non-zero if a read (or write) transaction is active.
   59870 */
   59871 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
   59872   assert( p );
   59873   assert( sqlite3_mutex_held(p->db->mutex) );
   59874   return p->inTrans!=TRANS_NONE;
   59875 }
   59876 
   59877 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
   59878   assert( p );
   59879   assert( sqlite3_mutex_held(p->db->mutex) );
   59880   return p->nBackup!=0;
   59881 }
   59882 
   59883 /*
   59884 ** This function returns a pointer to a blob of memory associated with
   59885 ** a single shared-btree. The memory is used by client code for its own
   59886 ** purposes (for example, to store a high-level schema associated with
   59887 ** the shared-btree). The btree layer manages reference counting issues.
   59888 **
   59889 ** The first time this is called on a shared-btree, nBytes bytes of memory
   59890 ** are allocated, zeroed, and returned to the caller. For each subsequent
   59891 ** call the nBytes parameter is ignored and a pointer to the same blob
   59892 ** of memory returned.
   59893 **
   59894 ** If the nBytes parameter is 0 and the blob of memory has not yet been
   59895 ** allocated, a null pointer is returned. If the blob has already been
   59896 ** allocated, it is returned as normal.
   59897 **
   59898 ** Just before the shared-btree is closed, the function passed as the
   59899 ** xFree argument when the memory allocation was made is invoked on the
   59900 ** blob of allocated memory. The xFree function should not call sqlite3_free()
   59901 ** on the memory, the btree layer does that.
   59902 */
   59903 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
   59904   BtShared *pBt = p->pBt;
   59905   sqlite3BtreeEnter(p);
   59906   if( !pBt->pSchema && nBytes ){
   59907     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
   59908     pBt->xFreeSchema = xFree;
   59909   }
   59910   sqlite3BtreeLeave(p);
   59911   return pBt->pSchema;
   59912 }
   59913 
   59914 /*
   59915 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
   59916 ** btree as the argument handle holds an exclusive lock on the
   59917 ** sqlite_master table. Otherwise SQLITE_OK.
   59918 */
   59919 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
   59920   int rc;
   59921   assert( sqlite3_mutex_held(p->db->mutex) );
   59922   sqlite3BtreeEnter(p);
   59923   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   59924   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
   59925   sqlite3BtreeLeave(p);
   59926   return rc;
   59927 }
   59928 
   59929 
   59930 #ifndef SQLITE_OMIT_SHARED_CACHE
   59931 /*
   59932 ** Obtain a lock on the table whose root page is iTab.  The
   59933 ** lock is a write lock if isWritelock is true or a read lock
   59934 ** if it is false.
   59935 */
   59936 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
   59937   int rc = SQLITE_OK;
   59938   assert( p->inTrans!=TRANS_NONE );
   59939   if( p->sharable ){
   59940     u8 lockType = READ_LOCK + isWriteLock;
   59941     assert( READ_LOCK+1==WRITE_LOCK );
   59942     assert( isWriteLock==0 || isWriteLock==1 );
   59943 
   59944     sqlite3BtreeEnter(p);
   59945     rc = querySharedCacheTableLock(p, iTab, lockType);
   59946     if( rc==SQLITE_OK ){
   59947       rc = setSharedCacheTableLock(p, iTab, lockType);
   59948     }
   59949     sqlite3BtreeLeave(p);
   59950   }
   59951   return rc;
   59952 }
   59953 #endif
   59954 
   59955 #ifndef SQLITE_OMIT_INCRBLOB
   59956 /*
   59957 ** Argument pCsr must be a cursor opened for writing on an
   59958 ** INTKEY table currently pointing at a valid table entry.
   59959 ** This function modifies the data stored as part of that entry.
   59960 **
   59961 ** Only the data content may only be modified, it is not possible to
   59962 ** change the length of the data stored. If this function is called with
   59963 ** parameters that attempt to write past the end of the existing data,
   59964 ** no modifications are made and SQLITE_CORRUPT is returned.
   59965 */
   59966 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
   59967   int rc;
   59968   assert( cursorHoldsMutex(pCsr) );
   59969   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
   59970   assert( pCsr->curFlags & BTCF_Incrblob );
   59971 
   59972   rc = restoreCursorPosition(pCsr);
   59973   if( rc!=SQLITE_OK ){
   59974     return rc;
   59975   }
   59976   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
   59977   if( pCsr->eState!=CURSOR_VALID ){
   59978     return SQLITE_ABORT;
   59979   }
   59980 
   59981   /* Save the positions of all other cursors open on this table. This is
   59982   ** required in case any of them are holding references to an xFetch
   59983   ** version of the b-tree page modified by the accessPayload call below.
   59984   **
   59985   ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
   59986   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
   59987   ** saveAllCursors can only return SQLITE_OK.
   59988   */
   59989   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
   59990   assert( rc==SQLITE_OK );
   59991 
   59992   /* Check some assumptions:
   59993   **   (a) the cursor is open for writing,
   59994   **   (b) there is a read/write transaction open,
   59995   **   (c) the connection holds a write-lock on the table (if required),
   59996   **   (d) there are no conflicting read-locks, and
   59997   **   (e) the cursor points at a valid row of an intKey table.
   59998   */
   59999   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
   60000     return SQLITE_READONLY;
   60001   }
   60002   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
   60003               && pCsr->pBt->inTransaction==TRANS_WRITE );
   60004   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
   60005   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
   60006   assert( pCsr->apPage[pCsr->iPage]->intKey );
   60007 
   60008   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
   60009 }
   60010 
   60011 /*
   60012 ** Mark this cursor as an incremental blob cursor.
   60013 */
   60014 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
   60015   pCur->curFlags |= BTCF_Incrblob;
   60016 }
   60017 #endif
   60018 
   60019 /*
   60020 ** Set both the "read version" (single byte at byte offset 18) and
   60021 ** "write version" (single byte at byte offset 19) fields in the database
   60022 ** header to iVersion.
   60023 */
   60024 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
   60025   BtShared *pBt = pBtree->pBt;
   60026   int rc;                         /* Return code */
   60027 
   60028   assert( iVersion==1 || iVersion==2 );
   60029 
   60030   /* If setting the version fields to 1, do not automatically open the
   60031   ** WAL connection, even if the version fields are currently set to 2.
   60032   */
   60033   pBt->btsFlags &= ~BTS_NO_WAL;
   60034   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
   60035 
   60036   rc = sqlite3BtreeBeginTrans(pBtree, 0);
   60037   if( rc==SQLITE_OK ){
   60038     u8 *aData = pBt->pPage1->aData;
   60039     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
   60040       rc = sqlite3BtreeBeginTrans(pBtree, 2);
   60041       if( rc==SQLITE_OK ){
   60042         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   60043         if( rc==SQLITE_OK ){
   60044           aData[18] = (u8)iVersion;
   60045           aData[19] = (u8)iVersion;
   60046         }
   60047       }
   60048     }
   60049   }
   60050 
   60051   pBt->btsFlags &= ~BTS_NO_WAL;
   60052   return rc;
   60053 }
   60054 
   60055 /*
   60056 ** set the mask of hint flags for cursor pCsr. Currently the only valid
   60057 ** values are 0 and BTREE_BULKLOAD.
   60058 */
   60059 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
   60060   assert( mask==BTREE_BULKLOAD || mask==0 );
   60061   pCsr->hints = mask;
   60062 }
   60063 
   60064 /*
   60065 ** Return true if the given Btree is read-only.
   60066 */
   60067 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
   60068   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
   60069 }
   60070 
   60071 /************** End of btree.c ***********************************************/
   60072 /************** Begin file backup.c ******************************************/
   60073 /*
   60074 ** 2009 January 28
   60075 **
   60076 ** The author disclaims copyright to this source code.  In place of
   60077 ** a legal notice, here is a blessing:
   60078 **
   60079 **    May you do good and not evil.
   60080 **    May you find forgiveness for yourself and forgive others.
   60081 **    May you share freely, never taking more than you give.
   60082 **
   60083 *************************************************************************
   60084 ** This file contains the implementation of the sqlite3_backup_XXX()
   60085 ** API functions and the related features.
   60086 */
   60087 
   60088 /*
   60089 ** Structure allocated for each backup operation.
   60090 */
   60091 struct sqlite3_backup {
   60092   sqlite3* pDestDb;        /* Destination database handle */
   60093   Btree *pDest;            /* Destination b-tree file */
   60094   u32 iDestSchema;         /* Original schema cookie in destination */
   60095   int bDestLocked;         /* True once a write-transaction is open on pDest */
   60096 
   60097   Pgno iNext;              /* Page number of the next source page to copy */
   60098   sqlite3* pSrcDb;         /* Source database handle */
   60099   Btree *pSrc;             /* Source b-tree file */
   60100 
   60101   int rc;                  /* Backup process error code */
   60102 
   60103   /* These two variables are set by every call to backup_step(). They are
   60104   ** read by calls to backup_remaining() and backup_pagecount().
   60105   */
   60106   Pgno nRemaining;         /* Number of pages left to copy */
   60107   Pgno nPagecount;         /* Total number of pages to copy */
   60108 
   60109   int isAttached;          /* True once backup has been registered with pager */
   60110   sqlite3_backup *pNext;   /* Next backup associated with source pager */
   60111 };
   60112 
   60113 /*
   60114 ** THREAD SAFETY NOTES:
   60115 **
   60116 **   Once it has been created using backup_init(), a single sqlite3_backup
   60117 **   structure may be accessed via two groups of thread-safe entry points:
   60118 **
   60119 **     * Via the sqlite3_backup_XXX() API function backup_step() and
   60120 **       backup_finish(). Both these functions obtain the source database
   60121 **       handle mutex and the mutex associated with the source BtShared
   60122 **       structure, in that order.
   60123 **
   60124 **     * Via the BackupUpdate() and BackupRestart() functions, which are
   60125 **       invoked by the pager layer to report various state changes in
   60126 **       the page cache associated with the source database. The mutex
   60127 **       associated with the source database BtShared structure will always
   60128 **       be held when either of these functions are invoked.
   60129 **
   60130 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
   60131 **   backup_pagecount() are not thread-safe functions. If they are called
   60132 **   while some other thread is calling backup_step() or backup_finish(),
   60133 **   the values returned may be invalid. There is no way for a call to
   60134 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
   60135 **   or backup_pagecount().
   60136 **
   60137 **   Depending on the SQLite configuration, the database handles and/or
   60138 **   the Btree objects may have their own mutexes that require locking.
   60139 **   Non-sharable Btrees (in-memory databases for example), do not have
   60140 **   associated mutexes.
   60141 */
   60142 
   60143 /*
   60144 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
   60145 ** in connection handle pDb. If such a database cannot be found, return
   60146 ** a NULL pointer and write an error message to pErrorDb.
   60147 **
   60148 ** If the "temp" database is requested, it may need to be opened by this
   60149 ** function. If an error occurs while doing so, return 0 and write an
   60150 ** error message to pErrorDb.
   60151 */
   60152 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
   60153   int i = sqlite3FindDbName(pDb, zDb);
   60154 
   60155   if( i==1 ){
   60156     Parse *pParse;
   60157     int rc = 0;
   60158     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
   60159     if( pParse==0 ){
   60160       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
   60161       rc = SQLITE_NOMEM;
   60162     }else{
   60163       pParse->db = pDb;
   60164       if( sqlite3OpenTempDatabase(pParse) ){
   60165         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
   60166         rc = SQLITE_ERROR;
   60167       }
   60168       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
   60169       sqlite3ParserReset(pParse);
   60170       sqlite3StackFree(pErrorDb, pParse);
   60171     }
   60172     if( rc ){
   60173       return 0;
   60174     }
   60175   }
   60176 
   60177   if( i<0 ){
   60178     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
   60179     return 0;
   60180   }
   60181 
   60182   return pDb->aDb[i].pBt;
   60183 }
   60184 
   60185 /*
   60186 ** Attempt to set the page size of the destination to match the page size
   60187 ** of the source.
   60188 */
   60189 static int setDestPgsz(sqlite3_backup *p){
   60190   int rc;
   60191   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
   60192   return rc;
   60193 }
   60194 
   60195 /*
   60196 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
   60197 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
   60198 ** a pointer to the new sqlite3_backup object.
   60199 **
   60200 ** If an error occurs, NULL is returned and an error code and error message
   60201 ** stored in database handle pDestDb.
   60202 */
   60203 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   60204   sqlite3* pDestDb,                     /* Database to write to */
   60205   const char *zDestDb,                  /* Name of database within pDestDb */
   60206   sqlite3* pSrcDb,                      /* Database connection to read from */
   60207   const char *zSrcDb                    /* Name of database within pSrcDb */
   60208 ){
   60209   sqlite3_backup *p;                    /* Value to return */
   60210 
   60211   /* Lock the source database handle. The destination database
   60212   ** handle is not locked in this routine, but it is locked in
   60213   ** sqlite3_backup_step(). The user is required to ensure that no
   60214   ** other thread accesses the destination handle for the duration
   60215   ** of the backup operation.  Any attempt to use the destination
   60216   ** database connection while a backup is in progress may cause
   60217   ** a malfunction or a deadlock.
   60218   */
   60219   sqlite3_mutex_enter(pSrcDb->mutex);
   60220   sqlite3_mutex_enter(pDestDb->mutex);
   60221 
   60222   if( pSrcDb==pDestDb ){
   60223     sqlite3Error(
   60224         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
   60225     );
   60226     p = 0;
   60227   }else {
   60228     /* Allocate space for a new sqlite3_backup object...
   60229     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   60230     ** call to sqlite3_backup_init() and is destroyed by a call to
   60231     ** sqlite3_backup_finish(). */
   60232     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
   60233     if( !p ){
   60234       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
   60235     }
   60236   }
   60237 
   60238   /* If the allocation succeeded, populate the new object. */
   60239   if( p ){
   60240     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
   60241     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
   60242     p->pDestDb = pDestDb;
   60243     p->pSrcDb = pSrcDb;
   60244     p->iNext = 1;
   60245     p->isAttached = 0;
   60246 
   60247     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
   60248       /* One (or both) of the named databases did not exist or an OOM
   60249       ** error was hit.  The error has already been written into the
   60250       ** pDestDb handle.  All that is left to do here is free the
   60251       ** sqlite3_backup structure.
   60252       */
   60253       sqlite3_free(p);
   60254       p = 0;
   60255     }
   60256   }
   60257   if( p ){
   60258     p->pSrc->nBackup++;
   60259   }
   60260 
   60261   sqlite3_mutex_leave(pDestDb->mutex);
   60262   sqlite3_mutex_leave(pSrcDb->mutex);
   60263   return p;
   60264 }
   60265 
   60266 /*
   60267 ** Argument rc is an SQLite error code. Return true if this error is
   60268 ** considered fatal if encountered during a backup operation. All errors
   60269 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
   60270 */
   60271 static int isFatalError(int rc){
   60272   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
   60273 }
   60274 
   60275 /*
   60276 ** Parameter zSrcData points to a buffer containing the data for
   60277 ** page iSrcPg from the source database. Copy this data into the
   60278 ** destination database.
   60279 */
   60280 static int backupOnePage(
   60281   sqlite3_backup *p,              /* Backup handle */
   60282   Pgno iSrcPg,                    /* Source database page to backup */
   60283   const u8 *zSrcData,             /* Source database page data */
   60284   int bUpdate                     /* True for an update, false otherwise */
   60285 ){
   60286   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
   60287   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
   60288   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
   60289   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
   60290   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
   60291 #ifdef SQLITE_HAS_CODEC
   60292   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
   60293   ** guaranteed that the shared-mutex is held by this thread, handle
   60294   ** p->pSrc may not actually be the owner.  */
   60295   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
   60296   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
   60297 #endif
   60298   int rc = SQLITE_OK;
   60299   i64 iOff;
   60300 
   60301   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
   60302   assert( p->bDestLocked );
   60303   assert( !isFatalError(p->rc) );
   60304   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
   60305   assert( zSrcData );
   60306 
   60307   /* Catch the case where the destination is an in-memory database and the
   60308   ** page sizes of the source and destination differ.
   60309   */
   60310   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
   60311     rc = SQLITE_READONLY;
   60312   }
   60313 
   60314 #ifdef SQLITE_HAS_CODEC
   60315   /* Backup is not possible if the page size of the destination is changing
   60316   ** and a codec is in use.
   60317   */
   60318   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
   60319     rc = SQLITE_READONLY;
   60320   }
   60321 
   60322   /* Backup is not possible if the number of bytes of reserve space differ
   60323   ** between source and destination.  If there is a difference, try to
   60324   ** fix the destination to agree with the source.  If that is not possible,
   60325   ** then the backup cannot proceed.
   60326   */
   60327   if( nSrcReserve!=nDestReserve ){
   60328     u32 newPgsz = nSrcPgsz;
   60329     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
   60330     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
   60331   }
   60332 #endif
   60333 
   60334   /* This loop runs once for each destination page spanned by the source
   60335   ** page. For each iteration, variable iOff is set to the byte offset
   60336   ** of the destination page.
   60337   */
   60338   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
   60339     DbPage *pDestPg = 0;
   60340     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
   60341     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
   60342     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
   60343      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
   60344     ){
   60345       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
   60346       u8 *zDestData = sqlite3PagerGetData(pDestPg);
   60347       u8 *zOut = &zDestData[iOff%nDestPgsz];
   60348 
   60349       /* Copy the data from the source page into the destination page.
   60350       ** Then clear the Btree layer MemPage.isInit flag. Both this module
   60351       ** and the pager code use this trick (clearing the first byte
   60352       ** of the page 'extra' space to invalidate the Btree layers
   60353       ** cached parse of the page). MemPage.isInit is marked
   60354       ** "MUST BE FIRST" for this purpose.
   60355       */
   60356       memcpy(zOut, zIn, nCopy);
   60357       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
   60358       if( iOff==0 && bUpdate==0 ){
   60359         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
   60360       }
   60361     }
   60362     sqlite3PagerUnref(pDestPg);
   60363   }
   60364 
   60365   return rc;
   60366 }
   60367 
   60368 /*
   60369 ** If pFile is currently larger than iSize bytes, then truncate it to
   60370 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
   60371 ** this function is a no-op.
   60372 **
   60373 ** Return SQLITE_OK if everything is successful, or an SQLite error
   60374 ** code if an error occurs.
   60375 */
   60376 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
   60377   i64 iCurrent;
   60378   int rc = sqlite3OsFileSize(pFile, &iCurrent);
   60379   if( rc==SQLITE_OK && iCurrent>iSize ){
   60380     rc = sqlite3OsTruncate(pFile, iSize);
   60381   }
   60382   return rc;
   60383 }
   60384 
   60385 /*
   60386 ** Register this backup object with the associated source pager for
   60387 ** callbacks when pages are changed or the cache invalidated.
   60388 */
   60389 static void attachBackupObject(sqlite3_backup *p){
   60390   sqlite3_backup **pp;
   60391   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
   60392   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   60393   p->pNext = *pp;
   60394   *pp = p;
   60395   p->isAttached = 1;
   60396 }
   60397 
   60398 /*
   60399 ** Copy nPage pages from the source b-tree to the destination.
   60400 */
   60401 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
   60402   int rc;
   60403   int destMode;       /* Destination journal mode */
   60404   int pgszSrc = 0;    /* Source page size */
   60405   int pgszDest = 0;   /* Destination page size */
   60406 
   60407   sqlite3_mutex_enter(p->pSrcDb->mutex);
   60408   sqlite3BtreeEnter(p->pSrc);
   60409   if( p->pDestDb ){
   60410     sqlite3_mutex_enter(p->pDestDb->mutex);
   60411   }
   60412 
   60413   rc = p->rc;
   60414   if( !isFatalError(rc) ){
   60415     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
   60416     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
   60417     int ii;                            /* Iterator variable */
   60418     int nSrcPage = -1;                 /* Size of source db in pages */
   60419     int bCloseTrans = 0;               /* True if src db requires unlocking */
   60420 
   60421     /* If the source pager is currently in a write-transaction, return
   60422     ** SQLITE_BUSY immediately.
   60423     */
   60424     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
   60425       rc = SQLITE_BUSY;
   60426     }else{
   60427       rc = SQLITE_OK;
   60428     }
   60429 
   60430     /* Lock the destination database, if it is not locked already. */
   60431     if( SQLITE_OK==rc && p->bDestLocked==0
   60432      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
   60433     ){
   60434       p->bDestLocked = 1;
   60435       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
   60436     }
   60437 
   60438     /* If there is no open read-transaction on the source database, open
   60439     ** one now. If a transaction is opened here, then it will be closed
   60440     ** before this function exits.
   60441     */
   60442     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
   60443       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
   60444       bCloseTrans = 1;
   60445     }
   60446 
   60447     /* Do not allow backup if the destination database is in WAL mode
   60448     ** and the page sizes are different between source and destination */
   60449     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
   60450     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
   60451     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
   60452     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
   60453       rc = SQLITE_READONLY;
   60454     }
   60455 
   60456     /* Now that there is a read-lock on the source database, query the
   60457     ** source pager for the number of pages in the database.
   60458     */
   60459     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
   60460     assert( nSrcPage>=0 );
   60461     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
   60462       const Pgno iSrcPg = p->iNext;                 /* Source page number */
   60463       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
   60464         DbPage *pSrcPg;                             /* Source page object */
   60465         rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
   60466                                  PAGER_GET_READONLY);
   60467         if( rc==SQLITE_OK ){
   60468           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
   60469           sqlite3PagerUnref(pSrcPg);
   60470         }
   60471       }
   60472       p->iNext++;
   60473     }
   60474     if( rc==SQLITE_OK ){
   60475       p->nPagecount = nSrcPage;
   60476       p->nRemaining = nSrcPage+1-p->iNext;
   60477       if( p->iNext>(Pgno)nSrcPage ){
   60478         rc = SQLITE_DONE;
   60479       }else if( !p->isAttached ){
   60480         attachBackupObject(p);
   60481       }
   60482     }
   60483 
   60484     /* Update the schema version field in the destination database. This
   60485     ** is to make sure that the schema-version really does change in
   60486     ** the case where the source and destination databases have the
   60487     ** same schema version.
   60488     */
   60489     if( rc==SQLITE_DONE ){
   60490       if( nSrcPage==0 ){
   60491         rc = sqlite3BtreeNewDb(p->pDest);
   60492         nSrcPage = 1;
   60493       }
   60494       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
   60495         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
   60496       }
   60497       if( rc==SQLITE_OK ){
   60498         if( p->pDestDb ){
   60499           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
   60500         }
   60501         if( destMode==PAGER_JOURNALMODE_WAL ){
   60502           rc = sqlite3BtreeSetVersion(p->pDest, 2);
   60503         }
   60504       }
   60505       if( rc==SQLITE_OK ){
   60506         int nDestTruncate;
   60507         /* Set nDestTruncate to the final number of pages in the destination
   60508         ** database. The complication here is that the destination page
   60509         ** size may be different to the source page size.
   60510         **
   60511         ** If the source page size is smaller than the destination page size,
   60512         ** round up. In this case the call to sqlite3OsTruncate() below will
   60513         ** fix the size of the file. However it is important to call
   60514         ** sqlite3PagerTruncateImage() here so that any pages in the
   60515         ** destination file that lie beyond the nDestTruncate page mark are
   60516         ** journalled by PagerCommitPhaseOne() before they are destroyed
   60517         ** by the file truncation.
   60518         */
   60519         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
   60520         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
   60521         if( pgszSrc<pgszDest ){
   60522           int ratio = pgszDest/pgszSrc;
   60523           nDestTruncate = (nSrcPage+ratio-1)/ratio;
   60524           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
   60525             nDestTruncate--;
   60526           }
   60527         }else{
   60528           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
   60529         }
   60530         assert( nDestTruncate>0 );
   60531 
   60532         if( pgszSrc<pgszDest ){
   60533           /* If the source page-size is smaller than the destination page-size,
   60534           ** two extra things may need to happen:
   60535           **
   60536           **   * The destination may need to be truncated, and
   60537           **
   60538           **   * Data stored on the pages immediately following the
   60539           **     pending-byte page in the source database may need to be
   60540           **     copied into the destination database.
   60541           */
   60542           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
   60543           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
   60544           Pgno iPg;
   60545           int nDstPage;
   60546           i64 iOff;
   60547           i64 iEnd;
   60548 
   60549           assert( pFile );
   60550           assert( nDestTruncate==0
   60551               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
   60552                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
   60553              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
   60554           ));
   60555 
   60556           /* This block ensures that all data required to recreate the original
   60557           ** database has been stored in the journal for pDestPager and the
   60558           ** journal synced to disk. So at this point we may safely modify
   60559           ** the database file in any way, knowing that if a power failure
   60560           ** occurs, the original database will be reconstructed from the
   60561           ** journal file.  */
   60562           sqlite3PagerPagecount(pDestPager, &nDstPage);
   60563           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
   60564             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
   60565               DbPage *pPg;
   60566               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
   60567               if( rc==SQLITE_OK ){
   60568                 rc = sqlite3PagerWrite(pPg);
   60569                 sqlite3PagerUnref(pPg);
   60570               }
   60571             }
   60572           }
   60573           if( rc==SQLITE_OK ){
   60574             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
   60575           }
   60576 
   60577           /* Write the extra pages and truncate the database file as required */
   60578           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
   60579           for(
   60580             iOff=PENDING_BYTE+pgszSrc;
   60581             rc==SQLITE_OK && iOff<iEnd;
   60582             iOff+=pgszSrc
   60583           ){
   60584             PgHdr *pSrcPg = 0;
   60585             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
   60586             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   60587             if( rc==SQLITE_OK ){
   60588               u8 *zData = sqlite3PagerGetData(pSrcPg);
   60589               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
   60590             }
   60591             sqlite3PagerUnref(pSrcPg);
   60592           }
   60593           if( rc==SQLITE_OK ){
   60594             rc = backupTruncateFile(pFile, iSize);
   60595           }
   60596 
   60597           /* Sync the database file to disk. */
   60598           if( rc==SQLITE_OK ){
   60599             rc = sqlite3PagerSync(pDestPager, 0);
   60600           }
   60601         }else{
   60602           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
   60603           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
   60604         }
   60605 
   60606         /* Finish committing the transaction to the destination database. */
   60607         if( SQLITE_OK==rc
   60608          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
   60609         ){
   60610           rc = SQLITE_DONE;
   60611         }
   60612       }
   60613     }
   60614 
   60615     /* If bCloseTrans is true, then this function opened a read transaction
   60616     ** on the source database. Close the read transaction here. There is
   60617     ** no need to check the return values of the btree methods here, as
   60618     ** "committing" a read-only transaction cannot fail.
   60619     */
   60620     if( bCloseTrans ){
   60621       TESTONLY( int rc2 );
   60622       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
   60623       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
   60624       assert( rc2==SQLITE_OK );
   60625     }
   60626 
   60627     if( rc==SQLITE_IOERR_NOMEM ){
   60628       rc = SQLITE_NOMEM;
   60629     }
   60630     p->rc = rc;
   60631   }
   60632   if( p->pDestDb ){
   60633     sqlite3_mutex_leave(p->pDestDb->mutex);
   60634   }
   60635   sqlite3BtreeLeave(p->pSrc);
   60636   sqlite3_mutex_leave(p->pSrcDb->mutex);
   60637   return rc;
   60638 }
   60639 
   60640 /*
   60641 ** Release all resources associated with an sqlite3_backup* handle.
   60642 */
   60643 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
   60644   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
   60645   sqlite3 *pSrcDb;                     /* Source database connection */
   60646   int rc;                              /* Value to return */
   60647 
   60648   /* Enter the mutexes */
   60649   if( p==0 ) return SQLITE_OK;
   60650   pSrcDb = p->pSrcDb;
   60651   sqlite3_mutex_enter(pSrcDb->mutex);
   60652   sqlite3BtreeEnter(p->pSrc);
   60653   if( p->pDestDb ){
   60654     sqlite3_mutex_enter(p->pDestDb->mutex);
   60655   }
   60656 
   60657   /* Detach this backup from the source pager. */
   60658   if( p->pDestDb ){
   60659     p->pSrc->nBackup--;
   60660   }
   60661   if( p->isAttached ){
   60662     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   60663     while( *pp!=p ){
   60664       pp = &(*pp)->pNext;
   60665     }
   60666     *pp = p->pNext;
   60667   }
   60668 
   60669   /* If a transaction is still open on the Btree, roll it back. */
   60670   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
   60671 
   60672   /* Set the error code of the destination database handle. */
   60673   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
   60674   if( p->pDestDb ){
   60675     sqlite3Error(p->pDestDb, rc, 0);
   60676 
   60677     /* Exit the mutexes and free the backup context structure. */
   60678     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
   60679   }
   60680   sqlite3BtreeLeave(p->pSrc);
   60681   if( p->pDestDb ){
   60682     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   60683     ** call to sqlite3_backup_init() and is destroyed by a call to
   60684     ** sqlite3_backup_finish(). */
   60685     sqlite3_free(p);
   60686   }
   60687   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
   60688   return rc;
   60689 }
   60690 
   60691 /*
   60692 ** Return the number of pages still to be backed up as of the most recent
   60693 ** call to sqlite3_backup_step().
   60694 */
   60695 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
   60696   return p->nRemaining;
   60697 }
   60698 
   60699 /*
   60700 ** Return the total number of pages in the source database as of the most
   60701 ** recent call to sqlite3_backup_step().
   60702 */
   60703 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
   60704   return p->nPagecount;
   60705 }
   60706 
   60707 /*
   60708 ** This function is called after the contents of page iPage of the
   60709 ** source database have been modified. If page iPage has already been
   60710 ** copied into the destination database, then the data written to the
   60711 ** destination is now invalidated. The destination copy of iPage needs
   60712 ** to be updated with the new data before the backup operation is
   60713 ** complete.
   60714 **
   60715 ** It is assumed that the mutex associated with the BtShared object
   60716 ** corresponding to the source database is held when this function is
   60717 ** called.
   60718 */
   60719 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
   60720   sqlite3_backup *p;                   /* Iterator variable */
   60721   for(p=pBackup; p; p=p->pNext){
   60722     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   60723     if( !isFatalError(p->rc) && iPage<p->iNext ){
   60724       /* The backup process p has already copied page iPage. But now it
   60725       ** has been modified by a transaction on the source pager. Copy
   60726       ** the new data into the backup.
   60727       */
   60728       int rc;
   60729       assert( p->pDestDb );
   60730       sqlite3_mutex_enter(p->pDestDb->mutex);
   60731       rc = backupOnePage(p, iPage, aData, 1);
   60732       sqlite3_mutex_leave(p->pDestDb->mutex);
   60733       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
   60734       if( rc!=SQLITE_OK ){
   60735         p->rc = rc;
   60736       }
   60737     }
   60738   }
   60739 }
   60740 
   60741 /*
   60742 ** Restart the backup process. This is called when the pager layer
   60743 ** detects that the database has been modified by an external database
   60744 ** connection. In this case there is no way of knowing which of the
   60745 ** pages that have been copied into the destination database are still
   60746 ** valid and which are not, so the entire process needs to be restarted.
   60747 **
   60748 ** It is assumed that the mutex associated with the BtShared object
   60749 ** corresponding to the source database is held when this function is
   60750 ** called.
   60751 */
   60752 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
   60753   sqlite3_backup *p;                   /* Iterator variable */
   60754   for(p=pBackup; p; p=p->pNext){
   60755     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   60756     p->iNext = 1;
   60757   }
   60758 }
   60759 
   60760 #ifndef SQLITE_OMIT_VACUUM
   60761 /*
   60762 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
   60763 ** must be active for both files.
   60764 **
   60765 ** The size of file pTo may be reduced by this operation. If anything
   60766 ** goes wrong, the transaction on pTo is rolled back. If successful, the
   60767 ** transaction is committed before returning.
   60768 */
   60769 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   60770   int rc;
   60771   sqlite3_file *pFd;              /* File descriptor for database pTo */
   60772   sqlite3_backup b;
   60773   sqlite3BtreeEnter(pTo);
   60774   sqlite3BtreeEnter(pFrom);
   60775 
   60776   assert( sqlite3BtreeIsInTrans(pTo) );
   60777   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
   60778   if( pFd->pMethods ){
   60779     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
   60780     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
   60781     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   60782     if( rc ) goto copy_finished;
   60783   }
   60784 
   60785   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
   60786   ** to 0. This is used by the implementations of sqlite3_backup_step()
   60787   ** and sqlite3_backup_finish() to detect that they are being called
   60788   ** from this function, not directly by the user.
   60789   */
   60790   memset(&b, 0, sizeof(b));
   60791   b.pSrcDb = pFrom->db;
   60792   b.pSrc = pFrom;
   60793   b.pDest = pTo;
   60794   b.iNext = 1;
   60795 
   60796   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
   60797   ** file. By passing this as the number of pages to copy to
   60798   ** sqlite3_backup_step(), we can guarantee that the copy finishes
   60799   ** within a single call (unless an error occurs). The assert() statement
   60800   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
   60801   ** or an error code.
   60802   */
   60803   sqlite3_backup_step(&b, 0x7FFFFFFF);
   60804   assert( b.rc!=SQLITE_OK );
   60805   rc = sqlite3_backup_finish(&b);
   60806   if( rc==SQLITE_OK ){
   60807     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
   60808   }else{
   60809     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
   60810   }
   60811 
   60812   assert( sqlite3BtreeIsInTrans(pTo)==0 );
   60813 copy_finished:
   60814   sqlite3BtreeLeave(pFrom);
   60815   sqlite3BtreeLeave(pTo);
   60816   return rc;
   60817 }
   60818 #endif /* SQLITE_OMIT_VACUUM */
   60819 
   60820 /************** End of backup.c **********************************************/
   60821 /************** Begin file vdbemem.c *****************************************/
   60822 /*
   60823 ** 2004 May 26
   60824 **
   60825 ** The author disclaims copyright to this source code.  In place of
   60826 ** a legal notice, here is a blessing:
   60827 **
   60828 **    May you do good and not evil.
   60829 **    May you find forgiveness for yourself and forgive others.
   60830 **    May you share freely, never taking more than you give.
   60831 **
   60832 *************************************************************************
   60833 **
   60834 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
   60835 ** stores a single value in the VDBE.  Mem is an opaque structure visible
   60836 ** only within the VDBE.  Interface routines refer to a Mem using the
   60837 ** name sqlite_value
   60838 */
   60839 
   60840 #ifdef SQLITE_DEBUG
   60841 /*
   60842 ** Check invariants on a Mem object.
   60843 **
   60844 ** This routine is intended for use inside of assert() statements, like
   60845 ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
   60846 */
   60847 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
   60848   /* The MEM_Dyn bit is set if and only if Mem.xDel is a non-NULL destructor
   60849   ** function for Mem.z
   60850   */
   60851   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
   60852   assert( (p->flags & MEM_Dyn)!=0 || p->xDel==0 );
   60853 
   60854   /* If p holds a string or blob, the Mem.z must point to exactly
   60855   ** one of the following:
   60856   **
   60857   **   (1) Memory in Mem.zMalloc and managed by the Mem object
   60858   **   (2) Memory to be freed using Mem.xDel
   60859   **   (3) An ephermal string or blob
   60860   **   (4) A static string or blob
   60861   */
   60862   if( (p->flags & (MEM_Str|MEM_Blob)) && p->z!=0 ){
   60863     assert(
   60864       ((p->z==p->zMalloc)? 1 : 0) +
   60865       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
   60866       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
   60867       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
   60868     );
   60869   }
   60870 
   60871   return 1;
   60872 }
   60873 #endif
   60874 
   60875 
   60876 /*
   60877 ** If pMem is an object with a valid string representation, this routine
   60878 ** ensures the internal encoding for the string representation is
   60879 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
   60880 **
   60881 ** If pMem is not a string object, or the encoding of the string
   60882 ** representation is already stored using the requested encoding, then this
   60883 ** routine is a no-op.
   60884 **
   60885 ** SQLITE_OK is returned if the conversion is successful (or not required).
   60886 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
   60887 ** between formats.
   60888 */
   60889 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
   60890 #ifndef SQLITE_OMIT_UTF16
   60891   int rc;
   60892 #endif
   60893   assert( (pMem->flags&MEM_RowSet)==0 );
   60894   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
   60895            || desiredEnc==SQLITE_UTF16BE );
   60896   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
   60897     return SQLITE_OK;
   60898   }
   60899   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   60900 #ifdef SQLITE_OMIT_UTF16
   60901   return SQLITE_ERROR;
   60902 #else
   60903 
   60904   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
   60905   ** then the encoding of the value may not have changed.
   60906   */
   60907   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
   60908   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
   60909   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
   60910   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
   60911   return rc;
   60912 #endif
   60913 }
   60914 
   60915 /*
   60916 ** Make sure pMem->z points to a writable allocation of at least
   60917 ** min(n,32) bytes.
   60918 **
   60919 ** If the bPreserve argument is true, then copy of the content of
   60920 ** pMem->z into the new allocation.  pMem must be either a string or
   60921 ** blob if bPreserve is true.  If bPreserve is false, any prior content
   60922 ** in pMem->z is discarded.
   60923 */
   60924 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
   60925   assert( sqlite3VdbeCheckMemInvariants(pMem) );
   60926   assert( (pMem->flags&MEM_RowSet)==0 );
   60927 
   60928   /* If the bPreserve flag is set to true, then the memory cell must already
   60929   ** contain a valid string or blob value.  */
   60930   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
   60931   testcase( bPreserve && pMem->z==0 );
   60932 
   60933   if( pMem->zMalloc==0 || sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
   60934     if( n<32 ) n = 32;
   60935     if( bPreserve && pMem->z==pMem->zMalloc ){
   60936       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
   60937       bPreserve = 0;
   60938     }else{
   60939       sqlite3DbFree(pMem->db, pMem->zMalloc);
   60940       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
   60941     }
   60942     if( pMem->zMalloc==0 ){
   60943       VdbeMemRelease(pMem);
   60944       pMem->z = 0;
   60945       pMem->flags = MEM_Null;
   60946       return SQLITE_NOMEM;
   60947     }
   60948   }
   60949 
   60950   if( pMem->z && bPreserve && pMem->z!=pMem->zMalloc ){
   60951     memcpy(pMem->zMalloc, pMem->z, pMem->n);
   60952   }
   60953   if( (pMem->flags&MEM_Dyn)!=0 ){
   60954     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
   60955     pMem->xDel((void *)(pMem->z));
   60956   }
   60957 
   60958   pMem->z = pMem->zMalloc;
   60959   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
   60960   pMem->xDel = 0;
   60961   return SQLITE_OK;
   60962 }
   60963 
   60964 /*
   60965 ** Make the given Mem object MEM_Dyn.  In other words, make it so
   60966 ** that any TEXT or BLOB content is stored in memory obtained from
   60967 ** malloc().  In this way, we know that the memory is safe to be
   60968 ** overwritten or altered.
   60969 **
   60970 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
   60971 */
   60972 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
   60973   int f;
   60974   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   60975   assert( (pMem->flags&MEM_RowSet)==0 );
   60976   ExpandBlob(pMem);
   60977   f = pMem->flags;
   60978   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
   60979     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
   60980       return SQLITE_NOMEM;
   60981     }
   60982     pMem->z[pMem->n] = 0;
   60983     pMem->z[pMem->n+1] = 0;
   60984     pMem->flags |= MEM_Term;
   60985 #ifdef SQLITE_DEBUG
   60986     pMem->pScopyFrom = 0;
   60987 #endif
   60988   }
   60989 
   60990   return SQLITE_OK;
   60991 }
   60992 
   60993 /*
   60994 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
   60995 ** blob stored in dynamically allocated space.
   60996 */
   60997 #ifndef SQLITE_OMIT_INCRBLOB
   60998 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   60999   if( pMem->flags & MEM_Zero ){
   61000     int nByte;
   61001     assert( pMem->flags&MEM_Blob );
   61002     assert( (pMem->flags&MEM_RowSet)==0 );
   61003     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61004 
   61005     /* Set nByte to the number of bytes required to store the expanded blob. */
   61006     nByte = pMem->n + pMem->u.nZero;
   61007     if( nByte<=0 ){
   61008       nByte = 1;
   61009     }
   61010     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
   61011       return SQLITE_NOMEM;
   61012     }
   61013 
   61014     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
   61015     pMem->n += pMem->u.nZero;
   61016     pMem->flags &= ~(MEM_Zero|MEM_Term);
   61017   }
   61018   return SQLITE_OK;
   61019 }
   61020 #endif
   61021 
   61022 
   61023 /*
   61024 ** Make sure the given Mem is \u0000 terminated.
   61025 */
   61026 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
   61027   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61028   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
   61029     return SQLITE_OK;   /* Nothing to do */
   61030   }
   61031   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
   61032     return SQLITE_NOMEM;
   61033   }
   61034   pMem->z[pMem->n] = 0;
   61035   pMem->z[pMem->n+1] = 0;
   61036   pMem->flags |= MEM_Term;
   61037   return SQLITE_OK;
   61038 }
   61039 
   61040 /*
   61041 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
   61042 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
   61043 ** is a no-op.
   61044 **
   61045 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
   61046 **
   61047 ** A MEM_Null value will never be passed to this function. This function is
   61048 ** used for converting values to text for returning to the user (i.e. via
   61049 ** sqlite3_value_text()), or for ensuring that values to be used as btree
   61050 ** keys are strings. In the former case a NULL pointer is returned the
   61051 ** user and the later is an internal programming error.
   61052 */
   61053 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
   61054   int rc = SQLITE_OK;
   61055   int fg = pMem->flags;
   61056   const int nByte = 32;
   61057 
   61058   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61059   assert( !(fg&MEM_Zero) );
   61060   assert( !(fg&(MEM_Str|MEM_Blob)) );
   61061   assert( fg&(MEM_Int|MEM_Real) );
   61062   assert( (pMem->flags&MEM_RowSet)==0 );
   61063   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61064 
   61065 
   61066   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   61067     return SQLITE_NOMEM;
   61068   }
   61069 
   61070   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
   61071   ** string representation of the value. Then, if the required encoding
   61072   ** is UTF-16le or UTF-16be do a translation.
   61073   **
   61074   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
   61075   */
   61076   if( fg & MEM_Int ){
   61077     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
   61078   }else{
   61079     assert( fg & MEM_Real );
   61080     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
   61081   }
   61082   pMem->n = sqlite3Strlen30(pMem->z);
   61083   pMem->enc = SQLITE_UTF8;
   61084   pMem->flags |= MEM_Str|MEM_Term;
   61085   sqlite3VdbeChangeEncoding(pMem, enc);
   61086   return rc;
   61087 }
   61088 
   61089 /*
   61090 ** Memory cell pMem contains the context of an aggregate function.
   61091 ** This routine calls the finalize method for that function.  The
   61092 ** result of the aggregate is stored back into pMem.
   61093 **
   61094 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
   61095 ** otherwise.
   61096 */
   61097 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
   61098   int rc = SQLITE_OK;
   61099   if( ALWAYS(pFunc && pFunc->xFinalize) ){
   61100     sqlite3_context ctx;
   61101     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
   61102     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61103     memset(&ctx, 0, sizeof(ctx));
   61104     ctx.s.flags = MEM_Null;
   61105     ctx.s.db = pMem->db;
   61106     ctx.pMem = pMem;
   61107     ctx.pFunc = pFunc;
   61108     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
   61109     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
   61110     sqlite3DbFree(pMem->db, pMem->zMalloc);
   61111     memcpy(pMem, &ctx.s, sizeof(ctx.s));
   61112     rc = ctx.isError;
   61113   }
   61114   return rc;
   61115 }
   61116 
   61117 /*
   61118 ** If the memory cell contains a string value that must be freed by
   61119 ** invoking an external callback, free it now. Calling this function
   61120 ** does not free any Mem.zMalloc buffer.
   61121 */
   61122 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
   61123   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   61124   if( p->flags&MEM_Agg ){
   61125     sqlite3VdbeMemFinalize(p, p->u.pDef);
   61126     assert( (p->flags & MEM_Agg)==0 );
   61127     sqlite3VdbeMemRelease(p);
   61128   }else if( p->flags&MEM_Dyn ){
   61129     assert( (p->flags&MEM_RowSet)==0 );
   61130     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
   61131     p->xDel((void *)p->z);
   61132     p->xDel = 0;
   61133   }else if( p->flags&MEM_RowSet ){
   61134     sqlite3RowSetClear(p->u.pRowSet);
   61135   }else if( p->flags&MEM_Frame ){
   61136     sqlite3VdbeMemSetNull(p);
   61137   }
   61138 }
   61139 
   61140 /*
   61141 ** Release any memory held by the Mem. This may leave the Mem in an
   61142 ** inconsistent state, for example with (Mem.z==0) and
   61143 ** (Mem.flags==MEM_Str).
   61144 */
   61145 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
   61146   assert( sqlite3VdbeCheckMemInvariants(p) );
   61147   VdbeMemRelease(p);
   61148   if( p->zMalloc ){
   61149     sqlite3DbFree(p->db, p->zMalloc);
   61150     p->zMalloc = 0;
   61151   }
   61152   p->z = 0;
   61153   assert( p->xDel==0 );  /* Zeroed by VdbeMemRelease() above */
   61154 }
   61155 
   61156 /*
   61157 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
   61158 ** If the double is out of range of a 64-bit signed integer then
   61159 ** return the closest available 64-bit signed integer.
   61160 */
   61161 static i64 doubleToInt64(double r){
   61162 #ifdef SQLITE_OMIT_FLOATING_POINT
   61163   /* When floating-point is omitted, double and int64 are the same thing */
   61164   return r;
   61165 #else
   61166   /*
   61167   ** Many compilers we encounter do not define constants for the
   61168   ** minimum and maximum 64-bit integers, or they define them
   61169   ** inconsistently.  And many do not understand the "LL" notation.
   61170   ** So we define our own static constants here using nothing
   61171   ** larger than a 32-bit integer constant.
   61172   */
   61173   static const i64 maxInt = LARGEST_INT64;
   61174   static const i64 minInt = SMALLEST_INT64;
   61175 
   61176   if( r<=(double)minInt ){
   61177     return minInt;
   61178   }else if( r>=(double)maxInt ){
   61179     return maxInt;
   61180   }else{
   61181     return (i64)r;
   61182   }
   61183 #endif
   61184 }
   61185 
   61186 /*
   61187 ** Return some kind of integer value which is the best we can do
   61188 ** at representing the value that *pMem describes as an integer.
   61189 ** If pMem is an integer, then the value is exact.  If pMem is
   61190 ** a floating-point then the value returned is the integer part.
   61191 ** If pMem is a string or blob, then we make an attempt to convert
   61192 ** it into a integer and return that.  If pMem represents an
   61193 ** an SQL-NULL value, return 0.
   61194 **
   61195 ** If pMem represents a string value, its encoding might be changed.
   61196 */
   61197 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
   61198   int flags;
   61199   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61200   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61201   flags = pMem->flags;
   61202   if( flags & MEM_Int ){
   61203     return pMem->u.i;
   61204   }else if( flags & MEM_Real ){
   61205     return doubleToInt64(pMem->r);
   61206   }else if( flags & (MEM_Str|MEM_Blob) ){
   61207     i64 value = 0;
   61208     assert( pMem->z || pMem->n==0 );
   61209     testcase( pMem->z==0 );
   61210     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
   61211     return value;
   61212   }else{
   61213     return 0;
   61214   }
   61215 }
   61216 
   61217 /*
   61218 ** Return the best representation of pMem that we can get into a
   61219 ** double.  If pMem is already a double or an integer, return its
   61220 ** value.  If it is a string or blob, try to convert it to a double.
   61221 ** If it is a NULL, return 0.0.
   61222 */
   61223 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
   61224   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61225   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61226   if( pMem->flags & MEM_Real ){
   61227     return pMem->r;
   61228   }else if( pMem->flags & MEM_Int ){
   61229     return (double)pMem->u.i;
   61230   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
   61231     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   61232     double val = (double)0;
   61233     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
   61234     return val;
   61235   }else{
   61236     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   61237     return (double)0;
   61238   }
   61239 }
   61240 
   61241 /*
   61242 ** The MEM structure is already a MEM_Real.  Try to also make it a
   61243 ** MEM_Int if we can.
   61244 */
   61245 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
   61246   assert( pMem->flags & MEM_Real );
   61247   assert( (pMem->flags & MEM_RowSet)==0 );
   61248   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61249   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61250 
   61251   pMem->u.i = doubleToInt64(pMem->r);
   61252 
   61253   /* Only mark the value as an integer if
   61254   **
   61255   **    (1) the round-trip conversion real->int->real is a no-op, and
   61256   **    (2) The integer is neither the largest nor the smallest
   61257   **        possible integer (ticket #3922)
   61258   **
   61259   ** The second and third terms in the following conditional enforces
   61260   ** the second condition under the assumption that addition overflow causes
   61261   ** values to wrap around.
   61262   */
   61263   if( pMem->r==(double)pMem->u.i
   61264    && pMem->u.i>SMALLEST_INT64
   61265    && pMem->u.i<LARGEST_INT64
   61266   ){
   61267     pMem->flags |= MEM_Int;
   61268   }
   61269 }
   61270 
   61271 /*
   61272 ** Convert pMem to type integer.  Invalidate any prior representations.
   61273 */
   61274 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
   61275   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61276   assert( (pMem->flags & MEM_RowSet)==0 );
   61277   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61278 
   61279   pMem->u.i = sqlite3VdbeIntValue(pMem);
   61280   MemSetTypeFlag(pMem, MEM_Int);
   61281   return SQLITE_OK;
   61282 }
   61283 
   61284 /*
   61285 ** Convert pMem so that it is of type MEM_Real.
   61286 ** Invalidate any prior representations.
   61287 */
   61288 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
   61289   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61290   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   61291 
   61292   pMem->r = sqlite3VdbeRealValue(pMem);
   61293   MemSetTypeFlag(pMem, MEM_Real);
   61294   return SQLITE_OK;
   61295 }
   61296 
   61297 /*
   61298 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
   61299 ** Invalidate any prior representations.
   61300 **
   61301 ** Every effort is made to force the conversion, even if the input
   61302 ** is a string that does not look completely like a number.  Convert
   61303 ** as much of the string as we can and ignore the rest.
   61304 */
   61305 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
   61306   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
   61307     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
   61308     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61309     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
   61310       MemSetTypeFlag(pMem, MEM_Int);
   61311     }else{
   61312       pMem->r = sqlite3VdbeRealValue(pMem);
   61313       MemSetTypeFlag(pMem, MEM_Real);
   61314       sqlite3VdbeIntegerAffinity(pMem);
   61315     }
   61316   }
   61317   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
   61318   pMem->flags &= ~(MEM_Str|MEM_Blob);
   61319   return SQLITE_OK;
   61320 }
   61321 
   61322 /*
   61323 ** Delete any previous value and set the value stored in *pMem to NULL.
   61324 */
   61325 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
   61326   if( pMem->flags & MEM_Frame ){
   61327     VdbeFrame *pFrame = pMem->u.pFrame;
   61328     pFrame->pParent = pFrame->v->pDelFrame;
   61329     pFrame->v->pDelFrame = pFrame;
   61330   }
   61331   if( pMem->flags & MEM_RowSet ){
   61332     sqlite3RowSetClear(pMem->u.pRowSet);
   61333   }
   61334   MemSetTypeFlag(pMem, MEM_Null);
   61335 }
   61336 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
   61337   sqlite3VdbeMemSetNull((Mem*)p);
   61338 }
   61339 
   61340 /*
   61341 ** Delete any previous value and set the value to be a BLOB of length
   61342 ** n containing all zeros.
   61343 */
   61344 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   61345   sqlite3VdbeMemRelease(pMem);
   61346   pMem->flags = MEM_Blob|MEM_Zero;
   61347   pMem->n = 0;
   61348   if( n<0 ) n = 0;
   61349   pMem->u.nZero = n;
   61350   pMem->enc = SQLITE_UTF8;
   61351 
   61352 #ifdef SQLITE_OMIT_INCRBLOB
   61353   sqlite3VdbeMemGrow(pMem, n, 0);
   61354   if( pMem->z ){
   61355     pMem->n = n;
   61356     memset(pMem->z, 0, n);
   61357   }
   61358 #endif
   61359 }
   61360 
   61361 /*
   61362 ** Delete any previous value and set the value stored in *pMem to val,
   61363 ** manifest type INTEGER.
   61364 */
   61365 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
   61366   sqlite3VdbeMemRelease(pMem);
   61367   pMem->u.i = val;
   61368   pMem->flags = MEM_Int;
   61369 }
   61370 
   61371 #ifndef SQLITE_OMIT_FLOATING_POINT
   61372 /*
   61373 ** Delete any previous value and set the value stored in *pMem to val,
   61374 ** manifest type REAL.
   61375 */
   61376 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
   61377   if( sqlite3IsNaN(val) ){
   61378     sqlite3VdbeMemSetNull(pMem);
   61379   }else{
   61380     sqlite3VdbeMemRelease(pMem);
   61381     pMem->r = val;
   61382     pMem->flags = MEM_Real;
   61383   }
   61384 }
   61385 #endif
   61386 
   61387 /*
   61388 ** Delete any previous value and set the value of pMem to be an
   61389 ** empty boolean index.
   61390 */
   61391 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
   61392   sqlite3 *db = pMem->db;
   61393   assert( db!=0 );
   61394   assert( (pMem->flags & MEM_RowSet)==0 );
   61395   sqlite3VdbeMemRelease(pMem);
   61396   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
   61397   if( db->mallocFailed ){
   61398     pMem->flags = MEM_Null;
   61399   }else{
   61400     assert( pMem->zMalloc );
   61401     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
   61402                                        sqlite3DbMallocSize(db, pMem->zMalloc));
   61403     assert( pMem->u.pRowSet!=0 );
   61404     pMem->flags = MEM_RowSet;
   61405   }
   61406 }
   61407 
   61408 /*
   61409 ** Return true if the Mem object contains a TEXT or BLOB that is
   61410 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
   61411 */
   61412 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
   61413   assert( p->db!=0 );
   61414   if( p->flags & (MEM_Str|MEM_Blob) ){
   61415     int n = p->n;
   61416     if( p->flags & MEM_Zero ){
   61417       n += p->u.nZero;
   61418     }
   61419     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
   61420   }
   61421   return 0;
   61422 }
   61423 
   61424 #ifdef SQLITE_DEBUG
   61425 /*
   61426 ** This routine prepares a memory cell for modication by breaking
   61427 ** its link to a shallow copy and by marking any current shallow
   61428 ** copies of this cell as invalid.
   61429 **
   61430 ** This is used for testing and debugging only - to make sure shallow
   61431 ** copies are not misused.
   61432 */
   61433 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
   61434   int i;
   61435   Mem *pX;
   61436   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
   61437     if( pX->pScopyFrom==pMem ){
   61438       pX->flags |= MEM_Undefined;
   61439       pX->pScopyFrom = 0;
   61440     }
   61441   }
   61442   pMem->pScopyFrom = 0;
   61443 }
   61444 #endif /* SQLITE_DEBUG */
   61445 
   61446 /*
   61447 ** Size of struct Mem not including the Mem.zMalloc member.
   61448 */
   61449 #define MEMCELLSIZE offsetof(Mem,zMalloc)
   61450 
   61451 /*
   61452 ** Make an shallow copy of pFrom into pTo.  Prior contents of
   61453 ** pTo are freed.  The pFrom->z field is not duplicated.  If
   61454 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
   61455 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
   61456 */
   61457 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
   61458   assert( (pFrom->flags & MEM_RowSet)==0 );
   61459   VdbeMemRelease(pTo);
   61460   memcpy(pTo, pFrom, MEMCELLSIZE);
   61461   pTo->xDel = 0;
   61462   if( (pFrom->flags&MEM_Static)==0 ){
   61463     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
   61464     assert( srcType==MEM_Ephem || srcType==MEM_Static );
   61465     pTo->flags |= srcType;
   61466   }
   61467 }
   61468 
   61469 /*
   61470 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
   61471 ** freed before the copy is made.
   61472 */
   61473 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
   61474   int rc = SQLITE_OK;
   61475 
   61476   assert( (pFrom->flags & MEM_RowSet)==0 );
   61477   VdbeMemRelease(pTo);
   61478   memcpy(pTo, pFrom, MEMCELLSIZE);
   61479   pTo->flags &= ~MEM_Dyn;
   61480   pTo->xDel = 0;
   61481 
   61482   if( pTo->flags&(MEM_Str|MEM_Blob) ){
   61483     if( 0==(pFrom->flags&MEM_Static) ){
   61484       pTo->flags |= MEM_Ephem;
   61485       rc = sqlite3VdbeMemMakeWriteable(pTo);
   61486     }
   61487   }
   61488 
   61489   return rc;
   61490 }
   61491 
   61492 /*
   61493 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
   61494 ** freed. If pFrom contains ephemeral data, a copy is made.
   61495 **
   61496 ** pFrom contains an SQL NULL when this routine returns.
   61497 */
   61498 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
   61499   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
   61500   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
   61501   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
   61502 
   61503   sqlite3VdbeMemRelease(pTo);
   61504   memcpy(pTo, pFrom, sizeof(Mem));
   61505   pFrom->flags = MEM_Null;
   61506   pFrom->xDel = 0;
   61507   pFrom->zMalloc = 0;
   61508 }
   61509 
   61510 /*
   61511 ** Change the value of a Mem to be a string or a BLOB.
   61512 **
   61513 ** The memory management strategy depends on the value of the xDel
   61514 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
   61515 ** string is copied into a (possibly existing) buffer managed by the
   61516 ** Mem structure. Otherwise, any existing buffer is freed and the
   61517 ** pointer copied.
   61518 **
   61519 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
   61520 ** size limit) then no memory allocation occurs.  If the string can be
   61521 ** stored without allocating memory, then it is.  If a memory allocation
   61522 ** is required to store the string, then value of pMem is unchanged.  In
   61523 ** either case, SQLITE_TOOBIG is returned.
   61524 */
   61525 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   61526   Mem *pMem,          /* Memory cell to set to string value */
   61527   const char *z,      /* String pointer */
   61528   int n,              /* Bytes in string, or negative */
   61529   u8 enc,             /* Encoding of z.  0 for BLOBs */
   61530   void (*xDel)(void*) /* Destructor function */
   61531 ){
   61532   int nByte = n;      /* New value for pMem->n */
   61533   int iLimit;         /* Maximum allowed string or blob size */
   61534   u16 flags = 0;      /* New value for pMem->flags */
   61535 
   61536   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   61537   assert( (pMem->flags & MEM_RowSet)==0 );
   61538 
   61539   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
   61540   if( !z ){
   61541     sqlite3VdbeMemSetNull(pMem);
   61542     return SQLITE_OK;
   61543   }
   61544 
   61545   if( pMem->db ){
   61546     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
   61547   }else{
   61548     iLimit = SQLITE_MAX_LENGTH;
   61549   }
   61550   flags = (enc==0?MEM_Blob:MEM_Str);
   61551   if( nByte<0 ){
   61552     assert( enc!=0 );
   61553     if( enc==SQLITE_UTF8 ){
   61554       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
   61555     }else{
   61556       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
   61557     }
   61558     flags |= MEM_Term;
   61559   }
   61560 
   61561   /* The following block sets the new values of Mem.z and Mem.xDel. It
   61562   ** also sets a flag in local variable "flags" to indicate the memory
   61563   ** management (one of MEM_Dyn or MEM_Static).
   61564   */
   61565   if( xDel==SQLITE_TRANSIENT ){
   61566     int nAlloc = nByte;
   61567     if( flags&MEM_Term ){
   61568       nAlloc += (enc==SQLITE_UTF8?1:2);
   61569     }
   61570     if( nByte>iLimit ){
   61571       return SQLITE_TOOBIG;
   61572     }
   61573     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
   61574       return SQLITE_NOMEM;
   61575     }
   61576     memcpy(pMem->z, z, nAlloc);
   61577   }else if( xDel==SQLITE_DYNAMIC ){
   61578     sqlite3VdbeMemRelease(pMem);
   61579     pMem->zMalloc = pMem->z = (char *)z;
   61580     pMem->xDel = 0;
   61581   }else{
   61582     sqlite3VdbeMemRelease(pMem);
   61583     pMem->z = (char *)z;
   61584     pMem->xDel = xDel;
   61585     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
   61586   }
   61587 
   61588   pMem->n = nByte;
   61589   pMem->flags = flags;
   61590   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
   61591 
   61592 #ifndef SQLITE_OMIT_UTF16
   61593   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
   61594     return SQLITE_NOMEM;
   61595   }
   61596 #endif
   61597 
   61598   if( nByte>iLimit ){
   61599     return SQLITE_TOOBIG;
   61600   }
   61601 
   61602   return SQLITE_OK;
   61603 }
   61604 
   61605 /*
   61606 ** Move data out of a btree key or data field and into a Mem structure.
   61607 ** The data or key is taken from the entry that pCur is currently pointing
   61608 ** to.  offset and amt determine what portion of the data or key to retrieve.
   61609 ** key is true to get the key or false to get data.  The result is written
   61610 ** into the pMem element.
   61611 **
   61612 ** The pMem structure is assumed to be uninitialized.  Any prior content
   61613 ** is overwritten without being freed.
   61614 **
   61615 ** If this routine fails for any reason (malloc returns NULL or unable
   61616 ** to read from the disk) then the pMem is left in an inconsistent state.
   61617 */
   61618 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
   61619   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   61620   u32 offset,       /* Offset from the start of data to return bytes from. */
   61621   u32 amt,          /* Number of bytes to return. */
   61622   int key,          /* If true, retrieve from the btree key, not data. */
   61623   Mem *pMem         /* OUT: Return data in this Mem structure. */
   61624 ){
   61625   char *zData;        /* Data from the btree layer */
   61626   u32 available = 0;  /* Number of bytes available on the local btree page */
   61627   int rc = SQLITE_OK; /* Return code */
   61628 
   61629   assert( sqlite3BtreeCursorIsValid(pCur) );
   61630 
   61631   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
   61632   ** that both the BtShared and database handle mutexes are held. */
   61633   assert( (pMem->flags & MEM_RowSet)==0 );
   61634   if( key ){
   61635     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
   61636   }else{
   61637     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
   61638   }
   61639   assert( zData!=0 );
   61640 
   61641   if( offset+amt<=available ){
   61642     sqlite3VdbeMemRelease(pMem);
   61643     pMem->z = &zData[offset];
   61644     pMem->flags = MEM_Blob|MEM_Ephem;
   61645     pMem->n = (int)amt;
   61646   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
   61647     if( key ){
   61648       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
   61649     }else{
   61650       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
   61651     }
   61652     if( rc==SQLITE_OK ){
   61653       pMem->z[amt] = 0;
   61654       pMem->z[amt+1] = 0;
   61655       pMem->flags = MEM_Blob|MEM_Term;
   61656       pMem->n = (int)amt;
   61657     }else{
   61658       sqlite3VdbeMemRelease(pMem);
   61659     }
   61660   }
   61661 
   61662   return rc;
   61663 }
   61664 
   61665 /* This function is only available internally, it is not part of the
   61666 ** external API. It works in a similar way to sqlite3_value_text(),
   61667 ** except the data returned is in the encoding specified by the second
   61668 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
   61669 ** SQLITE_UTF8.
   61670 **
   61671 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
   61672 ** If that is the case, then the result must be aligned on an even byte
   61673 ** boundary.
   61674 */
   61675 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
   61676   if( !pVal ) return 0;
   61677 
   61678   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
   61679   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
   61680   assert( (pVal->flags & MEM_RowSet)==0 );
   61681 
   61682   if( pVal->flags&MEM_Null ){
   61683     return 0;
   61684   }
   61685   assert( (MEM_Blob>>3) == MEM_Str );
   61686   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
   61687   ExpandBlob(pVal);
   61688   if( pVal->flags&MEM_Str ){
   61689     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
   61690     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
   61691       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
   61692       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
   61693         return 0;
   61694       }
   61695     }
   61696     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
   61697   }else{
   61698     assert( (pVal->flags&MEM_Blob)==0 );
   61699     sqlite3VdbeMemStringify(pVal, enc);
   61700     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
   61701   }
   61702   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
   61703               || pVal->db->mallocFailed );
   61704   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
   61705     return pVal->z;
   61706   }else{
   61707     return 0;
   61708   }
   61709 }
   61710 
   61711 /*
   61712 ** Create a new sqlite3_value object.
   61713 */
   61714 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
   61715   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
   61716   if( p ){
   61717     p->flags = MEM_Null;
   61718     p->db = db;
   61719   }
   61720   return p;
   61721 }
   61722 
   61723 /*
   61724 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
   61725 ** valueNew(). See comments above valueNew() for details.
   61726 */
   61727 struct ValueNewStat4Ctx {
   61728   Parse *pParse;
   61729   Index *pIdx;
   61730   UnpackedRecord **ppRec;
   61731   int iVal;
   61732 };
   61733 
   61734 /*
   61735 ** Allocate and return a pointer to a new sqlite3_value object. If
   61736 ** the second argument to this function is NULL, the object is allocated
   61737 ** by calling sqlite3ValueNew().
   61738 **
   61739 ** Otherwise, if the second argument is non-zero, then this function is
   61740 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
   61741 ** already been allocated, allocate the UnpackedRecord structure that
   61742 ** that function will return to its caller here. Then return a pointer
   61743 ** an sqlite3_value within the UnpackedRecord.a[] array.
   61744 */
   61745 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
   61746 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   61747   if( p ){
   61748     UnpackedRecord *pRec = p->ppRec[0];
   61749 
   61750     if( pRec==0 ){
   61751       Index *pIdx = p->pIdx;      /* Index being probed */
   61752       int nByte;                  /* Bytes of space to allocate */
   61753       int i;                      /* Counter variable */
   61754       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
   61755 
   61756       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
   61757       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
   61758       if( pRec ){
   61759         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
   61760         if( pRec->pKeyInfo ){
   61761           assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
   61762           assert( pRec->pKeyInfo->enc==ENC(db) );
   61763           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
   61764           for(i=0; i<nCol; i++){
   61765             pRec->aMem[i].flags = MEM_Null;
   61766             pRec->aMem[i].db = db;
   61767           }
   61768         }else{
   61769           sqlite3DbFree(db, pRec);
   61770           pRec = 0;
   61771         }
   61772       }
   61773       if( pRec==0 ) return 0;
   61774       p->ppRec[0] = pRec;
   61775     }
   61776 
   61777     pRec->nField = p->iVal+1;
   61778     return &pRec->aMem[p->iVal];
   61779   }
   61780 #else
   61781   UNUSED_PARAMETER(p);
   61782 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
   61783   return sqlite3ValueNew(db);
   61784 }
   61785 
   61786 /*
   61787 ** Extract a value from the supplied expression in the manner described
   61788 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
   61789 ** using valueNew().
   61790 **
   61791 ** If pCtx is NULL and an error occurs after the sqlite3_value object
   61792 ** has been allocated, it is freed before returning. Or, if pCtx is not
   61793 ** NULL, it is assumed that the caller will free any allocated object
   61794 ** in all cases.
   61795 */
   61796 static int valueFromExpr(
   61797   sqlite3 *db,                    /* The database connection */
   61798   Expr *pExpr,                    /* The expression to evaluate */
   61799   u8 enc,                         /* Encoding to use */
   61800   u8 affinity,                    /* Affinity to use */
   61801   sqlite3_value **ppVal,          /* Write the new value here */
   61802   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
   61803 ){
   61804   int op;
   61805   char *zVal = 0;
   61806   sqlite3_value *pVal = 0;
   61807   int negInt = 1;
   61808   const char *zNeg = "";
   61809   int rc = SQLITE_OK;
   61810 
   61811   if( !pExpr ){
   61812     *ppVal = 0;
   61813     return SQLITE_OK;
   61814   }
   61815   op = pExpr->op;
   61816   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
   61817 
   61818   /* Handle negative integers in a single step.  This is needed in the
   61819   ** case when the value is -9223372036854775808.
   61820   */
   61821   if( op==TK_UMINUS
   61822    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
   61823     pExpr = pExpr->pLeft;
   61824     op = pExpr->op;
   61825     negInt = -1;
   61826     zNeg = "-";
   61827   }
   61828 
   61829   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
   61830     pVal = valueNew(db, pCtx);
   61831     if( pVal==0 ) goto no_mem;
   61832     if( ExprHasProperty(pExpr, EP_IntValue) ){
   61833       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
   61834     }else{
   61835       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
   61836       if( zVal==0 ) goto no_mem;
   61837       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
   61838     }
   61839     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
   61840       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
   61841     }else{
   61842       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
   61843     }
   61844     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
   61845     if( enc!=SQLITE_UTF8 ){
   61846       rc = sqlite3VdbeChangeEncoding(pVal, enc);
   61847     }
   61848   }else if( op==TK_UMINUS ) {
   61849     /* This branch happens for multiple negative signs.  Ex: -(-5) */
   61850     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
   61851      && pVal!=0
   61852     ){
   61853       sqlite3VdbeMemNumerify(pVal);
   61854       if( pVal->u.i==SMALLEST_INT64 ){
   61855         pVal->flags &= ~MEM_Int;
   61856         pVal->flags |= MEM_Real;
   61857         pVal->r = (double)SMALLEST_INT64;
   61858       }else{
   61859         pVal->u.i = -pVal->u.i;
   61860       }
   61861       pVal->r = -pVal->r;
   61862       sqlite3ValueApplyAffinity(pVal, affinity, enc);
   61863     }
   61864   }else if( op==TK_NULL ){
   61865     pVal = valueNew(db, pCtx);
   61866     if( pVal==0 ) goto no_mem;
   61867   }
   61868 #ifndef SQLITE_OMIT_BLOB_LITERAL
   61869   else if( op==TK_BLOB ){
   61870     int nVal;
   61871     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   61872     assert( pExpr->u.zToken[1]=='\'' );
   61873     pVal = valueNew(db, pCtx);
   61874     if( !pVal ) goto no_mem;
   61875     zVal = &pExpr->u.zToken[2];
   61876     nVal = sqlite3Strlen30(zVal)-1;
   61877     assert( zVal[nVal]=='\'' );
   61878     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
   61879                          0, SQLITE_DYNAMIC);
   61880   }
   61881 #endif
   61882 
   61883   *ppVal = pVal;
   61884   return rc;
   61885 
   61886 no_mem:
   61887   db->mallocFailed = 1;
   61888   sqlite3DbFree(db, zVal);
   61889   assert( *ppVal==0 );
   61890 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   61891   if( pCtx==0 ) sqlite3ValueFree(pVal);
   61892 #else
   61893   assert( pCtx==0 ); sqlite3ValueFree(pVal);
   61894 #endif
   61895   return SQLITE_NOMEM;
   61896 }
   61897 
   61898 /*
   61899 ** Create a new sqlite3_value object, containing the value of pExpr.
   61900 **
   61901 ** This only works for very simple expressions that consist of one constant
   61902 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
   61903 ** be converted directly into a value, then the value is allocated and
   61904 ** a pointer written to *ppVal. The caller is responsible for deallocating
   61905 ** the value by passing it to sqlite3ValueFree() later on. If the expression
   61906 ** cannot be converted to a value, then *ppVal is set to NULL.
   61907 */
   61908 SQLITE_PRIVATE int sqlite3ValueFromExpr(
   61909   sqlite3 *db,              /* The database connection */
   61910   Expr *pExpr,              /* The expression to evaluate */
   61911   u8 enc,                   /* Encoding to use */
   61912   u8 affinity,              /* Affinity to use */
   61913   sqlite3_value **ppVal     /* Write the new value here */
   61914 ){
   61915   return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
   61916 }
   61917 
   61918 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   61919 /*
   61920 ** The implementation of the sqlite_record() function. This function accepts
   61921 ** a single argument of any type. The return value is a formatted database
   61922 ** record (a blob) containing the argument value.
   61923 **
   61924 ** This is used to convert the value stored in the 'sample' column of the
   61925 ** sqlite_stat3 table to the record format SQLite uses internally.
   61926 */
   61927 static void recordFunc(
   61928   sqlite3_context *context,
   61929   int argc,
   61930   sqlite3_value **argv
   61931 ){
   61932   const int file_format = 1;
   61933   int iSerial;                    /* Serial type */
   61934   int nSerial;                    /* Bytes of space for iSerial as varint */
   61935   int nVal;                       /* Bytes of space required for argv[0] */
   61936   int nRet;
   61937   sqlite3 *db;
   61938   u8 *aRet;
   61939 
   61940   UNUSED_PARAMETER( argc );
   61941   iSerial = sqlite3VdbeSerialType(argv[0], file_format);
   61942   nSerial = sqlite3VarintLen(iSerial);
   61943   nVal = sqlite3VdbeSerialTypeLen(iSerial);
   61944   db = sqlite3_context_db_handle(context);
   61945 
   61946   nRet = 1 + nSerial + nVal;
   61947   aRet = sqlite3DbMallocRaw(db, nRet);
   61948   if( aRet==0 ){
   61949     sqlite3_result_error_nomem(context);
   61950   }else{
   61951     aRet[0] = nSerial+1;
   61952     sqlite3PutVarint(&aRet[1], iSerial);
   61953     sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
   61954     sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
   61955     sqlite3DbFree(db, aRet);
   61956   }
   61957 }
   61958 
   61959 /*
   61960 ** Register built-in functions used to help read ANALYZE data.
   61961 */
   61962 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
   61963   static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
   61964     FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
   61965   };
   61966   int i;
   61967   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   61968   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
   61969   for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
   61970     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   61971   }
   61972 }
   61973 
   61974 /*
   61975 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
   61976 **
   61977 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
   61978 ** pAlloc if one does not exist and the new value is added to the
   61979 ** UnpackedRecord object.
   61980 **
   61981 ** A value is extracted in the following cases:
   61982 **
   61983 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
   61984 **
   61985 **  * The expression is a bound variable, and this is a reprepare, or
   61986 **
   61987 **  * The expression is a literal value.
   61988 **
   61989 ** On success, *ppVal is made to point to the extracted value.  The caller
   61990 ** is responsible for ensuring that the value is eventually freed.
   61991 */
   61992 static int stat4ValueFromExpr(
   61993   Parse *pParse,                  /* Parse context */
   61994   Expr *pExpr,                    /* The expression to extract a value from */
   61995   u8 affinity,                    /* Affinity to use */
   61996   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
   61997   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
   61998 ){
   61999   int rc = SQLITE_OK;
   62000   sqlite3_value *pVal = 0;
   62001   sqlite3 *db = pParse->db;
   62002 
   62003   /* Skip over any TK_COLLATE nodes */
   62004   pExpr = sqlite3ExprSkipCollate(pExpr);
   62005 
   62006   if( !pExpr ){
   62007     pVal = valueNew(db, pAlloc);
   62008     if( pVal ){
   62009       sqlite3VdbeMemSetNull((Mem*)pVal);
   62010     }
   62011   }else if( pExpr->op==TK_VARIABLE
   62012         || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
   62013   ){
   62014     Vdbe *v;
   62015     int iBindVar = pExpr->iColumn;
   62016     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
   62017     if( (v = pParse->pReprepare)!=0 ){
   62018       pVal = valueNew(db, pAlloc);
   62019       if( pVal ){
   62020         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
   62021         if( rc==SQLITE_OK ){
   62022           sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
   62023         }
   62024         pVal->db = pParse->db;
   62025       }
   62026     }
   62027   }else{
   62028     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
   62029   }
   62030 
   62031   assert( pVal==0 || pVal->db==db );
   62032   *ppVal = pVal;
   62033   return rc;
   62034 }
   62035 
   62036 /*
   62037 ** This function is used to allocate and populate UnpackedRecord
   62038 ** structures intended to be compared against sample index keys stored
   62039 ** in the sqlite_stat4 table.
   62040 **
   62041 ** A single call to this function attempts to populates field iVal (leftmost
   62042 ** is 0 etc.) of the unpacked record with a value extracted from expression
   62043 ** pExpr. Extraction of values is possible if:
   62044 **
   62045 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
   62046 **
   62047 **  * The expression is a bound variable, and this is a reprepare, or
   62048 **
   62049 **  * The sqlite3ValueFromExpr() function is able to extract a value
   62050 **    from the expression (i.e. the expression is a literal value).
   62051 **
   62052 ** If a value can be extracted, the affinity passed as the 5th argument
   62053 ** is applied to it before it is copied into the UnpackedRecord. Output
   62054 ** parameter *pbOk is set to true if a value is extracted, or false
   62055 ** otherwise.
   62056 **
   62057 ** When this function is called, *ppRec must either point to an object
   62058 ** allocated by an earlier call to this function, or must be NULL. If it
   62059 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
   62060 ** is allocated (and *ppRec set to point to it) before returning.
   62061 **
   62062 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
   62063 ** error if a value cannot be extracted from pExpr. If an error does
   62064 ** occur, an SQLite error code is returned.
   62065 */
   62066 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
   62067   Parse *pParse,                  /* Parse context */
   62068   Index *pIdx,                    /* Index being probed */
   62069   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
   62070   Expr *pExpr,                    /* The expression to extract a value from */
   62071   u8 affinity,                    /* Affinity to use */
   62072   int iVal,                       /* Array element to populate */
   62073   int *pbOk                       /* OUT: True if value was extracted */
   62074 ){
   62075   int rc;
   62076   sqlite3_value *pVal = 0;
   62077   struct ValueNewStat4Ctx alloc;
   62078 
   62079   alloc.pParse = pParse;
   62080   alloc.pIdx = pIdx;
   62081   alloc.ppRec = ppRec;
   62082   alloc.iVal = iVal;
   62083 
   62084   rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
   62085   assert( pVal==0 || pVal->db==pParse->db );
   62086   *pbOk = (pVal!=0);
   62087   return rc;
   62088 }
   62089 
   62090 /*
   62091 ** Attempt to extract a value from expression pExpr using the methods
   62092 ** as described for sqlite3Stat4ProbeSetValue() above.
   62093 **
   62094 ** If successful, set *ppVal to point to a new value object and return
   62095 ** SQLITE_OK. If no value can be extracted, but no other error occurs
   62096 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
   62097 ** does occur, return an SQLite error code. The final value of *ppVal
   62098 ** is undefined in this case.
   62099 */
   62100 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
   62101   Parse *pParse,                  /* Parse context */
   62102   Expr *pExpr,                    /* The expression to extract a value from */
   62103   u8 affinity,                    /* Affinity to use */
   62104   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
   62105 ){
   62106   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
   62107 }
   62108 
   62109 /*
   62110 ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
   62111 ** the column value into *ppVal.  If *ppVal is initially NULL then a new
   62112 ** sqlite3_value object is allocated.
   62113 **
   62114 ** If *ppVal is initially NULL then the caller is responsible for
   62115 ** ensuring that the value written into *ppVal is eventually freed.
   62116 */
   62117 SQLITE_PRIVATE int sqlite3Stat4Column(
   62118   sqlite3 *db,                    /* Database handle */
   62119   const void *pRec,               /* Pointer to buffer containing record */
   62120   int nRec,                       /* Size of buffer pRec in bytes */
   62121   int iCol,                       /* Column to extract */
   62122   sqlite3_value **ppVal           /* OUT: Extracted value */
   62123 ){
   62124   u32 t;                          /* a column type code */
   62125   int nHdr;                       /* Size of the header in the record */
   62126   int iHdr;                       /* Next unread header byte */
   62127   int iField;                     /* Next unread data byte */
   62128   int szField;                    /* Size of the current data field */
   62129   int i;                          /* Column index */
   62130   u8 *a = (u8*)pRec;              /* Typecast byte array */
   62131   Mem *pMem = *ppVal;             /* Write result into this Mem object */
   62132 
   62133   assert( iCol>0 );
   62134   iHdr = getVarint32(a, nHdr);
   62135   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
   62136   iField = nHdr;
   62137   for(i=0; i<=iCol; i++){
   62138     iHdr += getVarint32(&a[iHdr], t);
   62139     testcase( iHdr==nHdr );
   62140     testcase( iHdr==nHdr+1 );
   62141     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
   62142     szField = sqlite3VdbeSerialTypeLen(t);
   62143     iField += szField;
   62144   }
   62145   testcase( iField==nRec );
   62146   testcase( iField==nRec+1 );
   62147   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
   62148   if( pMem==0 ){
   62149     pMem = *ppVal = sqlite3ValueNew(db);
   62150     if( pMem==0 ) return SQLITE_NOMEM;
   62151   }
   62152   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
   62153   pMem->enc = ENC(db);
   62154   return SQLITE_OK;
   62155 }
   62156 
   62157 /*
   62158 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
   62159 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
   62160 ** the object.
   62161 */
   62162 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
   62163   if( pRec ){
   62164     int i;
   62165     int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
   62166     Mem *aMem = pRec->aMem;
   62167     sqlite3 *db = aMem[0].db;
   62168     for(i=0; i<nCol; i++){
   62169       sqlite3DbFree(db, aMem[i].zMalloc);
   62170     }
   62171     sqlite3KeyInfoUnref(pRec->pKeyInfo);
   62172     sqlite3DbFree(db, pRec);
   62173   }
   62174 }
   62175 #endif /* ifdef SQLITE_ENABLE_STAT4 */
   62176 
   62177 /*
   62178 ** Change the string value of an sqlite3_value object
   62179 */
   62180 SQLITE_PRIVATE void sqlite3ValueSetStr(
   62181   sqlite3_value *v,     /* Value to be set */
   62182   int n,                /* Length of string z */
   62183   const void *z,        /* Text of the new string */
   62184   u8 enc,               /* Encoding to use */
   62185   void (*xDel)(void*)   /* Destructor for the string */
   62186 ){
   62187   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
   62188 }
   62189 
   62190 /*
   62191 ** Free an sqlite3_value object
   62192 */
   62193 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
   62194   if( !v ) return;
   62195   sqlite3VdbeMemRelease((Mem *)v);
   62196   sqlite3DbFree(((Mem*)v)->db, v);
   62197 }
   62198 
   62199 /*
   62200 ** Return the number of bytes in the sqlite3_value object assuming
   62201 ** that it uses the encoding "enc"
   62202 */
   62203 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
   62204   Mem *p = (Mem*)pVal;
   62205   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
   62206     if( p->flags & MEM_Zero ){
   62207       return p->n + p->u.nZero;
   62208     }else{
   62209       return p->n;
   62210     }
   62211   }
   62212   return 0;
   62213 }
   62214 
   62215 /************** End of vdbemem.c *********************************************/
   62216 /************** Begin file vdbeaux.c *****************************************/
   62217 /*
   62218 ** 2003 September 6
   62219 **
   62220 ** The author disclaims copyright to this source code.  In place of
   62221 ** a legal notice, here is a blessing:
   62222 **
   62223 **    May you do good and not evil.
   62224 **    May you find forgiveness for yourself and forgive others.
   62225 **    May you share freely, never taking more than you give.
   62226 **
   62227 *************************************************************************
   62228 ** This file contains code used for creating, destroying, and populating
   62229 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
   62230 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
   62231 ** But that file was getting too big so this subroutines were split out.
   62232 */
   62233 
   62234 /*
   62235 ** Create a new virtual database engine.
   62236 */
   62237 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
   62238   sqlite3 *db = pParse->db;
   62239   Vdbe *p;
   62240   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
   62241   if( p==0 ) return 0;
   62242   p->db = db;
   62243   if( db->pVdbe ){
   62244     db->pVdbe->pPrev = p;
   62245   }
   62246   p->pNext = db->pVdbe;
   62247   p->pPrev = 0;
   62248   db->pVdbe = p;
   62249   p->magic = VDBE_MAGIC_INIT;
   62250   p->pParse = pParse;
   62251   assert( pParse->aLabel==0 );
   62252   assert( pParse->nLabel==0 );
   62253   assert( pParse->nOpAlloc==0 );
   62254   return p;
   62255 }
   62256 
   62257 /*
   62258 ** Remember the SQL string for a prepared statement.
   62259 */
   62260 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
   62261   assert( isPrepareV2==1 || isPrepareV2==0 );
   62262   if( p==0 ) return;
   62263 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
   62264   if( !isPrepareV2 ) return;
   62265 #endif
   62266   assert( p->zSql==0 );
   62267   p->zSql = sqlite3DbStrNDup(p->db, z, n);
   62268   p->isPrepareV2 = (u8)isPrepareV2;
   62269 }
   62270 
   62271 /*
   62272 ** Return the SQL associated with a prepared statement
   62273 */
   62274 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
   62275   Vdbe *p = (Vdbe *)pStmt;
   62276   return (p && p->isPrepareV2) ? p->zSql : 0;
   62277 }
   62278 
   62279 /*
   62280 ** Swap all content between two VDBE structures.
   62281 */
   62282 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
   62283   Vdbe tmp, *pTmp;
   62284   char *zTmp;
   62285   tmp = *pA;
   62286   *pA = *pB;
   62287   *pB = tmp;
   62288   pTmp = pA->pNext;
   62289   pA->pNext = pB->pNext;
   62290   pB->pNext = pTmp;
   62291   pTmp = pA->pPrev;
   62292   pA->pPrev = pB->pPrev;
   62293   pB->pPrev = pTmp;
   62294   zTmp = pA->zSql;
   62295   pA->zSql = pB->zSql;
   62296   pB->zSql = zTmp;
   62297   pB->isPrepareV2 = pA->isPrepareV2;
   62298 }
   62299 
   62300 /*
   62301 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
   62302 ** than its current size. nOp is guaranteed to be less than or equal
   62303 ** to 1024/sizeof(Op).
   62304 **
   62305 ** If an out-of-memory error occurs while resizing the array, return
   62306 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
   62307 ** unchanged (this is so that any opcodes already allocated can be
   62308 ** correctly deallocated along with the rest of the Vdbe).
   62309 */
   62310 static int growOpArray(Vdbe *v, int nOp){
   62311   VdbeOp *pNew;
   62312   Parse *p = v->pParse;
   62313 
   62314   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
   62315   ** more frequent reallocs and hence provide more opportunities for
   62316   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
   62317   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
   62318   ** by the minimum* amount required until the size reaches 512.  Normal
   62319   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
   62320   ** size of the op array or add 1KB of space, whichever is smaller. */
   62321 #ifdef SQLITE_TEST_REALLOC_STRESS
   62322   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
   62323 #else
   62324   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
   62325   UNUSED_PARAMETER(nOp);
   62326 #endif
   62327 
   62328   assert( nOp<=(1024/sizeof(Op)) );
   62329   assert( nNew>=(p->nOpAlloc+nOp) );
   62330   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
   62331   if( pNew ){
   62332     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
   62333     v->aOp = pNew;
   62334   }
   62335   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
   62336 }
   62337 
   62338 #ifdef SQLITE_DEBUG
   62339 /* This routine is just a convenient place to set a breakpoint that will
   62340 ** fire after each opcode is inserted and displayed using
   62341 ** "PRAGMA vdbe_addoptrace=on".
   62342 */
   62343 static void test_addop_breakpoint(void){
   62344   static int n = 0;
   62345   n++;
   62346 }
   62347 #endif
   62348 
   62349 /*
   62350 ** Add a new instruction to the list of instructions current in the
   62351 ** VDBE.  Return the address of the new instruction.
   62352 **
   62353 ** Parameters:
   62354 **
   62355 **    p               Pointer to the VDBE
   62356 **
   62357 **    op              The opcode for this instruction
   62358 **
   62359 **    p1, p2, p3      Operands
   62360 **
   62361 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
   62362 ** the sqlite3VdbeChangeP4() function to change the value of the P4
   62363 ** operand.
   62364 */
   62365 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
   62366   int i;
   62367   VdbeOp *pOp;
   62368 
   62369   i = p->nOp;
   62370   assert( p->magic==VDBE_MAGIC_INIT );
   62371   assert( op>0 && op<0xff );
   62372   if( p->pParse->nOpAlloc<=i ){
   62373     if( growOpArray(p, 1) ){
   62374       return 1;
   62375     }
   62376   }
   62377   p->nOp++;
   62378   pOp = &p->aOp[i];
   62379   pOp->opcode = (u8)op;
   62380   pOp->p5 = 0;
   62381   pOp->p1 = p1;
   62382   pOp->p2 = p2;
   62383   pOp->p3 = p3;
   62384   pOp->p4.p = 0;
   62385   pOp->p4type = P4_NOTUSED;
   62386 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   62387   pOp->zComment = 0;
   62388 #endif
   62389 #ifdef SQLITE_DEBUG
   62390   if( p->db->flags & SQLITE_VdbeAddopTrace ){
   62391     int jj, kk;
   62392     Parse *pParse = p->pParse;
   62393     for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
   62394       struct yColCache *x = pParse->aColCache + jj;
   62395       if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
   62396       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
   62397       kk++;
   62398     }
   62399     if( kk ) printf("\n");
   62400     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
   62401     test_addop_breakpoint();
   62402   }
   62403 #endif
   62404 #ifdef VDBE_PROFILE
   62405   pOp->cycles = 0;
   62406   pOp->cnt = 0;
   62407 #endif
   62408 #ifdef SQLITE_VDBE_COVERAGE
   62409   pOp->iSrcLine = 0;
   62410 #endif
   62411   return i;
   62412 }
   62413 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
   62414   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
   62415 }
   62416 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
   62417   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
   62418 }
   62419 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
   62420   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
   62421 }
   62422 
   62423 
   62424 /*
   62425 ** Add an opcode that includes the p4 value as a pointer.
   62426 */
   62427 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
   62428   Vdbe *p,            /* Add the opcode to this VM */
   62429   int op,             /* The new opcode */
   62430   int p1,             /* The P1 operand */
   62431   int p2,             /* The P2 operand */
   62432   int p3,             /* The P3 operand */
   62433   const char *zP4,    /* The P4 operand */
   62434   int p4type          /* P4 operand type */
   62435 ){
   62436   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   62437   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
   62438   return addr;
   62439 }
   62440 
   62441 /*
   62442 ** Add an OP_ParseSchema opcode.  This routine is broken out from
   62443 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
   62444 ** as having been used.
   62445 **
   62446 ** The zWhere string must have been obtained from sqlite3_malloc().
   62447 ** This routine will take ownership of the allocated memory.
   62448 */
   62449 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
   62450   int j;
   62451   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
   62452   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
   62453   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
   62454 }
   62455 
   62456 /*
   62457 ** Add an opcode that includes the p4 value as an integer.
   62458 */
   62459 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
   62460   Vdbe *p,            /* Add the opcode to this VM */
   62461   int op,             /* The new opcode */
   62462   int p1,             /* The P1 operand */
   62463   int p2,             /* The P2 operand */
   62464   int p3,             /* The P3 operand */
   62465   int p4              /* The P4 operand as an integer */
   62466 ){
   62467   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   62468   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
   62469   return addr;
   62470 }
   62471 
   62472 /*
   62473 ** Create a new symbolic label for an instruction that has yet to be
   62474 ** coded.  The symbolic label is really just a negative number.  The
   62475 ** label can be used as the P2 value of an operation.  Later, when
   62476 ** the label is resolved to a specific address, the VDBE will scan
   62477 ** through its operation list and change all values of P2 which match
   62478 ** the label into the resolved address.
   62479 **
   62480 ** The VDBE knows that a P2 value is a label because labels are
   62481 ** always negative and P2 values are suppose to be non-negative.
   62482 ** Hence, a negative P2 value is a label that has yet to be resolved.
   62483 **
   62484 ** Zero is returned if a malloc() fails.
   62485 */
   62486 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
   62487   Parse *p = v->pParse;
   62488   int i = p->nLabel++;
   62489   assert( v->magic==VDBE_MAGIC_INIT );
   62490   if( (i & (i-1))==0 ){
   62491     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
   62492                                        (i*2+1)*sizeof(p->aLabel[0]));
   62493   }
   62494   if( p->aLabel ){
   62495     p->aLabel[i] = -1;
   62496   }
   62497   return -1-i;
   62498 }
   62499 
   62500 /*
   62501 ** Resolve label "x" to be the address of the next instruction to
   62502 ** be inserted.  The parameter "x" must have been obtained from
   62503 ** a prior call to sqlite3VdbeMakeLabel().
   62504 */
   62505 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
   62506   Parse *p = v->pParse;
   62507   int j = -1-x;
   62508   assert( v->magic==VDBE_MAGIC_INIT );
   62509   assert( j<p->nLabel );
   62510   if( ALWAYS(j>=0) && p->aLabel ){
   62511     p->aLabel[j] = v->nOp;
   62512   }
   62513   p->iFixedOp = v->nOp - 1;
   62514 }
   62515 
   62516 /*
   62517 ** Mark the VDBE as one that can only be run one time.
   62518 */
   62519 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
   62520   p->runOnlyOnce = 1;
   62521 }
   62522 
   62523 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
   62524 
   62525 /*
   62526 ** The following type and function are used to iterate through all opcodes
   62527 ** in a Vdbe main program and each of the sub-programs (triggers) it may
   62528 ** invoke directly or indirectly. It should be used as follows:
   62529 **
   62530 **   Op *pOp;
   62531 **   VdbeOpIter sIter;
   62532 **
   62533 **   memset(&sIter, 0, sizeof(sIter));
   62534 **   sIter.v = v;                            // v is of type Vdbe*
   62535 **   while( (pOp = opIterNext(&sIter)) ){
   62536 **     // Do something with pOp
   62537 **   }
   62538 **   sqlite3DbFree(v->db, sIter.apSub);
   62539 **
   62540 */
   62541 typedef struct VdbeOpIter VdbeOpIter;
   62542 struct VdbeOpIter {
   62543   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
   62544   SubProgram **apSub;        /* Array of subprograms */
   62545   int nSub;                  /* Number of entries in apSub */
   62546   int iAddr;                 /* Address of next instruction to return */
   62547   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
   62548 };
   62549 static Op *opIterNext(VdbeOpIter *p){
   62550   Vdbe *v = p->v;
   62551   Op *pRet = 0;
   62552   Op *aOp;
   62553   int nOp;
   62554 
   62555   if( p->iSub<=p->nSub ){
   62556 
   62557     if( p->iSub==0 ){
   62558       aOp = v->aOp;
   62559       nOp = v->nOp;
   62560     }else{
   62561       aOp = p->apSub[p->iSub-1]->aOp;
   62562       nOp = p->apSub[p->iSub-1]->nOp;
   62563     }
   62564     assert( p->iAddr<nOp );
   62565 
   62566     pRet = &aOp[p->iAddr];
   62567     p->iAddr++;
   62568     if( p->iAddr==nOp ){
   62569       p->iSub++;
   62570       p->iAddr = 0;
   62571     }
   62572 
   62573     if( pRet->p4type==P4_SUBPROGRAM ){
   62574       int nByte = (p->nSub+1)*sizeof(SubProgram*);
   62575       int j;
   62576       for(j=0; j<p->nSub; j++){
   62577         if( p->apSub[j]==pRet->p4.pProgram ) break;
   62578       }
   62579       if( j==p->nSub ){
   62580         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
   62581         if( !p->apSub ){
   62582           pRet = 0;
   62583         }else{
   62584           p->apSub[p->nSub++] = pRet->p4.pProgram;
   62585         }
   62586       }
   62587     }
   62588   }
   62589 
   62590   return pRet;
   62591 }
   62592 
   62593 /*
   62594 ** Check if the program stored in the VM associated with pParse may
   62595 ** throw an ABORT exception (causing the statement, but not entire transaction
   62596 ** to be rolled back). This condition is true if the main program or any
   62597 ** sub-programs contains any of the following:
   62598 **
   62599 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   62600 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   62601 **   *  OP_Destroy
   62602 **   *  OP_VUpdate
   62603 **   *  OP_VRename
   62604 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
   62605 **
   62606 ** Then check that the value of Parse.mayAbort is true if an
   62607 ** ABORT may be thrown, or false otherwise. Return true if it does
   62608 ** match, or false otherwise. This function is intended to be used as
   62609 ** part of an assert statement in the compiler. Similar to:
   62610 **
   62611 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
   62612 */
   62613 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
   62614   int hasAbort = 0;
   62615   Op *pOp;
   62616   VdbeOpIter sIter;
   62617   memset(&sIter, 0, sizeof(sIter));
   62618   sIter.v = v;
   62619 
   62620   while( (pOp = opIterNext(&sIter))!=0 ){
   62621     int opcode = pOp->opcode;
   62622     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
   62623 #ifndef SQLITE_OMIT_FOREIGN_KEY
   62624      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
   62625 #endif
   62626      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
   62627       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
   62628     ){
   62629       hasAbort = 1;
   62630       break;
   62631     }
   62632   }
   62633   sqlite3DbFree(v->db, sIter.apSub);
   62634 
   62635   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
   62636   ** If malloc failed, then the while() loop above may not have iterated
   62637   ** through all opcodes and hasAbort may be set incorrectly. Return
   62638   ** true for this case to prevent the assert() in the callers frame
   62639   ** from failing.  */
   62640   return ( v->db->mallocFailed || hasAbort==mayAbort );
   62641 }
   62642 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
   62643 
   62644 /*
   62645 ** Loop through the program looking for P2 values that are negative
   62646 ** on jump instructions.  Each such value is a label.  Resolve the
   62647 ** label by setting the P2 value to its correct non-zero value.
   62648 **
   62649 ** This routine is called once after all opcodes have been inserted.
   62650 **
   62651 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
   62652 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
   62653 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
   62654 **
   62655 ** The Op.opflags field is set on all opcodes.
   62656 */
   62657 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
   62658   int i;
   62659   int nMaxArgs = *pMaxFuncArgs;
   62660   Op *pOp;
   62661   Parse *pParse = p->pParse;
   62662   int *aLabel = pParse->aLabel;
   62663   p->readOnly = 1;
   62664   p->bIsReader = 0;
   62665   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   62666     u8 opcode = pOp->opcode;
   62667 
   62668     /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
   62669     ** cases from this switch! */
   62670     switch( opcode ){
   62671       case OP_Function:
   62672       case OP_AggStep: {
   62673         if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
   62674         break;
   62675       }
   62676       case OP_Transaction: {
   62677         if( pOp->p2!=0 ) p->readOnly = 0;
   62678         /* fall thru */
   62679       }
   62680       case OP_AutoCommit:
   62681       case OP_Savepoint: {
   62682         p->bIsReader = 1;
   62683         break;
   62684       }
   62685 #ifndef SQLITE_OMIT_WAL
   62686       case OP_Checkpoint:
   62687 #endif
   62688       case OP_Vacuum:
   62689       case OP_JournalMode: {
   62690         p->readOnly = 0;
   62691         p->bIsReader = 1;
   62692         break;
   62693       }
   62694 #ifndef SQLITE_OMIT_VIRTUALTABLE
   62695       case OP_VUpdate: {
   62696         if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   62697         break;
   62698       }
   62699       case OP_VFilter: {
   62700         int n;
   62701         assert( p->nOp - i >= 3 );
   62702         assert( pOp[-1].opcode==OP_Integer );
   62703         n = pOp[-1].p1;
   62704         if( n>nMaxArgs ) nMaxArgs = n;
   62705         break;
   62706       }
   62707 #endif
   62708       case OP_Next:
   62709       case OP_NextIfOpen:
   62710       case OP_SorterNext: {
   62711         pOp->p4.xAdvance = sqlite3BtreeNext;
   62712         pOp->p4type = P4_ADVANCE;
   62713         break;
   62714       }
   62715       case OP_Prev:
   62716       case OP_PrevIfOpen: {
   62717         pOp->p4.xAdvance = sqlite3BtreePrevious;
   62718         pOp->p4type = P4_ADVANCE;
   62719         break;
   62720       }
   62721     }
   62722 
   62723     pOp->opflags = sqlite3OpcodeProperty[opcode];
   62724     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
   62725       assert( -1-pOp->p2<pParse->nLabel );
   62726       pOp->p2 = aLabel[-1-pOp->p2];
   62727     }
   62728   }
   62729   sqlite3DbFree(p->db, pParse->aLabel);
   62730   pParse->aLabel = 0;
   62731   pParse->nLabel = 0;
   62732   *pMaxFuncArgs = nMaxArgs;
   62733   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
   62734 }
   62735 
   62736 /*
   62737 ** Return the address of the next instruction to be inserted.
   62738 */
   62739 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
   62740   assert( p->magic==VDBE_MAGIC_INIT );
   62741   return p->nOp;
   62742 }
   62743 
   62744 /*
   62745 ** This function returns a pointer to the array of opcodes associated with
   62746 ** the Vdbe passed as the first argument. It is the callers responsibility
   62747 ** to arrange for the returned array to be eventually freed using the
   62748 ** vdbeFreeOpArray() function.
   62749 **
   62750 ** Before returning, *pnOp is set to the number of entries in the returned
   62751 ** array. Also, *pnMaxArg is set to the larger of its current value and
   62752 ** the number of entries in the Vdbe.apArg[] array required to execute the
   62753 ** returned program.
   62754 */
   62755 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
   62756   VdbeOp *aOp = p->aOp;
   62757   assert( aOp && !p->db->mallocFailed );
   62758 
   62759   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
   62760   assert( DbMaskAllZero(p->btreeMask) );
   62761 
   62762   resolveP2Values(p, pnMaxArg);
   62763   *pnOp = p->nOp;
   62764   p->aOp = 0;
   62765   return aOp;
   62766 }
   62767 
   62768 /*
   62769 ** Add a whole list of operations to the operation stack.  Return the
   62770 ** address of the first operation added.
   62771 */
   62772 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
   62773   int addr;
   62774   assert( p->magic==VDBE_MAGIC_INIT );
   62775   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
   62776     return 0;
   62777   }
   62778   addr = p->nOp;
   62779   if( ALWAYS(nOp>0) ){
   62780     int i;
   62781     VdbeOpList const *pIn = aOp;
   62782     for(i=0; i<nOp; i++, pIn++){
   62783       int p2 = pIn->p2;
   62784       VdbeOp *pOut = &p->aOp[i+addr];
   62785       pOut->opcode = pIn->opcode;
   62786       pOut->p1 = pIn->p1;
   62787       if( p2<0 ){
   62788         assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
   62789         pOut->p2 = addr + ADDR(p2);
   62790       }else{
   62791         pOut->p2 = p2;
   62792       }
   62793       pOut->p3 = pIn->p3;
   62794       pOut->p4type = P4_NOTUSED;
   62795       pOut->p4.p = 0;
   62796       pOut->p5 = 0;
   62797 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   62798       pOut->zComment = 0;
   62799 #endif
   62800 #ifdef SQLITE_VDBE_COVERAGE
   62801       pOut->iSrcLine = iLineno+i;
   62802 #else
   62803       (void)iLineno;
   62804 #endif
   62805 #ifdef SQLITE_DEBUG
   62806       if( p->db->flags & SQLITE_VdbeAddopTrace ){
   62807         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
   62808       }
   62809 #endif
   62810     }
   62811     p->nOp += nOp;
   62812   }
   62813   return addr;
   62814 }
   62815 
   62816 /*
   62817 ** Change the value of the P1 operand for a specific instruction.
   62818 ** This routine is useful when a large program is loaded from a
   62819 ** static array using sqlite3VdbeAddOpList but we want to make a
   62820 ** few minor changes to the program.
   62821 */
   62822 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
   62823   assert( p!=0 );
   62824   if( ((u32)p->nOp)>addr ){
   62825     p->aOp[addr].p1 = val;
   62826   }
   62827 }
   62828 
   62829 /*
   62830 ** Change the value of the P2 operand for a specific instruction.
   62831 ** This routine is useful for setting a jump destination.
   62832 */
   62833 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
   62834   assert( p!=0 );
   62835   if( ((u32)p->nOp)>addr ){
   62836     p->aOp[addr].p2 = val;
   62837   }
   62838 }
   62839 
   62840 /*
   62841 ** Change the value of the P3 operand for a specific instruction.
   62842 */
   62843 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
   62844   assert( p!=0 );
   62845   if( ((u32)p->nOp)>addr ){
   62846     p->aOp[addr].p3 = val;
   62847   }
   62848 }
   62849 
   62850 /*
   62851 ** Change the value of the P5 operand for the most recently
   62852 ** added operation.
   62853 */
   62854 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
   62855   assert( p!=0 );
   62856   if( p->aOp ){
   62857     assert( p->nOp>0 );
   62858     p->aOp[p->nOp-1].p5 = val;
   62859   }
   62860 }
   62861 
   62862 /*
   62863 ** Change the P2 operand of instruction addr so that it points to
   62864 ** the address of the next instruction to be coded.
   62865 */
   62866 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   62867   sqlite3VdbeChangeP2(p, addr, p->nOp);
   62868   p->pParse->iFixedOp = p->nOp - 1;
   62869 }
   62870 
   62871 
   62872 /*
   62873 ** If the input FuncDef structure is ephemeral, then free it.  If
   62874 ** the FuncDef is not ephermal, then do nothing.
   62875 */
   62876 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
   62877   if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
   62878     sqlite3DbFree(db, pDef);
   62879   }
   62880 }
   62881 
   62882 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
   62883 
   62884 /*
   62885 ** Delete a P4 value if necessary.
   62886 */
   62887 static void freeP4(sqlite3 *db, int p4type, void *p4){
   62888   if( p4 ){
   62889     assert( db );
   62890     switch( p4type ){
   62891       case P4_REAL:
   62892       case P4_INT64:
   62893       case P4_DYNAMIC:
   62894       case P4_INTARRAY: {
   62895         sqlite3DbFree(db, p4);
   62896         break;
   62897       }
   62898       case P4_KEYINFO: {
   62899         if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
   62900         break;
   62901       }
   62902       case P4_MPRINTF: {
   62903         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
   62904         break;
   62905       }
   62906       case P4_FUNCDEF: {
   62907         freeEphemeralFunction(db, (FuncDef*)p4);
   62908         break;
   62909       }
   62910       case P4_MEM: {
   62911         if( db->pnBytesFreed==0 ){
   62912           sqlite3ValueFree((sqlite3_value*)p4);
   62913         }else{
   62914           Mem *p = (Mem*)p4;
   62915           sqlite3DbFree(db, p->zMalloc);
   62916           sqlite3DbFree(db, p);
   62917         }
   62918         break;
   62919       }
   62920       case P4_VTAB : {
   62921         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
   62922         break;
   62923       }
   62924     }
   62925   }
   62926 }
   62927 
   62928 /*
   62929 ** Free the space allocated for aOp and any p4 values allocated for the
   62930 ** opcodes contained within. If aOp is not NULL it is assumed to contain
   62931 ** nOp entries.
   62932 */
   62933 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   62934   if( aOp ){
   62935     Op *pOp;
   62936     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
   62937       freeP4(db, pOp->p4type, pOp->p4.p);
   62938 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   62939       sqlite3DbFree(db, pOp->zComment);
   62940 #endif
   62941     }
   62942   }
   62943   sqlite3DbFree(db, aOp);
   62944 }
   62945 
   62946 /*
   62947 ** Link the SubProgram object passed as the second argument into the linked
   62948 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
   62949 ** objects when the VM is no longer required.
   62950 */
   62951 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
   62952   p->pNext = pVdbe->pProgram;
   62953   pVdbe->pProgram = p;
   62954 }
   62955 
   62956 /*
   62957 ** Change the opcode at addr into OP_Noop
   62958 */
   62959 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
   62960   if( addr<p->nOp ){
   62961     VdbeOp *pOp = &p->aOp[addr];
   62962     sqlite3 *db = p->db;
   62963     freeP4(db, pOp->p4type, pOp->p4.p);
   62964     memset(pOp, 0, sizeof(pOp[0]));
   62965     pOp->opcode = OP_Noop;
   62966     if( addr==p->nOp-1 ) p->nOp--;
   62967   }
   62968 }
   62969 
   62970 /*
   62971 ** Remove the last opcode inserted
   62972 */
   62973 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
   62974   if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
   62975     sqlite3VdbeChangeToNoop(p, p->nOp-1);
   62976     return 1;
   62977   }else{
   62978     return 0;
   62979   }
   62980 }
   62981 
   62982 /*
   62983 ** Change the value of the P4 operand for a specific instruction.
   62984 ** This routine is useful when a large program is loaded from a
   62985 ** static array using sqlite3VdbeAddOpList but we want to make a
   62986 ** few minor changes to the program.
   62987 **
   62988 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
   62989 ** the string is made into memory obtained from sqlite3_malloc().
   62990 ** A value of n==0 means copy bytes of zP4 up to and including the
   62991 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
   62992 **
   62993 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
   62994 ** to a string or structure that is guaranteed to exist for the lifetime of
   62995 ** the Vdbe. In these cases we can just copy the pointer.
   62996 **
   62997 ** If addr<0 then change P4 on the most recently inserted instruction.
   62998 */
   62999 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
   63000   Op *pOp;
   63001   sqlite3 *db;
   63002   assert( p!=0 );
   63003   db = p->db;
   63004   assert( p->magic==VDBE_MAGIC_INIT );
   63005   if( p->aOp==0 || db->mallocFailed ){
   63006     if( n!=P4_VTAB ){
   63007       freeP4(db, n, (void*)*(char**)&zP4);
   63008     }
   63009     return;
   63010   }
   63011   assert( p->nOp>0 );
   63012   assert( addr<p->nOp );
   63013   if( addr<0 ){
   63014     addr = p->nOp - 1;
   63015   }
   63016   pOp = &p->aOp[addr];
   63017   assert( pOp->p4type==P4_NOTUSED
   63018        || pOp->p4type==P4_INT32
   63019        || pOp->p4type==P4_KEYINFO );
   63020   freeP4(db, pOp->p4type, pOp->p4.p);
   63021   pOp->p4.p = 0;
   63022   if( n==P4_INT32 ){
   63023     /* Note: this cast is safe, because the origin data point was an int
   63024     ** that was cast to a (const char *). */
   63025     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
   63026     pOp->p4type = P4_INT32;
   63027   }else if( zP4==0 ){
   63028     pOp->p4.p = 0;
   63029     pOp->p4type = P4_NOTUSED;
   63030   }else if( n==P4_KEYINFO ){
   63031     pOp->p4.p = (void*)zP4;
   63032     pOp->p4type = P4_KEYINFO;
   63033   }else if( n==P4_VTAB ){
   63034     pOp->p4.p = (void*)zP4;
   63035     pOp->p4type = P4_VTAB;
   63036     sqlite3VtabLock((VTable *)zP4);
   63037     assert( ((VTable *)zP4)->db==p->db );
   63038   }else if( n<0 ){
   63039     pOp->p4.p = (void*)zP4;
   63040     pOp->p4type = (signed char)n;
   63041   }else{
   63042     if( n==0 ) n = sqlite3Strlen30(zP4);
   63043     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
   63044     pOp->p4type = P4_DYNAMIC;
   63045   }
   63046 }
   63047 
   63048 /*
   63049 ** Set the P4 on the most recently added opcode to the KeyInfo for the
   63050 ** index given.
   63051 */
   63052 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
   63053   Vdbe *v = pParse->pVdbe;
   63054   assert( v!=0 );
   63055   assert( pIdx!=0 );
   63056   sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
   63057                       P4_KEYINFO);
   63058 }
   63059 
   63060 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   63061 /*
   63062 ** Change the comment on the most recently coded instruction.  Or
   63063 ** insert a No-op and add the comment to that new instruction.  This
   63064 ** makes the code easier to read during debugging.  None of this happens
   63065 ** in a production build.
   63066 */
   63067 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
   63068   assert( p->nOp>0 || p->aOp==0 );
   63069   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   63070   if( p->nOp ){
   63071     assert( p->aOp );
   63072     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
   63073     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
   63074   }
   63075 }
   63076 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   63077   va_list ap;
   63078   if( p ){
   63079     va_start(ap, zFormat);
   63080     vdbeVComment(p, zFormat, ap);
   63081     va_end(ap);
   63082   }
   63083 }
   63084 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
   63085   va_list ap;
   63086   if( p ){
   63087     sqlite3VdbeAddOp0(p, OP_Noop);
   63088     va_start(ap, zFormat);
   63089     vdbeVComment(p, zFormat, ap);
   63090     va_end(ap);
   63091   }
   63092 }
   63093 #endif  /* NDEBUG */
   63094 
   63095 #ifdef SQLITE_VDBE_COVERAGE
   63096 /*
   63097 ** Set the value if the iSrcLine field for the previously coded instruction.
   63098 */
   63099 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
   63100   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
   63101 }
   63102 #endif /* SQLITE_VDBE_COVERAGE */
   63103 
   63104 /*
   63105 ** Return the opcode for a given address.  If the address is -1, then
   63106 ** return the most recently inserted opcode.
   63107 **
   63108 ** If a memory allocation error has occurred prior to the calling of this
   63109 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
   63110 ** is readable but not writable, though it is cast to a writable value.
   63111 ** The return of a dummy opcode allows the call to continue functioning
   63112 ** after a OOM fault without having to check to see if the return from
   63113 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
   63114 ** dummy will never be written to.  This is verified by code inspection and
   63115 ** by running with Valgrind.
   63116 */
   63117 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
   63118   /* C89 specifies that the constant "dummy" will be initialized to all
   63119   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
   63120   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
   63121   assert( p->magic==VDBE_MAGIC_INIT );
   63122   if( addr<0 ){
   63123     addr = p->nOp - 1;
   63124   }
   63125   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
   63126   if( p->db->mallocFailed ){
   63127     return (VdbeOp*)&dummy;
   63128   }else{
   63129     return &p->aOp[addr];
   63130   }
   63131 }
   63132 
   63133 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
   63134 /*
   63135 ** Return an integer value for one of the parameters to the opcode pOp
   63136 ** determined by character c.
   63137 */
   63138 static int translateP(char c, const Op *pOp){
   63139   if( c=='1' ) return pOp->p1;
   63140   if( c=='2' ) return pOp->p2;
   63141   if( c=='3' ) return pOp->p3;
   63142   if( c=='4' ) return pOp->p4.i;
   63143   return pOp->p5;
   63144 }
   63145 
   63146 /*
   63147 ** Compute a string for the "comment" field of a VDBE opcode listing.
   63148 **
   63149 ** The Synopsis: field in comments in the vdbe.c source file gets converted
   63150 ** to an extra string that is appended to the sqlite3OpcodeName().  In the
   63151 ** absence of other comments, this synopsis becomes the comment on the opcode.
   63152 ** Some translation occurs:
   63153 **
   63154 **       "PX"      ->  "r[X]"
   63155 **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
   63156 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
   63157 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
   63158 */
   63159 static int displayComment(
   63160   const Op *pOp,     /* The opcode to be commented */
   63161   const char *zP4,   /* Previously obtained value for P4 */
   63162   char *zTemp,       /* Write result here */
   63163   int nTemp          /* Space available in zTemp[] */
   63164 ){
   63165   const char *zOpName;
   63166   const char *zSynopsis;
   63167   int nOpName;
   63168   int ii, jj;
   63169   zOpName = sqlite3OpcodeName(pOp->opcode);
   63170   nOpName = sqlite3Strlen30(zOpName);
   63171   if( zOpName[nOpName+1] ){
   63172     int seenCom = 0;
   63173     char c;
   63174     zSynopsis = zOpName += nOpName + 1;
   63175     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
   63176       if( c=='P' ){
   63177         c = zSynopsis[++ii];
   63178         if( c=='4' ){
   63179           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
   63180         }else if( c=='X' ){
   63181           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
   63182           seenCom = 1;
   63183         }else{
   63184           int v1 = translateP(c, pOp);
   63185           int v2;
   63186           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
   63187           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
   63188             ii += 3;
   63189             jj += sqlite3Strlen30(zTemp+jj);
   63190             v2 = translateP(zSynopsis[ii], pOp);
   63191             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
   63192               ii += 2;
   63193               v2++;
   63194             }
   63195             if( v2>1 ){
   63196               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
   63197             }
   63198           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
   63199             ii += 4;
   63200           }
   63201         }
   63202         jj += sqlite3Strlen30(zTemp+jj);
   63203       }else{
   63204         zTemp[jj++] = c;
   63205       }
   63206     }
   63207     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
   63208       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
   63209       jj += sqlite3Strlen30(zTemp+jj);
   63210     }
   63211     if( jj<nTemp ) zTemp[jj] = 0;
   63212   }else if( pOp->zComment ){
   63213     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
   63214     jj = sqlite3Strlen30(zTemp);
   63215   }else{
   63216     zTemp[0] = 0;
   63217     jj = 0;
   63218   }
   63219   return jj;
   63220 }
   63221 #endif /* SQLITE_DEBUG */
   63222 
   63223 
   63224 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
   63225      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   63226 /*
   63227 ** Compute a string that describes the P4 parameter for an opcode.
   63228 ** Use zTemp for any required temporary buffer space.
   63229 */
   63230 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
   63231   char *zP4 = zTemp;
   63232   assert( nTemp>=20 );
   63233   switch( pOp->p4type ){
   63234     case P4_KEYINFO: {
   63235       int i, j;
   63236       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
   63237       assert( pKeyInfo->aSortOrder!=0 );
   63238       sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
   63239       i = sqlite3Strlen30(zTemp);
   63240       for(j=0; j<pKeyInfo->nField; j++){
   63241         CollSeq *pColl = pKeyInfo->aColl[j];
   63242         const char *zColl = pColl ? pColl->zName : "nil";
   63243         int n = sqlite3Strlen30(zColl);
   63244         if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
   63245           zColl = "B";
   63246           n = 1;
   63247         }
   63248         if( i+n>nTemp-6 ){
   63249           memcpy(&zTemp[i],",...",4);
   63250           break;
   63251         }
   63252         zTemp[i++] = ',';
   63253         if( pKeyInfo->aSortOrder[j] ){
   63254           zTemp[i++] = '-';
   63255         }
   63256         memcpy(&zTemp[i], zColl, n+1);
   63257         i += n;
   63258       }
   63259       zTemp[i++] = ')';
   63260       zTemp[i] = 0;
   63261       assert( i<nTemp );
   63262       break;
   63263     }
   63264     case P4_COLLSEQ: {
   63265       CollSeq *pColl = pOp->p4.pColl;
   63266       sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
   63267       break;
   63268     }
   63269     case P4_FUNCDEF: {
   63270       FuncDef *pDef = pOp->p4.pFunc;
   63271       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
   63272       break;
   63273     }
   63274     case P4_INT64: {
   63275       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
   63276       break;
   63277     }
   63278     case P4_INT32: {
   63279       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
   63280       break;
   63281     }
   63282     case P4_REAL: {
   63283       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
   63284       break;
   63285     }
   63286     case P4_MEM: {
   63287       Mem *pMem = pOp->p4.pMem;
   63288       if( pMem->flags & MEM_Str ){
   63289         zP4 = pMem->z;
   63290       }else if( pMem->flags & MEM_Int ){
   63291         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
   63292       }else if( pMem->flags & MEM_Real ){
   63293         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
   63294       }else if( pMem->flags & MEM_Null ){
   63295         sqlite3_snprintf(nTemp, zTemp, "NULL");
   63296       }else{
   63297         assert( pMem->flags & MEM_Blob );
   63298         zP4 = "(blob)";
   63299       }
   63300       break;
   63301     }
   63302 #ifndef SQLITE_OMIT_VIRTUALTABLE
   63303     case P4_VTAB: {
   63304       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
   63305       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
   63306       break;
   63307     }
   63308 #endif
   63309     case P4_INTARRAY: {
   63310       sqlite3_snprintf(nTemp, zTemp, "intarray");
   63311       break;
   63312     }
   63313     case P4_SUBPROGRAM: {
   63314       sqlite3_snprintf(nTemp, zTemp, "program");
   63315       break;
   63316     }
   63317     case P4_ADVANCE: {
   63318       zTemp[0] = 0;
   63319       break;
   63320     }
   63321     default: {
   63322       zP4 = pOp->p4.z;
   63323       if( zP4==0 ){
   63324         zP4 = zTemp;
   63325         zTemp[0] = 0;
   63326       }
   63327     }
   63328   }
   63329   assert( zP4!=0 );
   63330   return zP4;
   63331 }
   63332 #endif
   63333 
   63334 /*
   63335 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   63336 **
   63337 ** The prepared statements need to know in advance the complete set of
   63338 ** attached databases that will be use.  A mask of these databases
   63339 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
   63340 ** p->btreeMask of databases that will require a lock.
   63341 */
   63342 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   63343   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
   63344   assert( i<(int)sizeof(p->btreeMask)*8 );
   63345   DbMaskSet(p->btreeMask, i);
   63346   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
   63347     DbMaskSet(p->lockMask, i);
   63348   }
   63349 }
   63350 
   63351 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   63352 /*
   63353 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
   63354 ** this routine obtains the mutex associated with each BtShared structure
   63355 ** that may be accessed by the VM passed as an argument. In doing so it also
   63356 ** sets the BtShared.db member of each of the BtShared structures, ensuring
   63357 ** that the correct busy-handler callback is invoked if required.
   63358 **
   63359 ** If SQLite is not threadsafe but does support shared-cache mode, then
   63360 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
   63361 ** of all of BtShared structures accessible via the database handle
   63362 ** associated with the VM.
   63363 **
   63364 ** If SQLite is not threadsafe and does not support shared-cache mode, this
   63365 ** function is a no-op.
   63366 **
   63367 ** The p->btreeMask field is a bitmask of all btrees that the prepared
   63368 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
   63369 ** corresponding to btrees that use shared cache.  Then the runtime of
   63370 ** this routine is N*N.  But as N is rarely more than 1, this should not
   63371 ** be a problem.
   63372 */
   63373 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
   63374   int i;
   63375   sqlite3 *db;
   63376   Db *aDb;
   63377   int nDb;
   63378   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
   63379   db = p->db;
   63380   aDb = db->aDb;
   63381   nDb = db->nDb;
   63382   for(i=0; i<nDb; i++){
   63383     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
   63384       sqlite3BtreeEnter(aDb[i].pBt);
   63385     }
   63386   }
   63387 }
   63388 #endif
   63389 
   63390 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   63391 /*
   63392 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
   63393 */
   63394 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
   63395   int i;
   63396   sqlite3 *db;
   63397   Db *aDb;
   63398   int nDb;
   63399   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
   63400   db = p->db;
   63401   aDb = db->aDb;
   63402   nDb = db->nDb;
   63403   for(i=0; i<nDb; i++){
   63404     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
   63405       sqlite3BtreeLeave(aDb[i].pBt);
   63406     }
   63407   }
   63408 }
   63409 #endif
   63410 
   63411 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   63412 /*
   63413 ** Print a single opcode.  This routine is used for debugging only.
   63414 */
   63415 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
   63416   char *zP4;
   63417   char zPtr[50];
   63418   char zCom[100];
   63419   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
   63420   if( pOut==0 ) pOut = stdout;
   63421   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
   63422 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   63423   displayComment(pOp, zP4, zCom, sizeof(zCom));
   63424 #else
   63425   zCom[0] = 0;
   63426 #endif
   63427   /* NB:  The sqlite3OpcodeName() function is implemented by code created
   63428   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
   63429   ** information from the vdbe.c source text */
   63430   fprintf(pOut, zFormat1, pc,
   63431       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
   63432       zCom
   63433   );
   63434   fflush(pOut);
   63435 }
   63436 #endif
   63437 
   63438 /*
   63439 ** Release an array of N Mem elements
   63440 */
   63441 static void releaseMemArray(Mem *p, int N){
   63442   if( p && N ){
   63443     Mem *pEnd;
   63444     sqlite3 *db = p->db;
   63445     u8 malloc_failed = db->mallocFailed;
   63446     if( db->pnBytesFreed ){
   63447       for(pEnd=&p[N]; p<pEnd; p++){
   63448         sqlite3DbFree(db, p->zMalloc);
   63449       }
   63450       return;
   63451     }
   63452     for(pEnd=&p[N]; p<pEnd; p++){
   63453       assert( (&p[1])==pEnd || p[0].db==p[1].db );
   63454       assert( sqlite3VdbeCheckMemInvariants(p) );
   63455 
   63456       /* This block is really an inlined version of sqlite3VdbeMemRelease()
   63457       ** that takes advantage of the fact that the memory cell value is
   63458       ** being set to NULL after releasing any dynamic resources.
   63459       **
   63460       ** The justification for duplicating code is that according to
   63461       ** callgrind, this causes a certain test case to hit the CPU 4.7
   63462       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
   63463       ** sqlite3MemRelease() were called from here. With -O2, this jumps
   63464       ** to 6.6 percent. The test case is inserting 1000 rows into a table
   63465       ** with no indexes using a single prepared INSERT statement, bind()
   63466       ** and reset(). Inserts are grouped into a transaction.
   63467       */
   63468       testcase( p->flags & MEM_Agg );
   63469       testcase( p->flags & MEM_Dyn );
   63470       testcase( p->flags & MEM_Frame );
   63471       testcase( p->flags & MEM_RowSet );
   63472       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
   63473         sqlite3VdbeMemRelease(p);
   63474       }else if( p->zMalloc ){
   63475         sqlite3DbFree(db, p->zMalloc);
   63476         p->zMalloc = 0;
   63477       }
   63478 
   63479       p->flags = MEM_Undefined;
   63480     }
   63481     db->mallocFailed = malloc_failed;
   63482   }
   63483 }
   63484 
   63485 /*
   63486 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
   63487 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
   63488 */
   63489 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
   63490   int i;
   63491   Mem *aMem = VdbeFrameMem(p);
   63492   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
   63493   for(i=0; i<p->nChildCsr; i++){
   63494     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
   63495   }
   63496   releaseMemArray(aMem, p->nChildMem);
   63497   sqlite3DbFree(p->v->db, p);
   63498 }
   63499 
   63500 #ifndef SQLITE_OMIT_EXPLAIN
   63501 /*
   63502 ** Give a listing of the program in the virtual machine.
   63503 **
   63504 ** The interface is the same as sqlite3VdbeExec().  But instead of
   63505 ** running the code, it invokes the callback once for each instruction.
   63506 ** This feature is used to implement "EXPLAIN".
   63507 **
   63508 ** When p->explain==1, each instruction is listed.  When
   63509 ** p->explain==2, only OP_Explain instructions are listed and these
   63510 ** are shown in a different format.  p->explain==2 is used to implement
   63511 ** EXPLAIN QUERY PLAN.
   63512 **
   63513 ** When p->explain==1, first the main program is listed, then each of
   63514 ** the trigger subprograms are listed one by one.
   63515 */
   63516 SQLITE_PRIVATE int sqlite3VdbeList(
   63517   Vdbe *p                   /* The VDBE */
   63518 ){
   63519   int nRow;                            /* Stop when row count reaches this */
   63520   int nSub = 0;                        /* Number of sub-vdbes seen so far */
   63521   SubProgram **apSub = 0;              /* Array of sub-vdbes */
   63522   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
   63523   sqlite3 *db = p->db;                 /* The database connection */
   63524   int i;                               /* Loop counter */
   63525   int rc = SQLITE_OK;                  /* Return code */
   63526   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
   63527 
   63528   assert( p->explain );
   63529   assert( p->magic==VDBE_MAGIC_RUN );
   63530   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
   63531 
   63532   /* Even though this opcode does not use dynamic strings for
   63533   ** the result, result columns may become dynamic if the user calls
   63534   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   63535   */
   63536   releaseMemArray(pMem, 8);
   63537   p->pResultSet = 0;
   63538 
   63539   if( p->rc==SQLITE_NOMEM ){
   63540     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   63541     ** sqlite3_column_text16() failed.  */
   63542     db->mallocFailed = 1;
   63543     return SQLITE_ERROR;
   63544   }
   63545 
   63546   /* When the number of output rows reaches nRow, that means the
   63547   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
   63548   ** nRow is the sum of the number of rows in the main program, plus
   63549   ** the sum of the number of rows in all trigger subprograms encountered
   63550   ** so far.  The nRow value will increase as new trigger subprograms are
   63551   ** encountered, but p->pc will eventually catch up to nRow.
   63552   */
   63553   nRow = p->nOp;
   63554   if( p->explain==1 ){
   63555     /* The first 8 memory cells are used for the result set.  So we will
   63556     ** commandeer the 9th cell to use as storage for an array of pointers
   63557     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
   63558     ** cells.  */
   63559     assert( p->nMem>9 );
   63560     pSub = &p->aMem[9];
   63561     if( pSub->flags&MEM_Blob ){
   63562       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
   63563       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
   63564       nSub = pSub->n/sizeof(Vdbe*);
   63565       apSub = (SubProgram **)pSub->z;
   63566     }
   63567     for(i=0; i<nSub; i++){
   63568       nRow += apSub[i]->nOp;
   63569     }
   63570   }
   63571 
   63572   do{
   63573     i = p->pc++;
   63574   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
   63575   if( i>=nRow ){
   63576     p->rc = SQLITE_OK;
   63577     rc = SQLITE_DONE;
   63578   }else if( db->u1.isInterrupted ){
   63579     p->rc = SQLITE_INTERRUPT;
   63580     rc = SQLITE_ERROR;
   63581     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
   63582   }else{
   63583     char *zP4;
   63584     Op *pOp;
   63585     if( i<p->nOp ){
   63586       /* The output line number is small enough that we are still in the
   63587       ** main program. */
   63588       pOp = &p->aOp[i];
   63589     }else{
   63590       /* We are currently listing subprograms.  Figure out which one and
   63591       ** pick up the appropriate opcode. */
   63592       int j;
   63593       i -= p->nOp;
   63594       for(j=0; i>=apSub[j]->nOp; j++){
   63595         i -= apSub[j]->nOp;
   63596       }
   63597       pOp = &apSub[j]->aOp[i];
   63598     }
   63599     if( p->explain==1 ){
   63600       pMem->flags = MEM_Int;
   63601       pMem->u.i = i;                                /* Program counter */
   63602       pMem++;
   63603 
   63604       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   63605       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
   63606       assert( pMem->z!=0 );
   63607       pMem->n = sqlite3Strlen30(pMem->z);
   63608       pMem->enc = SQLITE_UTF8;
   63609       pMem++;
   63610 
   63611       /* When an OP_Program opcode is encounter (the only opcode that has
   63612       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
   63613       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
   63614       ** has not already been seen.
   63615       */
   63616       if( pOp->p4type==P4_SUBPROGRAM ){
   63617         int nByte = (nSub+1)*sizeof(SubProgram*);
   63618         int j;
   63619         for(j=0; j<nSub; j++){
   63620           if( apSub[j]==pOp->p4.pProgram ) break;
   63621         }
   63622         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
   63623           apSub = (SubProgram **)pSub->z;
   63624           apSub[nSub++] = pOp->p4.pProgram;
   63625           pSub->flags |= MEM_Blob;
   63626           pSub->n = nSub*sizeof(SubProgram*);
   63627         }
   63628       }
   63629     }
   63630 
   63631     pMem->flags = MEM_Int;
   63632     pMem->u.i = pOp->p1;                          /* P1 */
   63633     pMem++;
   63634 
   63635     pMem->flags = MEM_Int;
   63636     pMem->u.i = pOp->p2;                          /* P2 */
   63637     pMem++;
   63638 
   63639     pMem->flags = MEM_Int;
   63640     pMem->u.i = pOp->p3;                          /* P3 */
   63641     pMem++;
   63642 
   63643     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
   63644       assert( p->db->mallocFailed );
   63645       return SQLITE_ERROR;
   63646     }
   63647     pMem->flags = MEM_Str|MEM_Term;
   63648     zP4 = displayP4(pOp, pMem->z, 32);
   63649     if( zP4!=pMem->z ){
   63650       sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
   63651     }else{
   63652       assert( pMem->z!=0 );
   63653       pMem->n = sqlite3Strlen30(pMem->z);
   63654       pMem->enc = SQLITE_UTF8;
   63655     }
   63656     pMem++;
   63657 
   63658     if( p->explain==1 ){
   63659       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
   63660         assert( p->db->mallocFailed );
   63661         return SQLITE_ERROR;
   63662       }
   63663       pMem->flags = MEM_Str|MEM_Term;
   63664       pMem->n = 2;
   63665       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
   63666       pMem->enc = SQLITE_UTF8;
   63667       pMem++;
   63668 
   63669 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   63670       if( sqlite3VdbeMemGrow(pMem, 500, 0) ){
   63671         assert( p->db->mallocFailed );
   63672         return SQLITE_ERROR;
   63673       }
   63674       pMem->flags = MEM_Str|MEM_Term;
   63675       pMem->n = displayComment(pOp, zP4, pMem->z, 500);
   63676       pMem->enc = SQLITE_UTF8;
   63677 #else
   63678       pMem->flags = MEM_Null;                       /* Comment */
   63679 #endif
   63680     }
   63681 
   63682     p->nResColumn = 8 - 4*(p->explain-1);
   63683     p->pResultSet = &p->aMem[1];
   63684     p->rc = SQLITE_OK;
   63685     rc = SQLITE_ROW;
   63686   }
   63687   return rc;
   63688 }
   63689 #endif /* SQLITE_OMIT_EXPLAIN */
   63690 
   63691 #ifdef SQLITE_DEBUG
   63692 /*
   63693 ** Print the SQL that was used to generate a VDBE program.
   63694 */
   63695 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
   63696   const char *z = 0;
   63697   if( p->zSql ){
   63698     z = p->zSql;
   63699   }else if( p->nOp>=1 ){
   63700     const VdbeOp *pOp = &p->aOp[0];
   63701     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
   63702       z = pOp->p4.z;
   63703       while( sqlite3Isspace(*z) ) z++;
   63704     }
   63705   }
   63706   if( z ) printf("SQL: [%s]\n", z);
   63707 }
   63708 #endif
   63709 
   63710 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   63711 /*
   63712 ** Print an IOTRACE message showing SQL content.
   63713 */
   63714 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
   63715   int nOp = p->nOp;
   63716   VdbeOp *pOp;
   63717   if( sqlite3IoTrace==0 ) return;
   63718   if( nOp<1 ) return;
   63719   pOp = &p->aOp[0];
   63720   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
   63721     int i, j;
   63722     char z[1000];
   63723     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
   63724     for(i=0; sqlite3Isspace(z[i]); i++){}
   63725     for(j=0; z[i]; i++){
   63726       if( sqlite3Isspace(z[i]) ){
   63727         if( z[i-1]!=' ' ){
   63728           z[j++] = ' ';
   63729         }
   63730       }else{
   63731         z[j++] = z[i];
   63732       }
   63733     }
   63734     z[j] = 0;
   63735     sqlite3IoTrace("SQL %s\n", z);
   63736   }
   63737 }
   63738 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
   63739 
   63740 /*
   63741 ** Allocate space from a fixed size buffer and return a pointer to
   63742 ** that space.  If insufficient space is available, return NULL.
   63743 **
   63744 ** The pBuf parameter is the initial value of a pointer which will
   63745 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
   63746 ** NULL, it means that memory space has already been allocated and that
   63747 ** this routine should not allocate any new memory.  When pBuf is not
   63748 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
   63749 ** is NULL.
   63750 **
   63751 ** nByte is the number of bytes of space needed.
   63752 **
   63753 ** *ppFrom points to available space and pEnd points to the end of the
   63754 ** available space.  When space is allocated, *ppFrom is advanced past
   63755 ** the end of the allocated space.
   63756 **
   63757 ** *pnByte is a counter of the number of bytes of space that have failed
   63758 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
   63759 ** request, then increment *pnByte by the amount of the request.
   63760 */
   63761 static void *allocSpace(
   63762   void *pBuf,          /* Where return pointer will be stored */
   63763   int nByte,           /* Number of bytes to allocate */
   63764   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
   63765   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
   63766   int *pnByte          /* If allocation cannot be made, increment *pnByte */
   63767 ){
   63768   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
   63769   if( pBuf ) return pBuf;
   63770   nByte = ROUND8(nByte);
   63771   if( &(*ppFrom)[nByte] <= pEnd ){
   63772     pBuf = (void*)*ppFrom;
   63773     *ppFrom += nByte;
   63774   }else{
   63775     *pnByte += nByte;
   63776   }
   63777   return pBuf;
   63778 }
   63779 
   63780 /*
   63781 ** Rewind the VDBE back to the beginning in preparation for
   63782 ** running it.
   63783 */
   63784 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
   63785 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   63786   int i;
   63787 #endif
   63788   assert( p!=0 );
   63789   assert( p->magic==VDBE_MAGIC_INIT );
   63790 
   63791   /* There should be at least one opcode.
   63792   */
   63793   assert( p->nOp>0 );
   63794 
   63795   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
   63796   p->magic = VDBE_MAGIC_RUN;
   63797 
   63798 #ifdef SQLITE_DEBUG
   63799   for(i=1; i<p->nMem; i++){
   63800     assert( p->aMem[i].db==p->db );
   63801   }
   63802 #endif
   63803   p->pc = -1;
   63804   p->rc = SQLITE_OK;
   63805   p->errorAction = OE_Abort;
   63806   p->magic = VDBE_MAGIC_RUN;
   63807   p->nChange = 0;
   63808   p->cacheCtr = 1;
   63809   p->minWriteFileFormat = 255;
   63810   p->iStatement = 0;
   63811   p->nFkConstraint = 0;
   63812 #ifdef VDBE_PROFILE
   63813   for(i=0; i<p->nOp; i++){
   63814     p->aOp[i].cnt = 0;
   63815     p->aOp[i].cycles = 0;
   63816   }
   63817 #endif
   63818 }
   63819 
   63820 /*
   63821 ** Prepare a virtual machine for execution for the first time after
   63822 ** creating the virtual machine.  This involves things such
   63823 ** as allocating stack space and initializing the program counter.
   63824 ** After the VDBE has be prepped, it can be executed by one or more
   63825 ** calls to sqlite3VdbeExec().
   63826 **
   63827 ** This function may be called exact once on a each virtual machine.
   63828 ** After this routine is called the VM has been "packaged" and is ready
   63829 ** to run.  After this routine is called, futher calls to
   63830 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
   63831 ** the Vdbe from the Parse object that helped generate it so that the
   63832 ** the Vdbe becomes an independent entity and the Parse object can be
   63833 ** destroyed.
   63834 **
   63835 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
   63836 ** to its initial state after it has been run.
   63837 */
   63838 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
   63839   Vdbe *p,                       /* The VDBE */
   63840   Parse *pParse                  /* Parsing context */
   63841 ){
   63842   sqlite3 *db;                   /* The database connection */
   63843   int nVar;                      /* Number of parameters */
   63844   int nMem;                      /* Number of VM memory registers */
   63845   int nCursor;                   /* Number of cursors required */
   63846   int nArg;                      /* Number of arguments in subprograms */
   63847   int nOnce;                     /* Number of OP_Once instructions */
   63848   int n;                         /* Loop counter */
   63849   u8 *zCsr;                      /* Memory available for allocation */
   63850   u8 *zEnd;                      /* First byte past allocated memory */
   63851   int nByte;                     /* How much extra memory is needed */
   63852 
   63853   assert( p!=0 );
   63854   assert( p->nOp>0 );
   63855   assert( pParse!=0 );
   63856   assert( p->magic==VDBE_MAGIC_INIT );
   63857   assert( pParse==p->pParse );
   63858   db = p->db;
   63859   assert( db->mallocFailed==0 );
   63860   nVar = pParse->nVar;
   63861   nMem = pParse->nMem;
   63862   nCursor = pParse->nTab;
   63863   nArg = pParse->nMaxArg;
   63864   nOnce = pParse->nOnce;
   63865   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
   63866 
   63867   /* For each cursor required, also allocate a memory cell. Memory
   63868   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
   63869   ** the vdbe program. Instead they are used to allocate space for
   63870   ** VdbeCursor/BtCursor structures. The blob of memory associated with
   63871   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
   63872   ** stores the blob of memory associated with cursor 1, etc.
   63873   **
   63874   ** See also: allocateCursor().
   63875   */
   63876   nMem += nCursor;
   63877 
   63878   /* Allocate space for memory registers, SQL variables, VDBE cursors and
   63879   ** an array to marshal SQL function arguments in.
   63880   */
   63881   zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
   63882   zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
   63883 
   63884   resolveP2Values(p, &nArg);
   63885   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
   63886   if( pParse->explain && nMem<10 ){
   63887     nMem = 10;
   63888   }
   63889   memset(zCsr, 0, zEnd-zCsr);
   63890   zCsr += (zCsr - (u8*)0)&7;
   63891   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
   63892   p->expired = 0;
   63893 
   63894   /* Memory for registers, parameters, cursor, etc, is allocated in two
   63895   ** passes.  On the first pass, we try to reuse unused space at the
   63896   ** end of the opcode array.  If we are unable to satisfy all memory
   63897   ** requirements by reusing the opcode array tail, then the second
   63898   ** pass will fill in the rest using a fresh allocation.
   63899   **
   63900   ** This two-pass approach that reuses as much memory as possible from
   63901   ** the leftover space at the end of the opcode array can significantly
   63902   ** reduce the amount of memory held by a prepared statement.
   63903   */
   63904   do {
   63905     nByte = 0;
   63906     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
   63907     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
   63908     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
   63909     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
   63910     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
   63911                           &zCsr, zEnd, &nByte);
   63912     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
   63913     if( nByte ){
   63914       p->pFree = sqlite3DbMallocZero(db, nByte);
   63915     }
   63916     zCsr = p->pFree;
   63917     zEnd = &zCsr[nByte];
   63918   }while( nByte && !db->mallocFailed );
   63919 
   63920   p->nCursor = nCursor;
   63921   p->nOnceFlag = nOnce;
   63922   if( p->aVar ){
   63923     p->nVar = (ynVar)nVar;
   63924     for(n=0; n<nVar; n++){
   63925       p->aVar[n].flags = MEM_Null;
   63926       p->aVar[n].db = db;
   63927     }
   63928   }
   63929   if( p->azVar ){
   63930     p->nzVar = pParse->nzVar;
   63931     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
   63932     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
   63933   }
   63934   if( p->aMem ){
   63935     p->aMem--;                      /* aMem[] goes from 1..nMem */
   63936     p->nMem = nMem;                 /*       not from 0..nMem-1 */
   63937     for(n=1; n<=nMem; n++){
   63938       p->aMem[n].flags = MEM_Undefined;
   63939       p->aMem[n].db = db;
   63940     }
   63941   }
   63942   p->explain = pParse->explain;
   63943   sqlite3VdbeRewind(p);
   63944 }
   63945 
   63946 /*
   63947 ** Close a VDBE cursor and release all the resources that cursor
   63948 ** happens to hold.
   63949 */
   63950 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
   63951   if( pCx==0 ){
   63952     return;
   63953   }
   63954   sqlite3VdbeSorterClose(p->db, pCx);
   63955   if( pCx->pBt ){
   63956     sqlite3BtreeClose(pCx->pBt);
   63957     /* The pCx->pCursor will be close automatically, if it exists, by
   63958     ** the call above. */
   63959   }else if( pCx->pCursor ){
   63960     sqlite3BtreeCloseCursor(pCx->pCursor);
   63961   }
   63962 #ifndef SQLITE_OMIT_VIRTUALTABLE
   63963   if( pCx->pVtabCursor ){
   63964     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
   63965     const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
   63966     p->inVtabMethod = 1;
   63967     pModule->xClose(pVtabCursor);
   63968     p->inVtabMethod = 0;
   63969   }
   63970 #endif
   63971 }
   63972 
   63973 /*
   63974 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
   63975 ** is used, for example, when a trigger sub-program is halted to restore
   63976 ** control to the main program.
   63977 */
   63978 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
   63979   Vdbe *v = pFrame->v;
   63980   v->aOnceFlag = pFrame->aOnceFlag;
   63981   v->nOnceFlag = pFrame->nOnceFlag;
   63982   v->aOp = pFrame->aOp;
   63983   v->nOp = pFrame->nOp;
   63984   v->aMem = pFrame->aMem;
   63985   v->nMem = pFrame->nMem;
   63986   v->apCsr = pFrame->apCsr;
   63987   v->nCursor = pFrame->nCursor;
   63988   v->db->lastRowid = pFrame->lastRowid;
   63989   v->nChange = pFrame->nChange;
   63990   return pFrame->pc;
   63991 }
   63992 
   63993 /*
   63994 ** Close all cursors.
   63995 **
   63996 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
   63997 ** cell array. This is necessary as the memory cell array may contain
   63998 ** pointers to VdbeFrame objects, which may in turn contain pointers to
   63999 ** open cursors.
   64000 */
   64001 static void closeAllCursors(Vdbe *p){
   64002   if( p->pFrame ){
   64003     VdbeFrame *pFrame;
   64004     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   64005     sqlite3VdbeFrameRestore(pFrame);
   64006   }
   64007   p->pFrame = 0;
   64008   p->nFrame = 0;
   64009 
   64010   if( p->apCsr ){
   64011     int i;
   64012     for(i=0; i<p->nCursor; i++){
   64013       VdbeCursor *pC = p->apCsr[i];
   64014       if( pC ){
   64015         sqlite3VdbeFreeCursor(p, pC);
   64016         p->apCsr[i] = 0;
   64017       }
   64018     }
   64019   }
   64020   if( p->aMem ){
   64021     releaseMemArray(&p->aMem[1], p->nMem);
   64022   }
   64023   while( p->pDelFrame ){
   64024     VdbeFrame *pDel = p->pDelFrame;
   64025     p->pDelFrame = pDel->pParent;
   64026     sqlite3VdbeFrameDelete(pDel);
   64027   }
   64028 
   64029   /* Delete any auxdata allocations made by the VM */
   64030   sqlite3VdbeDeleteAuxData(p, -1, 0);
   64031   assert( p->pAuxData==0 );
   64032 }
   64033 
   64034 /*
   64035 ** Clean up the VM after execution.
   64036 **
   64037 ** This routine will automatically close any cursors, lists, and/or
   64038 ** sorters that were left open.  It also deletes the values of
   64039 ** variables in the aVar[] array.
   64040 */
   64041 static void Cleanup(Vdbe *p){
   64042   sqlite3 *db = p->db;
   64043 
   64044 #ifdef SQLITE_DEBUG
   64045   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
   64046   ** Vdbe.aMem[] arrays have already been cleaned up.  */
   64047   int i;
   64048   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
   64049   if( p->aMem ){
   64050     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
   64051   }
   64052 #endif
   64053 
   64054   sqlite3DbFree(db, p->zErrMsg);
   64055   p->zErrMsg = 0;
   64056   p->pResultSet = 0;
   64057 }
   64058 
   64059 /*
   64060 ** Set the number of result columns that will be returned by this SQL
   64061 ** statement. This is now set at compile time, rather than during
   64062 ** execution of the vdbe program so that sqlite3_column_count() can
   64063 ** be called on an SQL statement before sqlite3_step().
   64064 */
   64065 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
   64066   Mem *pColName;
   64067   int n;
   64068   sqlite3 *db = p->db;
   64069 
   64070   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   64071   sqlite3DbFree(db, p->aColName);
   64072   n = nResColumn*COLNAME_N;
   64073   p->nResColumn = (u16)nResColumn;
   64074   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
   64075   if( p->aColName==0 ) return;
   64076   while( n-- > 0 ){
   64077     pColName->flags = MEM_Null;
   64078     pColName->db = p->db;
   64079     pColName++;
   64080   }
   64081 }
   64082 
   64083 /*
   64084 ** Set the name of the idx'th column to be returned by the SQL statement.
   64085 ** zName must be a pointer to a nul terminated string.
   64086 **
   64087 ** This call must be made after a call to sqlite3VdbeSetNumCols().
   64088 **
   64089 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
   64090 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
   64091 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
   64092 */
   64093 SQLITE_PRIVATE int sqlite3VdbeSetColName(
   64094   Vdbe *p,                         /* Vdbe being configured */
   64095   int idx,                         /* Index of column zName applies to */
   64096   int var,                         /* One of the COLNAME_* constants */
   64097   const char *zName,               /* Pointer to buffer containing name */
   64098   void (*xDel)(void*)              /* Memory management strategy for zName */
   64099 ){
   64100   int rc;
   64101   Mem *pColName;
   64102   assert( idx<p->nResColumn );
   64103   assert( var<COLNAME_N );
   64104   if( p->db->mallocFailed ){
   64105     assert( !zName || xDel!=SQLITE_DYNAMIC );
   64106     return SQLITE_NOMEM;
   64107   }
   64108   assert( p->aColName!=0 );
   64109   pColName = &(p->aColName[idx+var*p->nResColumn]);
   64110   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
   64111   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
   64112   return rc;
   64113 }
   64114 
   64115 /*
   64116 ** A read or write transaction may or may not be active on database handle
   64117 ** db. If a transaction is active, commit it. If there is a
   64118 ** write-transaction spanning more than one database file, this routine
   64119 ** takes care of the master journal trickery.
   64120 */
   64121 static int vdbeCommit(sqlite3 *db, Vdbe *p){
   64122   int i;
   64123   int nTrans = 0;  /* Number of databases with an active write-transaction */
   64124   int rc = SQLITE_OK;
   64125   int needXcommit = 0;
   64126 
   64127 #ifdef SQLITE_OMIT_VIRTUALTABLE
   64128   /* With this option, sqlite3VtabSync() is defined to be simply
   64129   ** SQLITE_OK so p is not used.
   64130   */
   64131   UNUSED_PARAMETER(p);
   64132 #endif
   64133 
   64134   /* Before doing anything else, call the xSync() callback for any
   64135   ** virtual module tables written in this transaction. This has to
   64136   ** be done before determining whether a master journal file is
   64137   ** required, as an xSync() callback may add an attached database
   64138   ** to the transaction.
   64139   */
   64140   rc = sqlite3VtabSync(db, p);
   64141 
   64142   /* This loop determines (a) if the commit hook should be invoked and
   64143   ** (b) how many database files have open write transactions, not
   64144   ** including the temp database. (b) is important because if more than
   64145   ** one database file has an open write transaction, a master journal
   64146   ** file is required for an atomic commit.
   64147   */
   64148   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   64149     Btree *pBt = db->aDb[i].pBt;
   64150     if( sqlite3BtreeIsInTrans(pBt) ){
   64151       needXcommit = 1;
   64152       if( i!=1 ) nTrans++;
   64153       sqlite3BtreeEnter(pBt);
   64154       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
   64155       sqlite3BtreeLeave(pBt);
   64156     }
   64157   }
   64158   if( rc!=SQLITE_OK ){
   64159     return rc;
   64160   }
   64161 
   64162   /* If there are any write-transactions at all, invoke the commit hook */
   64163   if( needXcommit && db->xCommitCallback ){
   64164     rc = db->xCommitCallback(db->pCommitArg);
   64165     if( rc ){
   64166       return SQLITE_CONSTRAINT_COMMITHOOK;
   64167     }
   64168   }
   64169 
   64170   /* The simple case - no more than one database file (not counting the
   64171   ** TEMP database) has a transaction active.   There is no need for the
   64172   ** master-journal.
   64173   **
   64174   ** If the return value of sqlite3BtreeGetFilename() is a zero length
   64175   ** string, it means the main database is :memory: or a temp file.  In
   64176   ** that case we do not support atomic multi-file commits, so use the
   64177   ** simple case then too.
   64178   */
   64179   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
   64180    || nTrans<=1
   64181   ){
   64182     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   64183       Btree *pBt = db->aDb[i].pBt;
   64184       if( pBt ){
   64185         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
   64186       }
   64187     }
   64188 
   64189     /* Do the commit only if all databases successfully complete phase 1.
   64190     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
   64191     ** IO error while deleting or truncating a journal file. It is unlikely,
   64192     ** but could happen. In this case abandon processing and return the error.
   64193     */
   64194     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   64195       Btree *pBt = db->aDb[i].pBt;
   64196       if( pBt ){
   64197         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
   64198       }
   64199     }
   64200     if( rc==SQLITE_OK ){
   64201       sqlite3VtabCommit(db);
   64202     }
   64203   }
   64204 
   64205   /* The complex case - There is a multi-file write-transaction active.
   64206   ** This requires a master journal file to ensure the transaction is
   64207   ** committed atomicly.
   64208   */
   64209 #ifndef SQLITE_OMIT_DISKIO
   64210   else{
   64211     sqlite3_vfs *pVfs = db->pVfs;
   64212     int needSync = 0;
   64213     char *zMaster = 0;   /* File-name for the master journal */
   64214     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
   64215     sqlite3_file *pMaster = 0;
   64216     i64 offset = 0;
   64217     int res;
   64218     int retryCount = 0;
   64219     int nMainFile;
   64220 
   64221     /* Select a master journal file name */
   64222     nMainFile = sqlite3Strlen30(zMainFile);
   64223     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
   64224     if( zMaster==0 ) return SQLITE_NOMEM;
   64225     do {
   64226       u32 iRandom;
   64227       if( retryCount ){
   64228         if( retryCount>100 ){
   64229           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
   64230           sqlite3OsDelete(pVfs, zMaster, 0);
   64231           break;
   64232         }else if( retryCount==1 ){
   64233           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
   64234         }
   64235       }
   64236       retryCount++;
   64237       sqlite3_randomness(sizeof(iRandom), &iRandom);
   64238       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
   64239                                (iRandom>>8)&0xffffff, iRandom&0xff);
   64240       /* The antipenultimate character of the master journal name must
   64241       ** be "9" to avoid name collisions when using 8+3 filenames. */
   64242       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
   64243       sqlite3FileSuffix3(zMainFile, zMaster);
   64244       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   64245     }while( rc==SQLITE_OK && res );
   64246     if( rc==SQLITE_OK ){
   64247       /* Open the master journal. */
   64248       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
   64249           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   64250           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
   64251       );
   64252     }
   64253     if( rc!=SQLITE_OK ){
   64254       sqlite3DbFree(db, zMaster);
   64255       return rc;
   64256     }
   64257 
   64258     /* Write the name of each database file in the transaction into the new
   64259     ** master journal file. If an error occurs at this point close
   64260     ** and delete the master journal file. All the individual journal files
   64261     ** still have 'null' as the master journal pointer, so they will roll
   64262     ** back independently if a failure occurs.
   64263     */
   64264     for(i=0; i<db->nDb; i++){
   64265       Btree *pBt = db->aDb[i].pBt;
   64266       if( sqlite3BtreeIsInTrans(pBt) ){
   64267         char const *zFile = sqlite3BtreeGetJournalname(pBt);
   64268         if( zFile==0 ){
   64269           continue;  /* Ignore TEMP and :memory: databases */
   64270         }
   64271         assert( zFile[0]!=0 );
   64272         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
   64273           needSync = 1;
   64274         }
   64275         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
   64276         offset += sqlite3Strlen30(zFile)+1;
   64277         if( rc!=SQLITE_OK ){
   64278           sqlite3OsCloseFree(pMaster);
   64279           sqlite3OsDelete(pVfs, zMaster, 0);
   64280           sqlite3DbFree(db, zMaster);
   64281           return rc;
   64282         }
   64283       }
   64284     }
   64285 
   64286     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
   64287     ** flag is set this is not required.
   64288     */
   64289     if( needSync
   64290      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
   64291      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
   64292     ){
   64293       sqlite3OsCloseFree(pMaster);
   64294       sqlite3OsDelete(pVfs, zMaster, 0);
   64295       sqlite3DbFree(db, zMaster);
   64296       return rc;
   64297     }
   64298 
   64299     /* Sync all the db files involved in the transaction. The same call
   64300     ** sets the master journal pointer in each individual journal. If
   64301     ** an error occurs here, do not delete the master journal file.
   64302     **
   64303     ** If the error occurs during the first call to
   64304     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
   64305     ** master journal file will be orphaned. But we cannot delete it,
   64306     ** in case the master journal file name was written into the journal
   64307     ** file before the failure occurred.
   64308     */
   64309     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   64310       Btree *pBt = db->aDb[i].pBt;
   64311       if( pBt ){
   64312         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
   64313       }
   64314     }
   64315     sqlite3OsCloseFree(pMaster);
   64316     assert( rc!=SQLITE_BUSY );
   64317     if( rc!=SQLITE_OK ){
   64318       sqlite3DbFree(db, zMaster);
   64319       return rc;
   64320     }
   64321 
   64322     /* Delete the master journal file. This commits the transaction. After
   64323     ** doing this the directory is synced again before any individual
   64324     ** transaction files are deleted.
   64325     */
   64326     rc = sqlite3OsDelete(pVfs, zMaster, 1);
   64327     sqlite3DbFree(db, zMaster);
   64328     zMaster = 0;
   64329     if( rc ){
   64330       return rc;
   64331     }
   64332 
   64333     /* All files and directories have already been synced, so the following
   64334     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
   64335     ** deleting or truncating journals. If something goes wrong while
   64336     ** this is happening we don't really care. The integrity of the
   64337     ** transaction is already guaranteed, but some stray 'cold' journals
   64338     ** may be lying around. Returning an error code won't help matters.
   64339     */
   64340     disable_simulated_io_errors();
   64341     sqlite3BeginBenignMalloc();
   64342     for(i=0; i<db->nDb; i++){
   64343       Btree *pBt = db->aDb[i].pBt;
   64344       if( pBt ){
   64345         sqlite3BtreeCommitPhaseTwo(pBt, 1);
   64346       }
   64347     }
   64348     sqlite3EndBenignMalloc();
   64349     enable_simulated_io_errors();
   64350 
   64351     sqlite3VtabCommit(db);
   64352   }
   64353 #endif
   64354 
   64355   return rc;
   64356 }
   64357 
   64358 /*
   64359 ** This routine checks that the sqlite3.nVdbeActive count variable
   64360 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
   64361 ** currently active. An assertion fails if the two counts do not match.
   64362 ** This is an internal self-check only - it is not an essential processing
   64363 ** step.
   64364 **
   64365 ** This is a no-op if NDEBUG is defined.
   64366 */
   64367 #ifndef NDEBUG
   64368 static void checkActiveVdbeCnt(sqlite3 *db){
   64369   Vdbe *p;
   64370   int cnt = 0;
   64371   int nWrite = 0;
   64372   int nRead = 0;
   64373   p = db->pVdbe;
   64374   while( p ){
   64375     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
   64376       cnt++;
   64377       if( p->readOnly==0 ) nWrite++;
   64378       if( p->bIsReader ) nRead++;
   64379     }
   64380     p = p->pNext;
   64381   }
   64382   assert( cnt==db->nVdbeActive );
   64383   assert( nWrite==db->nVdbeWrite );
   64384   assert( nRead==db->nVdbeRead );
   64385 }
   64386 #else
   64387 #define checkActiveVdbeCnt(x)
   64388 #endif
   64389 
   64390 /*
   64391 ** If the Vdbe passed as the first argument opened a statement-transaction,
   64392 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
   64393 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
   64394 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
   64395 ** statement transaction is committed.
   64396 **
   64397 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
   64398 ** Otherwise SQLITE_OK.
   64399 */
   64400 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
   64401   sqlite3 *const db = p->db;
   64402   int rc = SQLITE_OK;
   64403 
   64404   /* If p->iStatement is greater than zero, then this Vdbe opened a
   64405   ** statement transaction that should be closed here. The only exception
   64406   ** is that an IO error may have occurred, causing an emergency rollback.
   64407   ** In this case (db->nStatement==0), and there is nothing to do.
   64408   */
   64409   if( db->nStatement && p->iStatement ){
   64410     int i;
   64411     const int iSavepoint = p->iStatement-1;
   64412 
   64413     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
   64414     assert( db->nStatement>0 );
   64415     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
   64416 
   64417     for(i=0; i<db->nDb; i++){
   64418       int rc2 = SQLITE_OK;
   64419       Btree *pBt = db->aDb[i].pBt;
   64420       if( pBt ){
   64421         if( eOp==SAVEPOINT_ROLLBACK ){
   64422           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
   64423         }
   64424         if( rc2==SQLITE_OK ){
   64425           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
   64426         }
   64427         if( rc==SQLITE_OK ){
   64428           rc = rc2;
   64429         }
   64430       }
   64431     }
   64432     db->nStatement--;
   64433     p->iStatement = 0;
   64434 
   64435     if( rc==SQLITE_OK ){
   64436       if( eOp==SAVEPOINT_ROLLBACK ){
   64437         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
   64438       }
   64439       if( rc==SQLITE_OK ){
   64440         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
   64441       }
   64442     }
   64443 
   64444     /* If the statement transaction is being rolled back, also restore the
   64445     ** database handles deferred constraint counter to the value it had when
   64446     ** the statement transaction was opened.  */
   64447     if( eOp==SAVEPOINT_ROLLBACK ){
   64448       db->nDeferredCons = p->nStmtDefCons;
   64449       db->nDeferredImmCons = p->nStmtDefImmCons;
   64450     }
   64451   }
   64452   return rc;
   64453 }
   64454 
   64455 /*
   64456 ** This function is called when a transaction opened by the database
   64457 ** handle associated with the VM passed as an argument is about to be
   64458 ** committed. If there are outstanding deferred foreign key constraint
   64459 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
   64460 **
   64461 ** If there are outstanding FK violations and this function returns
   64462 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
   64463 ** and write an error message to it. Then return SQLITE_ERROR.
   64464 */
   64465 #ifndef SQLITE_OMIT_FOREIGN_KEY
   64466 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
   64467   sqlite3 *db = p->db;
   64468   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
   64469    || (!deferred && p->nFkConstraint>0)
   64470   ){
   64471     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
   64472     p->errorAction = OE_Abort;
   64473     sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
   64474     return SQLITE_ERROR;
   64475   }
   64476   return SQLITE_OK;
   64477 }
   64478 #endif
   64479 
   64480 /*
   64481 ** This routine is called the when a VDBE tries to halt.  If the VDBE
   64482 ** has made changes and is in autocommit mode, then commit those
   64483 ** changes.  If a rollback is needed, then do the rollback.
   64484 **
   64485 ** This routine is the only way to move the state of a VM from
   64486 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
   64487 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
   64488 **
   64489 ** Return an error code.  If the commit could not complete because of
   64490 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
   64491 ** means the close did not happen and needs to be repeated.
   64492 */
   64493 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
   64494   int rc;                         /* Used to store transient return codes */
   64495   sqlite3 *db = p->db;
   64496 
   64497   /* This function contains the logic that determines if a statement or
   64498   ** transaction will be committed or rolled back as a result of the
   64499   ** execution of this virtual machine.
   64500   **
   64501   ** If any of the following errors occur:
   64502   **
   64503   **     SQLITE_NOMEM
   64504   **     SQLITE_IOERR
   64505   **     SQLITE_FULL
   64506   **     SQLITE_INTERRUPT
   64507   **
   64508   ** Then the internal cache might have been left in an inconsistent
   64509   ** state.  We need to rollback the statement transaction, if there is
   64510   ** one, or the complete transaction if there is no statement transaction.
   64511   */
   64512 
   64513   if( p->db->mallocFailed ){
   64514     p->rc = SQLITE_NOMEM;
   64515   }
   64516   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
   64517   closeAllCursors(p);
   64518   if( p->magic!=VDBE_MAGIC_RUN ){
   64519     return SQLITE_OK;
   64520   }
   64521   checkActiveVdbeCnt(db);
   64522 
   64523   /* No commit or rollback needed if the program never started or if the
   64524   ** SQL statement does not read or write a database file.  */
   64525   if( p->pc>=0 && p->bIsReader ){
   64526     int mrc;   /* Primary error code from p->rc */
   64527     int eStatementOp = 0;
   64528     int isSpecialError;            /* Set to true if a 'special' error */
   64529 
   64530     /* Lock all btrees used by the statement */
   64531     sqlite3VdbeEnter(p);
   64532 
   64533     /* Check for one of the special errors */
   64534     mrc = p->rc & 0xff;
   64535     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
   64536                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
   64537     if( isSpecialError ){
   64538       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
   64539       ** no rollback is necessary. Otherwise, at least a savepoint
   64540       ** transaction must be rolled back to restore the database to a
   64541       ** consistent state.
   64542       **
   64543       ** Even if the statement is read-only, it is important to perform
   64544       ** a statement or transaction rollback operation. If the error
   64545       ** occurred while writing to the journal, sub-journal or database
   64546       ** file as part of an effort to free up cache space (see function
   64547       ** pagerStress() in pager.c), the rollback is required to restore
   64548       ** the pager to a consistent state.
   64549       */
   64550       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
   64551         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
   64552           eStatementOp = SAVEPOINT_ROLLBACK;
   64553         }else{
   64554           /* We are forced to roll back the active transaction. Before doing
   64555           ** so, abort any other statements this handle currently has active.
   64556           */
   64557           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   64558           sqlite3CloseSavepoints(db);
   64559           db->autoCommit = 1;
   64560         }
   64561       }
   64562     }
   64563 
   64564     /* Check for immediate foreign key violations. */
   64565     if( p->rc==SQLITE_OK ){
   64566       sqlite3VdbeCheckFk(p, 0);
   64567     }
   64568 
   64569     /* If the auto-commit flag is set and this is the only active writer
   64570     ** VM, then we do either a commit or rollback of the current transaction.
   64571     **
   64572     ** Note: This block also runs if one of the special errors handled
   64573     ** above has occurred.
   64574     */
   64575     if( !sqlite3VtabInSync(db)
   64576      && db->autoCommit
   64577      && db->nVdbeWrite==(p->readOnly==0)
   64578     ){
   64579       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
   64580         rc = sqlite3VdbeCheckFk(p, 1);
   64581         if( rc!=SQLITE_OK ){
   64582           if( NEVER(p->readOnly) ){
   64583             sqlite3VdbeLeave(p);
   64584             return SQLITE_ERROR;
   64585           }
   64586           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
   64587         }else{
   64588           /* The auto-commit flag is true, the vdbe program was successful
   64589           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
   64590           ** key constraints to hold up the transaction. This means a commit
   64591           ** is required. */
   64592           rc = vdbeCommit(db, p);
   64593         }
   64594         if( rc==SQLITE_BUSY && p->readOnly ){
   64595           sqlite3VdbeLeave(p);
   64596           return SQLITE_BUSY;
   64597         }else if( rc!=SQLITE_OK ){
   64598           p->rc = rc;
   64599           sqlite3RollbackAll(db, SQLITE_OK);
   64600         }else{
   64601           db->nDeferredCons = 0;
   64602           db->nDeferredImmCons = 0;
   64603           db->flags &= ~SQLITE_DeferFKs;
   64604           sqlite3CommitInternalChanges(db);
   64605         }
   64606       }else{
   64607         sqlite3RollbackAll(db, SQLITE_OK);
   64608       }
   64609       db->nStatement = 0;
   64610     }else if( eStatementOp==0 ){
   64611       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
   64612         eStatementOp = SAVEPOINT_RELEASE;
   64613       }else if( p->errorAction==OE_Abort ){
   64614         eStatementOp = SAVEPOINT_ROLLBACK;
   64615       }else{
   64616         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   64617         sqlite3CloseSavepoints(db);
   64618         db->autoCommit = 1;
   64619       }
   64620     }
   64621 
   64622     /* If eStatementOp is non-zero, then a statement transaction needs to
   64623     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
   64624     ** do so. If this operation returns an error, and the current statement
   64625     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
   64626     ** current statement error code.
   64627     */
   64628     if( eStatementOp ){
   64629       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
   64630       if( rc ){
   64631         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
   64632           p->rc = rc;
   64633           sqlite3DbFree(db, p->zErrMsg);
   64634           p->zErrMsg = 0;
   64635         }
   64636         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   64637         sqlite3CloseSavepoints(db);
   64638         db->autoCommit = 1;
   64639       }
   64640     }
   64641 
   64642     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
   64643     ** has been rolled back, update the database connection change-counter.
   64644     */
   64645     if( p->changeCntOn ){
   64646       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
   64647         sqlite3VdbeSetChanges(db, p->nChange);
   64648       }else{
   64649         sqlite3VdbeSetChanges(db, 0);
   64650       }
   64651       p->nChange = 0;
   64652     }
   64653 
   64654     /* Release the locks */
   64655     sqlite3VdbeLeave(p);
   64656   }
   64657 
   64658   /* We have successfully halted and closed the VM.  Record this fact. */
   64659   if( p->pc>=0 ){
   64660     db->nVdbeActive--;
   64661     if( !p->readOnly ) db->nVdbeWrite--;
   64662     if( p->bIsReader ) db->nVdbeRead--;
   64663     assert( db->nVdbeActive>=db->nVdbeRead );
   64664     assert( db->nVdbeRead>=db->nVdbeWrite );
   64665     assert( db->nVdbeWrite>=0 );
   64666   }
   64667   p->magic = VDBE_MAGIC_HALT;
   64668   checkActiveVdbeCnt(db);
   64669   if( p->db->mallocFailed ){
   64670     p->rc = SQLITE_NOMEM;
   64671   }
   64672 
   64673   /* If the auto-commit flag is set to true, then any locks that were held
   64674   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
   64675   ** to invoke any required unlock-notify callbacks.
   64676   */
   64677   if( db->autoCommit ){
   64678     sqlite3ConnectionUnlocked(db);
   64679   }
   64680 
   64681   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
   64682   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
   64683 }
   64684 
   64685 
   64686 /*
   64687 ** Each VDBE holds the result of the most recent sqlite3_step() call
   64688 ** in p->rc.  This routine sets that result back to SQLITE_OK.
   64689 */
   64690 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
   64691   p->rc = SQLITE_OK;
   64692 }
   64693 
   64694 /*
   64695 ** Copy the error code and error message belonging to the VDBE passed
   64696 ** as the first argument to its database handle (so that they will be
   64697 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
   64698 **
   64699 ** This function does not clear the VDBE error code or message, just
   64700 ** copies them to the database handle.
   64701 */
   64702 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
   64703   sqlite3 *db = p->db;
   64704   int rc = p->rc;
   64705   if( p->zErrMsg ){
   64706     u8 mallocFailed = db->mallocFailed;
   64707     sqlite3BeginBenignMalloc();
   64708     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
   64709     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   64710     sqlite3EndBenignMalloc();
   64711     db->mallocFailed = mallocFailed;
   64712     db->errCode = rc;
   64713   }else{
   64714     sqlite3Error(db, rc, 0);
   64715   }
   64716   return rc;
   64717 }
   64718 
   64719 #ifdef SQLITE_ENABLE_SQLLOG
   64720 /*
   64721 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
   64722 ** invoke it.
   64723 */
   64724 static void vdbeInvokeSqllog(Vdbe *v){
   64725   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
   64726     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
   64727     assert( v->db->init.busy==0 );
   64728     if( zExpanded ){
   64729       sqlite3GlobalConfig.xSqllog(
   64730           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
   64731       );
   64732       sqlite3DbFree(v->db, zExpanded);
   64733     }
   64734   }
   64735 }
   64736 #else
   64737 # define vdbeInvokeSqllog(x)
   64738 #endif
   64739 
   64740 /*
   64741 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
   64742 ** Write any error messages into *pzErrMsg.  Return the result code.
   64743 **
   64744 ** After this routine is run, the VDBE should be ready to be executed
   64745 ** again.
   64746 **
   64747 ** To look at it another way, this routine resets the state of the
   64748 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
   64749 ** VDBE_MAGIC_INIT.
   64750 */
   64751 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   64752   sqlite3 *db;
   64753   db = p->db;
   64754 
   64755   /* If the VM did not run to completion or if it encountered an
   64756   ** error, then it might not have been halted properly.  So halt
   64757   ** it now.
   64758   */
   64759   sqlite3VdbeHalt(p);
   64760 
   64761   /* If the VDBE has be run even partially, then transfer the error code
   64762   ** and error message from the VDBE into the main database structure.  But
   64763   ** if the VDBE has just been set to run but has not actually executed any
   64764   ** instructions yet, leave the main database error information unchanged.
   64765   */
   64766   if( p->pc>=0 ){
   64767     vdbeInvokeSqllog(p);
   64768     sqlite3VdbeTransferError(p);
   64769     sqlite3DbFree(db, p->zErrMsg);
   64770     p->zErrMsg = 0;
   64771     if( p->runOnlyOnce ) p->expired = 1;
   64772   }else if( p->rc && p->expired ){
   64773     /* The expired flag was set on the VDBE before the first call
   64774     ** to sqlite3_step(). For consistency (since sqlite3_step() was
   64775     ** called), set the database error in this case as well.
   64776     */
   64777     sqlite3Error(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
   64778     sqlite3DbFree(db, p->zErrMsg);
   64779     p->zErrMsg = 0;
   64780   }
   64781 
   64782   /* Reclaim all memory used by the VDBE
   64783   */
   64784   Cleanup(p);
   64785 
   64786   /* Save profiling information from this VDBE run.
   64787   */
   64788 #ifdef VDBE_PROFILE
   64789   {
   64790     FILE *out = fopen("vdbe_profile.out", "a");
   64791     if( out ){
   64792       int i;
   64793       fprintf(out, "---- ");
   64794       for(i=0; i<p->nOp; i++){
   64795         fprintf(out, "%02x", p->aOp[i].opcode);
   64796       }
   64797       fprintf(out, "\n");
   64798       if( p->zSql ){
   64799         char c, pc = 0;
   64800         fprintf(out, "-- ");
   64801         for(i=0; (c = p->zSql[i])!=0; i++){
   64802           if( pc=='\n' ) fprintf(out, "-- ");
   64803           putc(c, out);
   64804           pc = c;
   64805         }
   64806         if( pc!='\n' ) fprintf(out, "\n");
   64807       }
   64808       for(i=0; i<p->nOp; i++){
   64809         char zHdr[100];
   64810         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
   64811            p->aOp[i].cnt,
   64812            p->aOp[i].cycles,
   64813            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
   64814         );
   64815         fprintf(out, "%s", zHdr);
   64816         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
   64817       }
   64818       fclose(out);
   64819     }
   64820   }
   64821 #endif
   64822   p->iCurrentTime = 0;
   64823   p->magic = VDBE_MAGIC_INIT;
   64824   return p->rc & db->errMask;
   64825 }
   64826 
   64827 /*
   64828 ** Clean up and delete a VDBE after execution.  Return an integer which is
   64829 ** the result code.  Write any error message text into *pzErrMsg.
   64830 */
   64831 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
   64832   int rc = SQLITE_OK;
   64833   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
   64834     rc = sqlite3VdbeReset(p);
   64835     assert( (rc & p->db->errMask)==rc );
   64836   }
   64837   sqlite3VdbeDelete(p);
   64838   return rc;
   64839 }
   64840 
   64841 /*
   64842 ** If parameter iOp is less than zero, then invoke the destructor for
   64843 ** all auxiliary data pointers currently cached by the VM passed as
   64844 ** the first argument.
   64845 **
   64846 ** Or, if iOp is greater than or equal to zero, then the destructor is
   64847 ** only invoked for those auxiliary data pointers created by the user
   64848 ** function invoked by the OP_Function opcode at instruction iOp of
   64849 ** VM pVdbe, and only then if:
   64850 **
   64851 **    * the associated function parameter is the 32nd or later (counting
   64852 **      from left to right), or
   64853 **
   64854 **    * the corresponding bit in argument mask is clear (where the first
   64855 **      function parameter corrsponds to bit 0 etc.).
   64856 */
   64857 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
   64858   AuxData **pp = &pVdbe->pAuxData;
   64859   while( *pp ){
   64860     AuxData *pAux = *pp;
   64861     if( (iOp<0)
   64862      || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
   64863     ){
   64864       testcase( pAux->iArg==31 );
   64865       if( pAux->xDelete ){
   64866         pAux->xDelete(pAux->pAux);
   64867       }
   64868       *pp = pAux->pNext;
   64869       sqlite3DbFree(pVdbe->db, pAux);
   64870     }else{
   64871       pp= &pAux->pNext;
   64872     }
   64873   }
   64874 }
   64875 
   64876 /*
   64877 ** Free all memory associated with the Vdbe passed as the second argument,
   64878 ** except for object itself, which is preserved.
   64879 **
   64880 ** The difference between this function and sqlite3VdbeDelete() is that
   64881 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
   64882 ** the database connection and frees the object itself.
   64883 */
   64884 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
   64885   SubProgram *pSub, *pNext;
   64886   int i;
   64887   assert( p->db==0 || p->db==db );
   64888   releaseMemArray(p->aVar, p->nVar);
   64889   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   64890   for(pSub=p->pProgram; pSub; pSub=pNext){
   64891     pNext = pSub->pNext;
   64892     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
   64893     sqlite3DbFree(db, pSub);
   64894   }
   64895   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
   64896   vdbeFreeOpArray(db, p->aOp, p->nOp);
   64897   sqlite3DbFree(db, p->aColName);
   64898   sqlite3DbFree(db, p->zSql);
   64899   sqlite3DbFree(db, p->pFree);
   64900 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   64901   sqlite3DbFree(db, p->zExplain);
   64902   sqlite3DbFree(db, p->pExplain);
   64903 #endif
   64904 }
   64905 
   64906 /*
   64907 ** Delete an entire VDBE.
   64908 */
   64909 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
   64910   sqlite3 *db;
   64911 
   64912   if( NEVER(p==0) ) return;
   64913   db = p->db;
   64914   assert( sqlite3_mutex_held(db->mutex) );
   64915   sqlite3VdbeClearObject(db, p);
   64916   if( p->pPrev ){
   64917     p->pPrev->pNext = p->pNext;
   64918   }else{
   64919     assert( db->pVdbe==p );
   64920     db->pVdbe = p->pNext;
   64921   }
   64922   if( p->pNext ){
   64923     p->pNext->pPrev = p->pPrev;
   64924   }
   64925   p->magic = VDBE_MAGIC_DEAD;
   64926   p->db = 0;
   64927   sqlite3DbFree(db, p);
   64928 }
   64929 
   64930 /*
   64931 ** Make sure the cursor p is ready to read or write the row to which it
   64932 ** was last positioned.  Return an error code if an OOM fault or I/O error
   64933 ** prevents us from positioning the cursor to its correct position.
   64934 **
   64935 ** If a MoveTo operation is pending on the given cursor, then do that
   64936 ** MoveTo now.  If no move is pending, check to see if the row has been
   64937 ** deleted out from under the cursor and if it has, mark the row as
   64938 ** a NULL row.
   64939 **
   64940 ** If the cursor is already pointing to the correct row and that row has
   64941 ** not been deleted out from under the cursor, then this routine is a no-op.
   64942 */
   64943 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
   64944   if( p->deferredMoveto ){
   64945     int res, rc;
   64946 #ifdef SQLITE_TEST
   64947     extern int sqlite3_search_count;
   64948 #endif
   64949     assert( p->isTable );
   64950     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
   64951     if( rc ) return rc;
   64952     p->lastRowid = p->movetoTarget;
   64953     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
   64954     p->rowidIsValid = 1;
   64955 #ifdef SQLITE_TEST
   64956     sqlite3_search_count++;
   64957 #endif
   64958     p->deferredMoveto = 0;
   64959     p->cacheStatus = CACHE_STALE;
   64960   }else if( p->pCursor ){
   64961     int hasMoved;
   64962     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
   64963     if( rc ) return rc;
   64964     if( hasMoved ){
   64965       p->cacheStatus = CACHE_STALE;
   64966       if( hasMoved==2 ) p->nullRow = 1;
   64967     }
   64968   }
   64969   return SQLITE_OK;
   64970 }
   64971 
   64972 /*
   64973 ** The following functions:
   64974 **
   64975 ** sqlite3VdbeSerialType()
   64976 ** sqlite3VdbeSerialTypeLen()
   64977 ** sqlite3VdbeSerialLen()
   64978 ** sqlite3VdbeSerialPut()
   64979 ** sqlite3VdbeSerialGet()
   64980 **
   64981 ** encapsulate the code that serializes values for storage in SQLite
   64982 ** data and index records. Each serialized value consists of a
   64983 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
   64984 ** integer, stored as a varint.
   64985 **
   64986 ** In an SQLite index record, the serial type is stored directly before
   64987 ** the blob of data that it corresponds to. In a table record, all serial
   64988 ** types are stored at the start of the record, and the blobs of data at
   64989 ** the end. Hence these functions allow the caller to handle the
   64990 ** serial-type and data blob separately.
   64991 **
   64992 ** The following table describes the various storage classes for data:
   64993 **
   64994 **   serial type        bytes of data      type
   64995 **   --------------     ---------------    ---------------
   64996 **      0                     0            NULL
   64997 **      1                     1            signed integer
   64998 **      2                     2            signed integer
   64999 **      3                     3            signed integer
   65000 **      4                     4            signed integer
   65001 **      5                     6            signed integer
   65002 **      6                     8            signed integer
   65003 **      7                     8            IEEE float
   65004 **      8                     0            Integer constant 0
   65005 **      9                     0            Integer constant 1
   65006 **     10,11                               reserved for expansion
   65007 **    N>=12 and even       (N-12)/2        BLOB
   65008 **    N>=13 and odd        (N-13)/2        text
   65009 **
   65010 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
   65011 ** of SQLite will not understand those serial types.
   65012 */
   65013 
   65014 /*
   65015 ** Return the serial-type for the value stored in pMem.
   65016 */
   65017 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
   65018   int flags = pMem->flags;
   65019   u32 n;
   65020 
   65021   if( flags&MEM_Null ){
   65022     return 0;
   65023   }
   65024   if( flags&MEM_Int ){
   65025     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
   65026 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
   65027     i64 i = pMem->u.i;
   65028     u64 u;
   65029     if( i<0 ){
   65030       if( i<(-MAX_6BYTE) ) return 6;
   65031       /* Previous test prevents:  u = -(-9223372036854775808) */
   65032       u = -i;
   65033     }else{
   65034       u = i;
   65035     }
   65036     if( u<=127 ){
   65037       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
   65038     }
   65039     if( u<=32767 ) return 2;
   65040     if( u<=8388607 ) return 3;
   65041     if( u<=2147483647 ) return 4;
   65042     if( u<=MAX_6BYTE ) return 5;
   65043     return 6;
   65044   }
   65045   if( flags&MEM_Real ){
   65046     return 7;
   65047   }
   65048   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
   65049   assert( pMem->n>=0 );
   65050   n = (u32)pMem->n;
   65051   if( flags & MEM_Zero ){
   65052     n += pMem->u.nZero;
   65053   }
   65054   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
   65055 }
   65056 
   65057 /*
   65058 ** Return the length of the data corresponding to the supplied serial-type.
   65059 */
   65060 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
   65061   if( serial_type>=12 ){
   65062     return (serial_type-12)/2;
   65063   }else{
   65064     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
   65065     return aSize[serial_type];
   65066   }
   65067 }
   65068 
   65069 /*
   65070 ** If we are on an architecture with mixed-endian floating
   65071 ** points (ex: ARM7) then swap the lower 4 bytes with the
   65072 ** upper 4 bytes.  Return the result.
   65073 **
   65074 ** For most architectures, this is a no-op.
   65075 **
   65076 ** (later):  It is reported to me that the mixed-endian problem
   65077 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
   65078 ** that early versions of GCC stored the two words of a 64-bit
   65079 ** float in the wrong order.  And that error has been propagated
   65080 ** ever since.  The blame is not necessarily with GCC, though.
   65081 ** GCC might have just copying the problem from a prior compiler.
   65082 ** I am also told that newer versions of GCC that follow a different
   65083 ** ABI get the byte order right.
   65084 **
   65085 ** Developers using SQLite on an ARM7 should compile and run their
   65086 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
   65087 ** enabled, some asserts below will ensure that the byte order of
   65088 ** floating point values is correct.
   65089 **
   65090 ** (2007-08-30)  Frank van Vugt has studied this problem closely
   65091 ** and has send his findings to the SQLite developers.  Frank
   65092 ** writes that some Linux kernels offer floating point hardware
   65093 ** emulation that uses only 32-bit mantissas instead of a full
   65094 ** 48-bits as required by the IEEE standard.  (This is the
   65095 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
   65096 ** byte swapping becomes very complicated.  To avoid problems,
   65097 ** the necessary byte swapping is carried out using a 64-bit integer
   65098 ** rather than a 64-bit float.  Frank assures us that the code here
   65099 ** works for him.  We, the developers, have no way to independently
   65100 ** verify this, but Frank seems to know what he is talking about
   65101 ** so we trust him.
   65102 */
   65103 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   65104 static u64 floatSwap(u64 in){
   65105   union {
   65106     u64 r;
   65107     u32 i[2];
   65108   } u;
   65109   u32 t;
   65110 
   65111   u.r = in;
   65112   t = u.i[0];
   65113   u.i[0] = u.i[1];
   65114   u.i[1] = t;
   65115   return u.r;
   65116 }
   65117 # define swapMixedEndianFloat(X)  X = floatSwap(X)
   65118 #else
   65119 # define swapMixedEndianFloat(X)
   65120 #endif
   65121 
   65122 /*
   65123 ** Write the serialized data blob for the value stored in pMem into
   65124 ** buf. It is assumed that the caller has allocated sufficient space.
   65125 ** Return the number of bytes written.
   65126 **
   65127 ** nBuf is the amount of space left in buf[].  The caller is responsible
   65128 ** for allocating enough space to buf[] to hold the entire field, exclusive
   65129 ** of the pMem->u.nZero bytes for a MEM_Zero value.
   65130 **
   65131 ** Return the number of bytes actually written into buf[].  The number
   65132 ** of bytes in the zero-filled tail is included in the return value only
   65133 ** if those bytes were zeroed in buf[].
   65134 */
   65135 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
   65136   u32 len;
   65137 
   65138   /* Integer and Real */
   65139   if( serial_type<=7 && serial_type>0 ){
   65140     u64 v;
   65141     u32 i;
   65142     if( serial_type==7 ){
   65143       assert( sizeof(v)==sizeof(pMem->r) );
   65144       memcpy(&v, &pMem->r, sizeof(v));
   65145       swapMixedEndianFloat(v);
   65146     }else{
   65147       v = pMem->u.i;
   65148     }
   65149     len = i = sqlite3VdbeSerialTypeLen(serial_type);
   65150     while( i-- ){
   65151       buf[i] = (u8)(v&0xFF);
   65152       v >>= 8;
   65153     }
   65154     return len;
   65155   }
   65156 
   65157   /* String or blob */
   65158   if( serial_type>=12 ){
   65159     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
   65160              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
   65161     len = pMem->n;
   65162     memcpy(buf, pMem->z, len);
   65163     return len;
   65164   }
   65165 
   65166   /* NULL or constants 0 or 1 */
   65167   return 0;
   65168 }
   65169 
   65170 /* Input "x" is a sequence of unsigned characters that represent a
   65171 ** big-endian integer.  Return the equivalent native integer
   65172 */
   65173 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
   65174 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
   65175 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
   65176 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
   65177 
   65178 /*
   65179 ** Deserialize the data blob pointed to by buf as serial type serial_type
   65180 ** and store the result in pMem.  Return the number of bytes read.
   65181 */
   65182 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
   65183   const unsigned char *buf,     /* Buffer to deserialize from */
   65184   u32 serial_type,              /* Serial type to deserialize */
   65185   Mem *pMem                     /* Memory cell to write value into */
   65186 ){
   65187   u64 x;
   65188   u32 y;
   65189   switch( serial_type ){
   65190     case 10:   /* Reserved for future use */
   65191     case 11:   /* Reserved for future use */
   65192     case 0: {  /* NULL */
   65193       pMem->flags = MEM_Null;
   65194       break;
   65195     }
   65196     case 1: { /* 1-byte signed integer */
   65197       pMem->u.i = ONE_BYTE_INT(buf);
   65198       pMem->flags = MEM_Int;
   65199       testcase( pMem->u.i<0 );
   65200       return 1;
   65201     }
   65202     case 2: { /* 2-byte signed integer */
   65203       pMem->u.i = TWO_BYTE_INT(buf);
   65204       pMem->flags = MEM_Int;
   65205       testcase( pMem->u.i<0 );
   65206       return 2;
   65207     }
   65208     case 3: { /* 3-byte signed integer */
   65209       pMem->u.i = THREE_BYTE_INT(buf);
   65210       pMem->flags = MEM_Int;
   65211       testcase( pMem->u.i<0 );
   65212       return 3;
   65213     }
   65214     case 4: { /* 4-byte signed integer */
   65215       y = FOUR_BYTE_UINT(buf);
   65216       pMem->u.i = (i64)*(int*)&y;
   65217       pMem->flags = MEM_Int;
   65218       testcase( pMem->u.i<0 );
   65219       return 4;
   65220     }
   65221     case 5: { /* 6-byte signed integer */
   65222       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
   65223       pMem->flags = MEM_Int;
   65224       testcase( pMem->u.i<0 );
   65225       return 6;
   65226     }
   65227     case 6:   /* 8-byte signed integer */
   65228     case 7: { /* IEEE floating point */
   65229 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
   65230       /* Verify that integers and floating point values use the same
   65231       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
   65232       ** defined that 64-bit floating point values really are mixed
   65233       ** endian.
   65234       */
   65235       static const u64 t1 = ((u64)0x3ff00000)<<32;
   65236       static const double r1 = 1.0;
   65237       u64 t2 = t1;
   65238       swapMixedEndianFloat(t2);
   65239       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
   65240 #endif
   65241       x = FOUR_BYTE_UINT(buf);
   65242       y = FOUR_BYTE_UINT(buf+4);
   65243       x = (x<<32) | y;
   65244       if( serial_type==6 ){
   65245         pMem->u.i = *(i64*)&x;
   65246         pMem->flags = MEM_Int;
   65247         testcase( pMem->u.i<0 );
   65248       }else{
   65249         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
   65250         swapMixedEndianFloat(x);
   65251         memcpy(&pMem->r, &x, sizeof(x));
   65252         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
   65253       }
   65254       return 8;
   65255     }
   65256     case 8:    /* Integer 0 */
   65257     case 9: {  /* Integer 1 */
   65258       pMem->u.i = serial_type-8;
   65259       pMem->flags = MEM_Int;
   65260       return 0;
   65261     }
   65262     default: {
   65263       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
   65264       u32 len = (serial_type-12)/2;
   65265       pMem->z = (char *)buf;
   65266       pMem->n = len;
   65267       pMem->xDel = 0;
   65268       pMem->flags = aFlag[serial_type&1];
   65269       return len;
   65270     }
   65271   }
   65272   return 0;
   65273 }
   65274 
   65275 /*
   65276 ** This routine is used to allocate sufficient space for an UnpackedRecord
   65277 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
   65278 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
   65279 **
   65280 ** The space is either allocated using sqlite3DbMallocRaw() or from within
   65281 ** the unaligned buffer passed via the second and third arguments (presumably
   65282 ** stack space). If the former, then *ppFree is set to a pointer that should
   65283 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
   65284 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
   65285 ** before returning.
   65286 **
   65287 ** If an OOM error occurs, NULL is returned.
   65288 */
   65289 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
   65290   KeyInfo *pKeyInfo,              /* Description of the record */
   65291   char *pSpace,                   /* Unaligned space available */
   65292   int szSpace,                    /* Size of pSpace[] in bytes */
   65293   char **ppFree                   /* OUT: Caller should free this pointer */
   65294 ){
   65295   UnpackedRecord *p;              /* Unpacked record to return */
   65296   int nOff;                       /* Increment pSpace by nOff to align it */
   65297   int nByte;                      /* Number of bytes required for *p */
   65298 
   65299   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
   65300   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
   65301   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
   65302   */
   65303   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
   65304   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
   65305   if( nByte>szSpace+nOff ){
   65306     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
   65307     *ppFree = (char *)p;
   65308     if( !p ) return 0;
   65309   }else{
   65310     p = (UnpackedRecord*)&pSpace[nOff];
   65311     *ppFree = 0;
   65312   }
   65313 
   65314   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
   65315   assert( pKeyInfo->aSortOrder!=0 );
   65316   p->pKeyInfo = pKeyInfo;
   65317   p->nField = pKeyInfo->nField + 1;
   65318   return p;
   65319 }
   65320 
   65321 /*
   65322 ** Given the nKey-byte encoding of a record in pKey[], populate the
   65323 ** UnpackedRecord structure indicated by the fourth argument with the
   65324 ** contents of the decoded record.
   65325 */
   65326 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
   65327   KeyInfo *pKeyInfo,     /* Information about the record format */
   65328   int nKey,              /* Size of the binary record */
   65329   const void *pKey,      /* The binary record */
   65330   UnpackedRecord *p      /* Populate this structure before returning. */
   65331 ){
   65332   const unsigned char *aKey = (const unsigned char *)pKey;
   65333   int d;
   65334   u32 idx;                        /* Offset in aKey[] to read from */
   65335   u16 u;                          /* Unsigned loop counter */
   65336   u32 szHdr;
   65337   Mem *pMem = p->aMem;
   65338 
   65339   p->default_rc = 0;
   65340   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   65341   idx = getVarint32(aKey, szHdr);
   65342   d = szHdr;
   65343   u = 0;
   65344   while( idx<szHdr && u<p->nField && d<=nKey ){
   65345     u32 serial_type;
   65346 
   65347     idx += getVarint32(&aKey[idx], serial_type);
   65348     pMem->enc = pKeyInfo->enc;
   65349     pMem->db = pKeyInfo->db;
   65350     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
   65351     pMem->zMalloc = 0;
   65352     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
   65353     pMem++;
   65354     u++;
   65355   }
   65356   assert( u<=pKeyInfo->nField + 1 );
   65357   p->nField = u;
   65358 }
   65359 
   65360 #if SQLITE_DEBUG
   65361 /*
   65362 ** This function compares two index or table record keys in the same way
   65363 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
   65364 ** this function deserializes and compares values using the
   65365 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
   65366 ** in assert() statements to ensure that the optimized code in
   65367 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
   65368 */
   65369 static int vdbeRecordCompareDebug(
   65370   int nKey1, const void *pKey1, /* Left key */
   65371   const UnpackedRecord *pPKey2  /* Right key */
   65372 ){
   65373   u32 d1;            /* Offset into aKey[] of next data element */
   65374   u32 idx1;          /* Offset into aKey[] of next header element */
   65375   u32 szHdr1;        /* Number of bytes in header */
   65376   int i = 0;
   65377   int rc = 0;
   65378   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   65379   KeyInfo *pKeyInfo;
   65380   Mem mem1;
   65381 
   65382   pKeyInfo = pPKey2->pKeyInfo;
   65383   mem1.enc = pKeyInfo->enc;
   65384   mem1.db = pKeyInfo->db;
   65385   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
   65386   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
   65387 
   65388   /* Compilers may complain that mem1.u.i is potentially uninitialized.
   65389   ** We could initialize it, as shown here, to silence those complaints.
   65390   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
   65391   ** the unnecessary initialization has a measurable negative performance
   65392   ** impact, since this routine is a very high runner.  And so, we choose
   65393   ** to ignore the compiler warnings and leave this variable uninitialized.
   65394   */
   65395   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
   65396 
   65397   idx1 = getVarint32(aKey1, szHdr1);
   65398   d1 = szHdr1;
   65399   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
   65400   assert( pKeyInfo->aSortOrder!=0 );
   65401   assert( pKeyInfo->nField>0 );
   65402   assert( idx1<=szHdr1 || CORRUPT_DB );
   65403   do{
   65404     u32 serial_type1;
   65405 
   65406     /* Read the serial types for the next element in each key. */
   65407     idx1 += getVarint32( aKey1+idx1, serial_type1 );
   65408 
   65409     /* Verify that there is enough key space remaining to avoid
   65410     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
   65411     ** always be greater than or equal to the amount of required key space.
   65412     ** Use that approximation to avoid the more expensive call to
   65413     ** sqlite3VdbeSerialTypeLen() in the common case.
   65414     */
   65415     if( d1+serial_type1+2>(u32)nKey1
   65416      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
   65417     ){
   65418       break;
   65419     }
   65420 
   65421     /* Extract the values to be compared.
   65422     */
   65423     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
   65424 
   65425     /* Do the comparison
   65426     */
   65427     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
   65428     if( rc!=0 ){
   65429       assert( mem1.zMalloc==0 );  /* See comment below */
   65430       if( pKeyInfo->aSortOrder[i] ){
   65431         rc = -rc;  /* Invert the result for DESC sort order. */
   65432       }
   65433       return rc;
   65434     }
   65435     i++;
   65436   }while( idx1<szHdr1 && i<pPKey2->nField );
   65437 
   65438   /* No memory allocation is ever used on mem1.  Prove this using
   65439   ** the following assert().  If the assert() fails, it indicates a
   65440   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
   65441   */
   65442   assert( mem1.zMalloc==0 );
   65443 
   65444   /* rc==0 here means that one of the keys ran out of fields and
   65445   ** all the fields up to that point were equal. Return the the default_rc
   65446   ** value.  */
   65447   return pPKey2->default_rc;
   65448 }
   65449 #endif
   65450 
   65451 /*
   65452 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
   65453 ** using the collation sequence pColl. As usual, return a negative , zero
   65454 ** or positive value if *pMem1 is less than, equal to or greater than
   65455 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
   65456 */
   65457 static int vdbeCompareMemString(
   65458   const Mem *pMem1,
   65459   const Mem *pMem2,
   65460   const CollSeq *pColl
   65461 ){
   65462   if( pMem1->enc==pColl->enc ){
   65463     /* The strings are already in the correct encoding.  Call the
   65464      ** comparison function directly */
   65465     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
   65466   }else{
   65467     int rc;
   65468     const void *v1, *v2;
   65469     int n1, n2;
   65470     Mem c1;
   65471     Mem c2;
   65472     memset(&c1, 0, sizeof(c1));
   65473     memset(&c2, 0, sizeof(c2));
   65474     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
   65475     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
   65476     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
   65477     n1 = v1==0 ? 0 : c1.n;
   65478     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
   65479     n2 = v2==0 ? 0 : c2.n;
   65480     rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
   65481     sqlite3VdbeMemRelease(&c1);
   65482     sqlite3VdbeMemRelease(&c2);
   65483     return rc;
   65484   }
   65485 }
   65486 
   65487 /*
   65488 ** Compare the values contained by the two memory cells, returning
   65489 ** negative, zero or positive if pMem1 is less than, equal to, or greater
   65490 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
   65491 ** and reals) sorted numerically, followed by text ordered by the collating
   65492 ** sequence pColl and finally blob's ordered by memcmp().
   65493 **
   65494 ** Two NULL values are considered equal by this function.
   65495 */
   65496 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
   65497   int rc;
   65498   int f1, f2;
   65499   int combined_flags;
   65500 
   65501   f1 = pMem1->flags;
   65502   f2 = pMem2->flags;
   65503   combined_flags = f1|f2;
   65504   assert( (combined_flags & MEM_RowSet)==0 );
   65505 
   65506   /* If one value is NULL, it is less than the other. If both values
   65507   ** are NULL, return 0.
   65508   */
   65509   if( combined_flags&MEM_Null ){
   65510     return (f2&MEM_Null) - (f1&MEM_Null);
   65511   }
   65512 
   65513   /* If one value is a number and the other is not, the number is less.
   65514   ** If both are numbers, compare as reals if one is a real, or as integers
   65515   ** if both values are integers.
   65516   */
   65517   if( combined_flags&(MEM_Int|MEM_Real) ){
   65518     double r1, r2;
   65519     if( (f1 & f2 & MEM_Int)!=0 ){
   65520       if( pMem1->u.i < pMem2->u.i ) return -1;
   65521       if( pMem1->u.i > pMem2->u.i ) return 1;
   65522       return 0;
   65523     }
   65524     if( (f1&MEM_Real)!=0 ){
   65525       r1 = pMem1->r;
   65526     }else if( (f1&MEM_Int)!=0 ){
   65527       r1 = (double)pMem1->u.i;
   65528     }else{
   65529       return 1;
   65530     }
   65531     if( (f2&MEM_Real)!=0 ){
   65532       r2 = pMem2->r;
   65533     }else if( (f2&MEM_Int)!=0 ){
   65534       r2 = (double)pMem2->u.i;
   65535     }else{
   65536       return -1;
   65537     }
   65538     if( r1<r2 ) return -1;
   65539     if( r1>r2 ) return 1;
   65540     return 0;
   65541   }
   65542 
   65543   /* If one value is a string and the other is a blob, the string is less.
   65544   ** If both are strings, compare using the collating functions.
   65545   */
   65546   if( combined_flags&MEM_Str ){
   65547     if( (f1 & MEM_Str)==0 ){
   65548       return 1;
   65549     }
   65550     if( (f2 & MEM_Str)==0 ){
   65551       return -1;
   65552     }
   65553 
   65554     assert( pMem1->enc==pMem2->enc );
   65555     assert( pMem1->enc==SQLITE_UTF8 ||
   65556             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
   65557 
   65558     /* The collation sequence must be defined at this point, even if
   65559     ** the user deletes the collation sequence after the vdbe program is
   65560     ** compiled (this was not always the case).
   65561     */
   65562     assert( !pColl || pColl->xCmp );
   65563 
   65564     if( pColl ){
   65565       return vdbeCompareMemString(pMem1, pMem2, pColl);
   65566     }
   65567     /* If a NULL pointer was passed as the collate function, fall through
   65568     ** to the blob case and use memcmp().  */
   65569   }
   65570 
   65571   /* Both values must be blobs.  Compare using memcmp().  */
   65572   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
   65573   if( rc==0 ){
   65574     rc = pMem1->n - pMem2->n;
   65575   }
   65576   return rc;
   65577 }
   65578 
   65579 
   65580 /*
   65581 ** The first argument passed to this function is a serial-type that
   65582 ** corresponds to an integer - all values between 1 and 9 inclusive
   65583 ** except 7. The second points to a buffer containing an integer value
   65584 ** serialized according to serial_type. This function deserializes
   65585 ** and returns the value.
   65586 */
   65587 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
   65588   u32 y;
   65589   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
   65590   switch( serial_type ){
   65591     case 0:
   65592     case 1:
   65593       testcase( aKey[0]&0x80 );
   65594       return ONE_BYTE_INT(aKey);
   65595     case 2:
   65596       testcase( aKey[0]&0x80 );
   65597       return TWO_BYTE_INT(aKey);
   65598     case 3:
   65599       testcase( aKey[0]&0x80 );
   65600       return THREE_BYTE_INT(aKey);
   65601     case 4: {
   65602       testcase( aKey[0]&0x80 );
   65603       y = FOUR_BYTE_UINT(aKey);
   65604       return (i64)*(int*)&y;
   65605     }
   65606     case 5: {
   65607       testcase( aKey[0]&0x80 );
   65608       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
   65609     }
   65610     case 6: {
   65611       u64 x = FOUR_BYTE_UINT(aKey);
   65612       testcase( aKey[0]&0x80 );
   65613       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
   65614       return (i64)*(i64*)&x;
   65615     }
   65616   }
   65617 
   65618   return (serial_type - 8);
   65619 }
   65620 
   65621 /*
   65622 ** This function compares the two table rows or index records
   65623 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
   65624 ** or positive integer if key1 is less than, equal to or
   65625 ** greater than key2.  The {nKey1, pKey1} key must be a blob
   65626 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
   65627 ** key must be a parsed key such as obtained from
   65628 ** sqlite3VdbeParseRecord.
   65629 **
   65630 ** If argument bSkip is non-zero, it is assumed that the caller has already
   65631 ** determined that the first fields of the keys are equal.
   65632 **
   65633 ** Key1 and Key2 do not have to contain the same number of fields. If all
   65634 ** fields that appear in both keys are equal, then pPKey2->default_rc is
   65635 ** returned.
   65636 **
   65637 ** If database corruption is discovered, set pPKey2->isCorrupt to non-zero
   65638 ** and return 0.
   65639 */
   65640 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
   65641   int nKey1, const void *pKey1,   /* Left key */
   65642   UnpackedRecord *pPKey2,         /* Right key */
   65643   int bSkip                       /* If true, skip the first field */
   65644 ){
   65645   u32 d1;                         /* Offset into aKey[] of next data element */
   65646   int i;                          /* Index of next field to compare */
   65647   u32 szHdr1;                     /* Size of record header in bytes */
   65648   u32 idx1;                       /* Offset of first type in header */
   65649   int rc = 0;                     /* Return value */
   65650   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
   65651   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
   65652   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   65653   Mem mem1;
   65654 
   65655   /* If bSkip is true, then the caller has already determined that the first
   65656   ** two elements in the keys are equal. Fix the various stack variables so
   65657   ** that this routine begins comparing at the second field. */
   65658   if( bSkip ){
   65659     u32 s1;
   65660     idx1 = 1 + getVarint32(&aKey1[1], s1);
   65661     szHdr1 = aKey1[0];
   65662     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
   65663     i = 1;
   65664     pRhs++;
   65665   }else{
   65666     idx1 = getVarint32(aKey1, szHdr1);
   65667     d1 = szHdr1;
   65668     if( d1>(unsigned)nKey1 ){
   65669       pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
   65670       return 0;  /* Corruption */
   65671     }
   65672     i = 0;
   65673   }
   65674 
   65675   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
   65676   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
   65677        || CORRUPT_DB );
   65678   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
   65679   assert( pPKey2->pKeyInfo->nField>0 );
   65680   assert( idx1<=szHdr1 || CORRUPT_DB );
   65681   do{
   65682     u32 serial_type;
   65683 
   65684     /* RHS is an integer */
   65685     if( pRhs->flags & MEM_Int ){
   65686       serial_type = aKey1[idx1];
   65687       testcase( serial_type==12 );
   65688       if( serial_type>=12 ){
   65689         rc = +1;
   65690       }else if( serial_type==0 ){
   65691         rc = -1;
   65692       }else if( serial_type==7 ){
   65693         double rhs = (double)pRhs->u.i;
   65694         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
   65695         if( mem1.r<rhs ){
   65696           rc = -1;
   65697         }else if( mem1.r>rhs ){
   65698           rc = +1;
   65699         }
   65700       }else{
   65701         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
   65702         i64 rhs = pRhs->u.i;
   65703         if( lhs<rhs ){
   65704           rc = -1;
   65705         }else if( lhs>rhs ){
   65706           rc = +1;
   65707         }
   65708       }
   65709     }
   65710 
   65711     /* RHS is real */
   65712     else if( pRhs->flags & MEM_Real ){
   65713       serial_type = aKey1[idx1];
   65714       if( serial_type>=12 ){
   65715         rc = +1;
   65716       }else if( serial_type==0 ){
   65717         rc = -1;
   65718       }else{
   65719         double rhs = pRhs->r;
   65720         double lhs;
   65721         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
   65722         if( serial_type==7 ){
   65723           lhs = mem1.r;
   65724         }else{
   65725           lhs = (double)mem1.u.i;
   65726         }
   65727         if( lhs<rhs ){
   65728           rc = -1;
   65729         }else if( lhs>rhs ){
   65730           rc = +1;
   65731         }
   65732       }
   65733     }
   65734 
   65735     /* RHS is a string */
   65736     else if( pRhs->flags & MEM_Str ){
   65737       getVarint32(&aKey1[idx1], serial_type);
   65738       testcase( serial_type==12 );
   65739       if( serial_type<12 ){
   65740         rc = -1;
   65741       }else if( !(serial_type & 0x01) ){
   65742         rc = +1;
   65743       }else{
   65744         mem1.n = (serial_type - 12) / 2;
   65745         testcase( (d1+mem1.n)==(unsigned)nKey1 );
   65746         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
   65747         if( (d1+mem1.n) > (unsigned)nKey1 ){
   65748           pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
   65749           return 0;                /* Corruption */
   65750         }else if( pKeyInfo->aColl[i] ){
   65751           mem1.enc = pKeyInfo->enc;
   65752           mem1.db = pKeyInfo->db;
   65753           mem1.flags = MEM_Str;
   65754           mem1.z = (char*)&aKey1[d1];
   65755           rc = vdbeCompareMemString(&mem1, pRhs, pKeyInfo->aColl[i]);
   65756         }else{
   65757           int nCmp = MIN(mem1.n, pRhs->n);
   65758           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
   65759           if( rc==0 ) rc = mem1.n - pRhs->n;
   65760         }
   65761       }
   65762     }
   65763 
   65764     /* RHS is a blob */
   65765     else if( pRhs->flags & MEM_Blob ){
   65766       getVarint32(&aKey1[idx1], serial_type);
   65767       testcase( serial_type==12 );
   65768       if( serial_type<12 || (serial_type & 0x01) ){
   65769         rc = -1;
   65770       }else{
   65771         int nStr = (serial_type - 12) / 2;
   65772         testcase( (d1+nStr)==(unsigned)nKey1 );
   65773         testcase( (d1+nStr+1)==(unsigned)nKey1 );
   65774         if( (d1+nStr) > (unsigned)nKey1 ){
   65775           pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
   65776           return 0;                /* Corruption */
   65777         }else{
   65778           int nCmp = MIN(nStr, pRhs->n);
   65779           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
   65780           if( rc==0 ) rc = nStr - pRhs->n;
   65781         }
   65782       }
   65783     }
   65784 
   65785     /* RHS is null */
   65786     else{
   65787       serial_type = aKey1[idx1];
   65788       rc = (serial_type!=0);
   65789     }
   65790 
   65791     if( rc!=0 ){
   65792       if( pKeyInfo->aSortOrder[i] ){
   65793         rc = -rc;
   65794       }
   65795       assert( CORRUPT_DB
   65796           || (rc<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
   65797           || (rc>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
   65798           || pKeyInfo->db->mallocFailed
   65799       );
   65800       assert( mem1.zMalloc==0 );  /* See comment below */
   65801       return rc;
   65802     }
   65803 
   65804     i++;
   65805     pRhs++;
   65806     d1 += sqlite3VdbeSerialTypeLen(serial_type);
   65807     idx1 += sqlite3VarintLen(serial_type);
   65808   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
   65809 
   65810   /* No memory allocation is ever used on mem1.  Prove this using
   65811   ** the following assert().  If the assert() fails, it indicates a
   65812   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
   65813   assert( mem1.zMalloc==0 );
   65814 
   65815   /* rc==0 here means that one or both of the keys ran out of fields and
   65816   ** all the fields up to that point were equal. Return the the default_rc
   65817   ** value.  */
   65818   assert( CORRUPT_DB
   65819        || pPKey2->default_rc==vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)
   65820        || pKeyInfo->db->mallocFailed
   65821   );
   65822   return pPKey2->default_rc;
   65823 }
   65824 
   65825 /*
   65826 ** This function is an optimized version of sqlite3VdbeRecordCompare()
   65827 ** that (a) the first field of pPKey2 is an integer, and (b) the
   65828 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
   65829 ** byte (i.e. is less than 128).
   65830 **
   65831 ** To avoid concerns about buffer overreads, this routine is only used
   65832 ** on schemas where the maximum valid header size is 63 bytes or less.
   65833 */
   65834 static int vdbeRecordCompareInt(
   65835   int nKey1, const void *pKey1, /* Left key */
   65836   UnpackedRecord *pPKey2,       /* Right key */
   65837   int bSkip                     /* Ignored */
   65838 ){
   65839   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
   65840   int serial_type = ((const u8*)pKey1)[1];
   65841   int res;
   65842   u32 y;
   65843   u64 x;
   65844   i64 v = pPKey2->aMem[0].u.i;
   65845   i64 lhs;
   65846   UNUSED_PARAMETER(bSkip);
   65847 
   65848   assert( bSkip==0 );
   65849   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
   65850   switch( serial_type ){
   65851     case 1: { /* 1-byte signed integer */
   65852       lhs = ONE_BYTE_INT(aKey);
   65853       testcase( lhs<0 );
   65854       break;
   65855     }
   65856     case 2: { /* 2-byte signed integer */
   65857       lhs = TWO_BYTE_INT(aKey);
   65858       testcase( lhs<0 );
   65859       break;
   65860     }
   65861     case 3: { /* 3-byte signed integer */
   65862       lhs = THREE_BYTE_INT(aKey);
   65863       testcase( lhs<0 );
   65864       break;
   65865     }
   65866     case 4: { /* 4-byte signed integer */
   65867       y = FOUR_BYTE_UINT(aKey);
   65868       lhs = (i64)*(int*)&y;
   65869       testcase( lhs<0 );
   65870       break;
   65871     }
   65872     case 5: { /* 6-byte signed integer */
   65873       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
   65874       testcase( lhs<0 );
   65875       break;
   65876     }
   65877     case 6: { /* 8-byte signed integer */
   65878       x = FOUR_BYTE_UINT(aKey);
   65879       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
   65880       lhs = *(i64*)&x;
   65881       testcase( lhs<0 );
   65882       break;
   65883     }
   65884     case 8:
   65885       lhs = 0;
   65886       break;
   65887     case 9:
   65888       lhs = 1;
   65889       break;
   65890 
   65891     /* This case could be removed without changing the results of running
   65892     ** this code. Including it causes gcc to generate a faster switch
   65893     ** statement (since the range of switch targets now starts at zero and
   65894     ** is contiguous) but does not cause any duplicate code to be generated
   65895     ** (as gcc is clever enough to combine the two like cases). Other
   65896     ** compilers might be similar.  */
   65897     case 0: case 7:
   65898       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
   65899 
   65900     default:
   65901       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
   65902   }
   65903 
   65904   if( v>lhs ){
   65905     res = pPKey2->r1;
   65906   }else if( v<lhs ){
   65907     res = pPKey2->r2;
   65908   }else if( pPKey2->nField>1 ){
   65909     /* The first fields of the two keys are equal. Compare the trailing
   65910     ** fields.  */
   65911     res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
   65912   }else{
   65913     /* The first fields of the two keys are equal and there are no trailing
   65914     ** fields. Return pPKey2->default_rc in this case. */
   65915     res = pPKey2->default_rc;
   65916   }
   65917 
   65918   assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
   65919        || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
   65920        || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
   65921        || CORRUPT_DB
   65922   );
   65923   return res;
   65924 }
   65925 
   65926 /*
   65927 ** This function is an optimized version of sqlite3VdbeRecordCompare()
   65928 ** that (a) the first field of pPKey2 is a string, that (b) the first field
   65929 ** uses the collation sequence BINARY and (c) that the size-of-header varint
   65930 ** at the start of (pKey1/nKey1) fits in a single byte.
   65931 */
   65932 static int vdbeRecordCompareString(
   65933   int nKey1, const void *pKey1, /* Left key */
   65934   UnpackedRecord *pPKey2,       /* Right key */
   65935   int bSkip
   65936 ){
   65937   const u8 *aKey1 = (const u8*)pKey1;
   65938   int serial_type;
   65939   int res;
   65940   UNUSED_PARAMETER(bSkip);
   65941 
   65942   assert( bSkip==0 );
   65943   getVarint32(&aKey1[1], serial_type);
   65944 
   65945   if( serial_type<12 ){
   65946     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
   65947   }else if( !(serial_type & 0x01) ){
   65948     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
   65949   }else{
   65950     int nCmp;
   65951     int nStr;
   65952     int szHdr = aKey1[0];
   65953 
   65954     nStr = (serial_type-12) / 2;
   65955     if( (szHdr + nStr) > nKey1 ){
   65956       pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
   65957       return 0;    /* Corruption */
   65958     }
   65959     nCmp = MIN( pPKey2->aMem[0].n, nStr );
   65960     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
   65961 
   65962     if( res==0 ){
   65963       res = nStr - pPKey2->aMem[0].n;
   65964       if( res==0 ){
   65965         if( pPKey2->nField>1 ){
   65966           res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
   65967         }else{
   65968           res = pPKey2->default_rc;
   65969         }
   65970       }else if( res>0 ){
   65971         res = pPKey2->r2;
   65972       }else{
   65973         res = pPKey2->r1;
   65974       }
   65975     }else if( res>0 ){
   65976       res = pPKey2->r2;
   65977     }else{
   65978       res = pPKey2->r1;
   65979     }
   65980   }
   65981 
   65982   assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
   65983        || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
   65984        || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
   65985        || CORRUPT_DB
   65986        || pPKey2->pKeyInfo->db->mallocFailed
   65987   );
   65988   return res;
   65989 }
   65990 
   65991 /*
   65992 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
   65993 ** suitable for comparing serialized records to the unpacked record passed
   65994 ** as the only argument.
   65995 */
   65996 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
   65997   /* varintRecordCompareInt() and varintRecordCompareString() both assume
   65998   ** that the size-of-header varint that occurs at the start of each record
   65999   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
   66000   ** also assumes that it is safe to overread a buffer by at least the
   66001   ** maximum possible legal header size plus 8 bytes. Because there is
   66002   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
   66003   ** buffer passed to varintRecordCompareInt() this makes it convenient to
   66004   ** limit the size of the header to 64 bytes in cases where the first field
   66005   ** is an integer.
   66006   **
   66007   ** The easiest way to enforce this limit is to consider only records with
   66008   ** 13 fields or less. If the first field is an integer, the maximum legal
   66009   ** header size is (12*5 + 1 + 1) bytes.  */
   66010   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
   66011     int flags = p->aMem[0].flags;
   66012     if( p->pKeyInfo->aSortOrder[0] ){
   66013       p->r1 = 1;
   66014       p->r2 = -1;
   66015     }else{
   66016       p->r1 = -1;
   66017       p->r2 = 1;
   66018     }
   66019     if( (flags & MEM_Int) ){
   66020       return vdbeRecordCompareInt;
   66021     }
   66022     testcase( flags & MEM_Real );
   66023     testcase( flags & MEM_Null );
   66024     testcase( flags & MEM_Blob );
   66025     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
   66026       assert( flags & MEM_Str );
   66027       return vdbeRecordCompareString;
   66028     }
   66029   }
   66030 
   66031   return sqlite3VdbeRecordCompare;
   66032 }
   66033 
   66034 /*
   66035 ** pCur points at an index entry created using the OP_MakeRecord opcode.
   66036 ** Read the rowid (the last field in the record) and store it in *rowid.
   66037 ** Return SQLITE_OK if everything works, or an error code otherwise.
   66038 **
   66039 ** pCur might be pointing to text obtained from a corrupt database file.
   66040 ** So the content cannot be trusted.  Do appropriate checks on the content.
   66041 */
   66042 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   66043   i64 nCellKey = 0;
   66044   int rc;
   66045   u32 szHdr;        /* Size of the header */
   66046   u32 typeRowid;    /* Serial type of the rowid */
   66047   u32 lenRowid;     /* Size of the rowid */
   66048   Mem m, v;
   66049 
   66050   UNUSED_PARAMETER(db);
   66051 
   66052   /* Get the size of the index entry.  Only indices entries of less
   66053   ** than 2GiB are support - anything large must be database corruption.
   66054   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
   66055   ** this code can safely assume that nCellKey is 32-bits
   66056   */
   66057   assert( sqlite3BtreeCursorIsValid(pCur) );
   66058   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
   66059   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
   66060   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
   66061 
   66062   /* Read in the complete content of the index entry */
   66063   memset(&m, 0, sizeof(m));
   66064   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
   66065   if( rc ){
   66066     return rc;
   66067   }
   66068 
   66069   /* The index entry must begin with a header size */
   66070   (void)getVarint32((u8*)m.z, szHdr);
   66071   testcase( szHdr==3 );
   66072   testcase( szHdr==m.n );
   66073   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
   66074     goto idx_rowid_corruption;
   66075   }
   66076 
   66077   /* The last field of the index should be an integer - the ROWID.
   66078   ** Verify that the last entry really is an integer. */
   66079   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
   66080   testcase( typeRowid==1 );
   66081   testcase( typeRowid==2 );
   66082   testcase( typeRowid==3 );
   66083   testcase( typeRowid==4 );
   66084   testcase( typeRowid==5 );
   66085   testcase( typeRowid==6 );
   66086   testcase( typeRowid==8 );
   66087   testcase( typeRowid==9 );
   66088   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
   66089     goto idx_rowid_corruption;
   66090   }
   66091   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
   66092   testcase( (u32)m.n==szHdr+lenRowid );
   66093   if( unlikely((u32)m.n<szHdr+lenRowid) ){
   66094     goto idx_rowid_corruption;
   66095   }
   66096 
   66097   /* Fetch the integer off the end of the index record */
   66098   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
   66099   *rowid = v.u.i;
   66100   sqlite3VdbeMemRelease(&m);
   66101   return SQLITE_OK;
   66102 
   66103   /* Jump here if database corruption is detected after m has been
   66104   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
   66105 idx_rowid_corruption:
   66106   testcase( m.zMalloc!=0 );
   66107   sqlite3VdbeMemRelease(&m);
   66108   return SQLITE_CORRUPT_BKPT;
   66109 }
   66110 
   66111 /*
   66112 ** Compare the key of the index entry that cursor pC is pointing to against
   66113 ** the key string in pUnpacked.  Write into *pRes a number
   66114 ** that is negative, zero, or positive if pC is less than, equal to,
   66115 ** or greater than pUnpacked.  Return SQLITE_OK on success.
   66116 **
   66117 ** pUnpacked is either created without a rowid or is truncated so that it
   66118 ** omits the rowid at the end.  The rowid at the end of the index entry
   66119 ** is ignored as well.  Hence, this routine only compares the prefixes
   66120 ** of the keys prior to the final rowid, not the entire key.
   66121 */
   66122 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
   66123   VdbeCursor *pC,                  /* The cursor to compare against */
   66124   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
   66125   int *res                         /* Write the comparison result here */
   66126 ){
   66127   i64 nCellKey = 0;
   66128   int rc;
   66129   BtCursor *pCur = pC->pCursor;
   66130   Mem m;
   66131 
   66132   assert( sqlite3BtreeCursorIsValid(pCur) );
   66133   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
   66134   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
   66135   /* nCellKey will always be between 0 and 0xffffffff because of the way
   66136   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
   66137   if( nCellKey<=0 || nCellKey>0x7fffffff ){
   66138     *res = 0;
   66139     return SQLITE_CORRUPT_BKPT;
   66140   }
   66141   memset(&m, 0, sizeof(m));
   66142   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
   66143   if( rc ){
   66144     return rc;
   66145   }
   66146   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked, 0);
   66147   sqlite3VdbeMemRelease(&m);
   66148   return SQLITE_OK;
   66149 }
   66150 
   66151 /*
   66152 ** This routine sets the value to be returned by subsequent calls to
   66153 ** sqlite3_changes() on the database handle 'db'.
   66154 */
   66155 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
   66156   assert( sqlite3_mutex_held(db->mutex) );
   66157   db->nChange = nChange;
   66158   db->nTotalChange += nChange;
   66159 }
   66160 
   66161 /*
   66162 ** Set a flag in the vdbe to update the change counter when it is finalised
   66163 ** or reset.
   66164 */
   66165 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
   66166   v->changeCntOn = 1;
   66167 }
   66168 
   66169 /*
   66170 ** Mark every prepared statement associated with a database connection
   66171 ** as expired.
   66172 **
   66173 ** An expired statement means that recompilation of the statement is
   66174 ** recommend.  Statements expire when things happen that make their
   66175 ** programs obsolete.  Removing user-defined functions or collating
   66176 ** sequences, or changing an authorization function are the types of
   66177 ** things that make prepared statements obsolete.
   66178 */
   66179 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
   66180   Vdbe *p;
   66181   for(p = db->pVdbe; p; p=p->pNext){
   66182     p->expired = 1;
   66183   }
   66184 }
   66185 
   66186 /*
   66187 ** Return the database associated with the Vdbe.
   66188 */
   66189 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
   66190   return v->db;
   66191 }
   66192 
   66193 /*
   66194 ** Return a pointer to an sqlite3_value structure containing the value bound
   66195 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
   66196 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
   66197 ** constants) to the value before returning it.
   66198 **
   66199 ** The returned value must be freed by the caller using sqlite3ValueFree().
   66200 */
   66201 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
   66202   assert( iVar>0 );
   66203   if( v ){
   66204     Mem *pMem = &v->aVar[iVar-1];
   66205     if( 0==(pMem->flags & MEM_Null) ){
   66206       sqlite3_value *pRet = sqlite3ValueNew(v->db);
   66207       if( pRet ){
   66208         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
   66209         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
   66210       }
   66211       return pRet;
   66212     }
   66213   }
   66214   return 0;
   66215 }
   66216 
   66217 /*
   66218 ** Configure SQL variable iVar so that binding a new value to it signals
   66219 ** to sqlite3_reoptimize() that re-preparing the statement may result
   66220 ** in a better query plan.
   66221 */
   66222 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
   66223   assert( iVar>0 );
   66224   if( iVar>32 ){
   66225     v->expmask = 0xffffffff;
   66226   }else{
   66227     v->expmask |= ((u32)1 << (iVar-1));
   66228   }
   66229 }
   66230 
   66231 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66232 /*
   66233 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
   66234 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
   66235 ** in memory obtained from sqlite3DbMalloc).
   66236 */
   66237 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
   66238   sqlite3 *db = p->db;
   66239   sqlite3DbFree(db, p->zErrMsg);
   66240   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   66241   sqlite3_free(pVtab->zErrMsg);
   66242   pVtab->zErrMsg = 0;
   66243 }
   66244 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   66245 
   66246 /************** End of vdbeaux.c *********************************************/
   66247 /************** Begin file vdbeapi.c *****************************************/
   66248 /*
   66249 ** 2004 May 26
   66250 **
   66251 ** The author disclaims copyright to this source code.  In place of
   66252 ** a legal notice, here is a blessing:
   66253 **
   66254 **    May you do good and not evil.
   66255 **    May you find forgiveness for yourself and forgive others.
   66256 **    May you share freely, never taking more than you give.
   66257 **
   66258 *************************************************************************
   66259 **
   66260 ** This file contains code use to implement APIs that are part of the
   66261 ** VDBE.
   66262 */
   66263 
   66264 #ifndef SQLITE_OMIT_DEPRECATED
   66265 /*
   66266 ** Return TRUE (non-zero) of the statement supplied as an argument needs
   66267 ** to be recompiled.  A statement needs to be recompiled whenever the
   66268 ** execution environment changes in a way that would alter the program
   66269 ** that sqlite3_prepare() generates.  For example, if new functions or
   66270 ** collating sequences are registered or if an authorizer function is
   66271 ** added or changed.
   66272 */
   66273 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
   66274   Vdbe *p = (Vdbe*)pStmt;
   66275   return p==0 || p->expired;
   66276 }
   66277 #endif
   66278 
   66279 /*
   66280 ** Check on a Vdbe to make sure it has not been finalized.  Log
   66281 ** an error and return true if it has been finalized (or is otherwise
   66282 ** invalid).  Return false if it is ok.
   66283 */
   66284 static int vdbeSafety(Vdbe *p){
   66285   if( p->db==0 ){
   66286     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
   66287     return 1;
   66288   }else{
   66289     return 0;
   66290   }
   66291 }
   66292 static int vdbeSafetyNotNull(Vdbe *p){
   66293   if( p==0 ){
   66294     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
   66295     return 1;
   66296   }else{
   66297     return vdbeSafety(p);
   66298   }
   66299 }
   66300 
   66301 /*
   66302 ** The following routine destroys a virtual machine that is created by
   66303 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
   66304 ** success/failure code that describes the result of executing the virtual
   66305 ** machine.
   66306 **
   66307 ** This routine sets the error code and string returned by
   66308 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   66309 */
   66310 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
   66311   int rc;
   66312   if( pStmt==0 ){
   66313     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
   66314     ** pointer is a harmless no-op. */
   66315     rc = SQLITE_OK;
   66316   }else{
   66317     Vdbe *v = (Vdbe*)pStmt;
   66318     sqlite3 *db = v->db;
   66319     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
   66320     sqlite3_mutex_enter(db->mutex);
   66321     rc = sqlite3VdbeFinalize(v);
   66322     rc = sqlite3ApiExit(db, rc);
   66323     sqlite3LeaveMutexAndCloseZombie(db);
   66324   }
   66325   return rc;
   66326 }
   66327 
   66328 /*
   66329 ** Terminate the current execution of an SQL statement and reset it
   66330 ** back to its starting state so that it can be reused. A success code from
   66331 ** the prior execution is returned.
   66332 **
   66333 ** This routine sets the error code and string returned by
   66334 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   66335 */
   66336 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
   66337   int rc;
   66338   if( pStmt==0 ){
   66339     rc = SQLITE_OK;
   66340   }else{
   66341     Vdbe *v = (Vdbe*)pStmt;
   66342     sqlite3_mutex_enter(v->db->mutex);
   66343     rc = sqlite3VdbeReset(v);
   66344     sqlite3VdbeRewind(v);
   66345     assert( (rc & (v->db->errMask))==rc );
   66346     rc = sqlite3ApiExit(v->db, rc);
   66347     sqlite3_mutex_leave(v->db->mutex);
   66348   }
   66349   return rc;
   66350 }
   66351 
   66352 /*
   66353 ** Set all the parameters in the compiled SQL statement to NULL.
   66354 */
   66355 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
   66356   int i;
   66357   int rc = SQLITE_OK;
   66358   Vdbe *p = (Vdbe*)pStmt;
   66359 #if SQLITE_THREADSAFE
   66360   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
   66361 #endif
   66362   sqlite3_mutex_enter(mutex);
   66363   for(i=0; i<p->nVar; i++){
   66364     sqlite3VdbeMemRelease(&p->aVar[i]);
   66365     p->aVar[i].flags = MEM_Null;
   66366   }
   66367   if( p->isPrepareV2 && p->expmask ){
   66368     p->expired = 1;
   66369   }
   66370   sqlite3_mutex_leave(mutex);
   66371   return rc;
   66372 }
   66373 
   66374 
   66375 /**************************** sqlite3_value_  *******************************
   66376 ** The following routines extract information from a Mem or sqlite3_value
   66377 ** structure.
   66378 */
   66379 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
   66380   Mem *p = (Mem*)pVal;
   66381   if( p->flags & (MEM_Blob|MEM_Str) ){
   66382     sqlite3VdbeMemExpandBlob(p);
   66383     p->flags |= MEM_Blob;
   66384     return p->n ? p->z : 0;
   66385   }else{
   66386     return sqlite3_value_text(pVal);
   66387   }
   66388 }
   66389 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
   66390   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
   66391 }
   66392 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
   66393   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
   66394 }
   66395 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
   66396   return sqlite3VdbeRealValue((Mem*)pVal);
   66397 }
   66398 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
   66399   return (int)sqlite3VdbeIntValue((Mem*)pVal);
   66400 }
   66401 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
   66402   return sqlite3VdbeIntValue((Mem*)pVal);
   66403 }
   66404 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
   66405   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
   66406 }
   66407 #ifndef SQLITE_OMIT_UTF16
   66408 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
   66409   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
   66410 }
   66411 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
   66412   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
   66413 }
   66414 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
   66415   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
   66416 }
   66417 #endif /* SQLITE_OMIT_UTF16 */
   66418 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
   66419   static const u8 aType[] = {
   66420      SQLITE_BLOB,     /* 0x00 */
   66421      SQLITE_NULL,     /* 0x01 */
   66422      SQLITE_TEXT,     /* 0x02 */
   66423      SQLITE_NULL,     /* 0x03 */
   66424      SQLITE_INTEGER,  /* 0x04 */
   66425      SQLITE_NULL,     /* 0x05 */
   66426      SQLITE_INTEGER,  /* 0x06 */
   66427      SQLITE_NULL,     /* 0x07 */
   66428      SQLITE_FLOAT,    /* 0x08 */
   66429      SQLITE_NULL,     /* 0x09 */
   66430      SQLITE_FLOAT,    /* 0x0a */
   66431      SQLITE_NULL,     /* 0x0b */
   66432      SQLITE_INTEGER,  /* 0x0c */
   66433      SQLITE_NULL,     /* 0x0d */
   66434      SQLITE_INTEGER,  /* 0x0e */
   66435      SQLITE_NULL,     /* 0x0f */
   66436      SQLITE_BLOB,     /* 0x10 */
   66437      SQLITE_NULL,     /* 0x11 */
   66438      SQLITE_TEXT,     /* 0x12 */
   66439      SQLITE_NULL,     /* 0x13 */
   66440      SQLITE_INTEGER,  /* 0x14 */
   66441      SQLITE_NULL,     /* 0x15 */
   66442      SQLITE_INTEGER,  /* 0x16 */
   66443      SQLITE_NULL,     /* 0x17 */
   66444      SQLITE_FLOAT,    /* 0x18 */
   66445      SQLITE_NULL,     /* 0x19 */
   66446      SQLITE_FLOAT,    /* 0x1a */
   66447      SQLITE_NULL,     /* 0x1b */
   66448      SQLITE_INTEGER,  /* 0x1c */
   66449      SQLITE_NULL,     /* 0x1d */
   66450      SQLITE_INTEGER,  /* 0x1e */
   66451      SQLITE_NULL,     /* 0x1f */
   66452   };
   66453   return aType[pVal->flags&MEM_AffMask];
   66454 }
   66455 
   66456 /**************************** sqlite3_result_  *******************************
   66457 ** The following routines are used by user-defined functions to specify
   66458 ** the function result.
   66459 **
   66460 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
   66461 ** result as a string or blob but if the string or blob is too large, it
   66462 ** then sets the error code to SQLITE_TOOBIG
   66463 */
   66464 static void setResultStrOrError(
   66465   sqlite3_context *pCtx,  /* Function context */
   66466   const char *z,          /* String pointer */
   66467   int n,                  /* Bytes in string, or negative */
   66468   u8 enc,                 /* Encoding of z.  0 for BLOBs */
   66469   void (*xDel)(void*)     /* Destructor function */
   66470 ){
   66471   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
   66472     sqlite3_result_error_toobig(pCtx);
   66473   }
   66474 }
   66475 SQLITE_API void sqlite3_result_blob(
   66476   sqlite3_context *pCtx,
   66477   const void *z,
   66478   int n,
   66479   void (*xDel)(void *)
   66480 ){
   66481   assert( n>=0 );
   66482   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66483   setResultStrOrError(pCtx, z, n, 0, xDel);
   66484 }
   66485 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
   66486   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66487   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
   66488 }
   66489 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
   66490   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66491   pCtx->isError = SQLITE_ERROR;
   66492   pCtx->fErrorOrAux = 1;
   66493   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
   66494 }
   66495 #ifndef SQLITE_OMIT_UTF16
   66496 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
   66497   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66498   pCtx->isError = SQLITE_ERROR;
   66499   pCtx->fErrorOrAux = 1;
   66500   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
   66501 }
   66502 #endif
   66503 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
   66504   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66505   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
   66506 }
   66507 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
   66508   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66509   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
   66510 }
   66511 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
   66512   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66513   sqlite3VdbeMemSetNull(&pCtx->s);
   66514 }
   66515 SQLITE_API void sqlite3_result_text(
   66516   sqlite3_context *pCtx,
   66517   const char *z,
   66518   int n,
   66519   void (*xDel)(void *)
   66520 ){
   66521   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66522   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
   66523 }
   66524 #ifndef SQLITE_OMIT_UTF16
   66525 SQLITE_API void sqlite3_result_text16(
   66526   sqlite3_context *pCtx,
   66527   const void *z,
   66528   int n,
   66529   void (*xDel)(void *)
   66530 ){
   66531   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66532   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
   66533 }
   66534 SQLITE_API void sqlite3_result_text16be(
   66535   sqlite3_context *pCtx,
   66536   const void *z,
   66537   int n,
   66538   void (*xDel)(void *)
   66539 ){
   66540   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66541   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
   66542 }
   66543 SQLITE_API void sqlite3_result_text16le(
   66544   sqlite3_context *pCtx,
   66545   const void *z,
   66546   int n,
   66547   void (*xDel)(void *)
   66548 ){
   66549   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66550   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
   66551 }
   66552 #endif /* SQLITE_OMIT_UTF16 */
   66553 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
   66554   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66555   sqlite3VdbeMemCopy(&pCtx->s, pValue);
   66556 }
   66557 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
   66558   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66559   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
   66560 }
   66561 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   66562   pCtx->isError = errCode;
   66563   pCtx->fErrorOrAux = 1;
   66564   if( pCtx->s.flags & MEM_Null ){
   66565     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
   66566                          SQLITE_UTF8, SQLITE_STATIC);
   66567   }
   66568 }
   66569 
   66570 /* Force an SQLITE_TOOBIG error. */
   66571 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   66572   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66573   pCtx->isError = SQLITE_TOOBIG;
   66574   pCtx->fErrorOrAux = 1;
   66575   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
   66576                        SQLITE_UTF8, SQLITE_STATIC);
   66577 }
   66578 
   66579 /* An SQLITE_NOMEM error. */
   66580 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
   66581   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66582   sqlite3VdbeMemSetNull(&pCtx->s);
   66583   pCtx->isError = SQLITE_NOMEM;
   66584   pCtx->fErrorOrAux = 1;
   66585   pCtx->s.db->mallocFailed = 1;
   66586 }
   66587 
   66588 /*
   66589 ** This function is called after a transaction has been committed. It
   66590 ** invokes callbacks registered with sqlite3_wal_hook() as required.
   66591 */
   66592 static int doWalCallbacks(sqlite3 *db){
   66593   int rc = SQLITE_OK;
   66594 #ifndef SQLITE_OMIT_WAL
   66595   int i;
   66596   for(i=0; i<db->nDb; i++){
   66597     Btree *pBt = db->aDb[i].pBt;
   66598     if( pBt ){
   66599       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
   66600       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
   66601         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
   66602       }
   66603     }
   66604   }
   66605 #endif
   66606   return rc;
   66607 }
   66608 
   66609 /*
   66610 ** Execute the statement pStmt, either until a row of data is ready, the
   66611 ** statement is completely executed or an error occurs.
   66612 **
   66613 ** This routine implements the bulk of the logic behind the sqlite_step()
   66614 ** API.  The only thing omitted is the automatic recompile if a
   66615 ** schema change has occurred.  That detail is handled by the
   66616 ** outer sqlite3_step() wrapper procedure.
   66617 */
   66618 static int sqlite3Step(Vdbe *p){
   66619   sqlite3 *db;
   66620   int rc;
   66621 
   66622   assert(p);
   66623   if( p->magic!=VDBE_MAGIC_RUN ){
   66624     /* We used to require that sqlite3_reset() be called before retrying
   66625     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
   66626     ** with version 3.7.0, we changed this so that sqlite3_reset() would
   66627     ** be called automatically instead of throwing the SQLITE_MISUSE error.
   66628     ** This "automatic-reset" change is not technically an incompatibility,
   66629     ** since any application that receives an SQLITE_MISUSE is broken by
   66630     ** definition.
   66631     **
   66632     ** Nevertheless, some published applications that were originally written
   66633     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
   66634     ** returns, and those were broken by the automatic-reset change.  As a
   66635     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
   66636     ** legacy behavior of returning SQLITE_MISUSE for cases where the
   66637     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
   66638     ** or SQLITE_BUSY error.
   66639     */
   66640 #ifdef SQLITE_OMIT_AUTORESET
   66641     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
   66642       sqlite3_reset((sqlite3_stmt*)p);
   66643     }else{
   66644       return SQLITE_MISUSE_BKPT;
   66645     }
   66646 #else
   66647     sqlite3_reset((sqlite3_stmt*)p);
   66648 #endif
   66649   }
   66650 
   66651   /* Check that malloc() has not failed. If it has, return early. */
   66652   db = p->db;
   66653   if( db->mallocFailed ){
   66654     p->rc = SQLITE_NOMEM;
   66655     return SQLITE_NOMEM;
   66656   }
   66657 
   66658   if( p->pc<=0 && p->expired ){
   66659     p->rc = SQLITE_SCHEMA;
   66660     rc = SQLITE_ERROR;
   66661     goto end_of_step;
   66662   }
   66663   if( p->pc<0 ){
   66664     /* If there are no other statements currently running, then
   66665     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
   66666     ** from interrupting a statement that has not yet started.
   66667     */
   66668     if( db->nVdbeActive==0 ){
   66669       db->u1.isInterrupted = 0;
   66670     }
   66671 
   66672     assert( db->nVdbeWrite>0 || db->autoCommit==0
   66673         || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
   66674     );
   66675 
   66676 #ifndef SQLITE_OMIT_TRACE
   66677     if( db->xProfile && !db->init.busy ){
   66678       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
   66679     }
   66680 #endif
   66681 
   66682     db->nVdbeActive++;
   66683     if( p->readOnly==0 ) db->nVdbeWrite++;
   66684     if( p->bIsReader ) db->nVdbeRead++;
   66685     p->pc = 0;
   66686   }
   66687 #ifndef SQLITE_OMIT_EXPLAIN
   66688   if( p->explain ){
   66689     rc = sqlite3VdbeList(p);
   66690   }else
   66691 #endif /* SQLITE_OMIT_EXPLAIN */
   66692   {
   66693     db->nVdbeExec++;
   66694     rc = sqlite3VdbeExec(p);
   66695     db->nVdbeExec--;
   66696   }
   66697 
   66698 #ifndef SQLITE_OMIT_TRACE
   66699   /* Invoke the profile callback if there is one
   66700   */
   66701   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
   66702     sqlite3_int64 iNow;
   66703     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
   66704     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
   66705   }
   66706 #endif
   66707 
   66708   if( rc==SQLITE_DONE ){
   66709     assert( p->rc==SQLITE_OK );
   66710     p->rc = doWalCallbacks(db);
   66711     if( p->rc!=SQLITE_OK ){
   66712       rc = SQLITE_ERROR;
   66713     }
   66714   }
   66715 
   66716   db->errCode = rc;
   66717   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
   66718     p->rc = SQLITE_NOMEM;
   66719   }
   66720 end_of_step:
   66721   /* At this point local variable rc holds the value that should be
   66722   ** returned if this statement was compiled using the legacy
   66723   ** sqlite3_prepare() interface. According to the docs, this can only
   66724   ** be one of the values in the first assert() below. Variable p->rc
   66725   ** contains the value that would be returned if sqlite3_finalize()
   66726   ** were called on statement p.
   66727   */
   66728   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
   66729        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
   66730   );
   66731   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
   66732   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
   66733     /* If this statement was prepared using sqlite3_prepare_v2(), and an
   66734     ** error has occurred, then return the error code in p->rc to the
   66735     ** caller. Set the error code in the database handle to the same value.
   66736     */
   66737     rc = sqlite3VdbeTransferError(p);
   66738   }
   66739   return (rc&db->errMask);
   66740 }
   66741 
   66742 /*
   66743 ** This is the top-level implementation of sqlite3_step().  Call
   66744 ** sqlite3Step() to do most of the work.  If a schema error occurs,
   66745 ** call sqlite3Reprepare() and try again.
   66746 */
   66747 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
   66748   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
   66749   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
   66750   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
   66751   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
   66752   sqlite3 *db;             /* The database connection */
   66753 
   66754   if( vdbeSafetyNotNull(v) ){
   66755     return SQLITE_MISUSE_BKPT;
   66756   }
   66757   db = v->db;
   66758   sqlite3_mutex_enter(db->mutex);
   66759   v->doingRerun = 0;
   66760   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
   66761          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
   66762          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
   66763     sqlite3_reset(pStmt);
   66764     v->doingRerun = 1;
   66765     assert( v->expired==0 );
   66766   }
   66767   if( rc2!=SQLITE_OK ){
   66768     /* This case occurs after failing to recompile an sql statement.
   66769     ** The error message from the SQL compiler has already been loaded
   66770     ** into the database handle. This block copies the error message
   66771     ** from the database handle into the statement and sets the statement
   66772     ** program counter to 0 to ensure that when the statement is
   66773     ** finalized or reset the parser error message is available via
   66774     ** sqlite3_errmsg() and sqlite3_errcode().
   66775     */
   66776     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
   66777     assert( zErr!=0 || db->mallocFailed );
   66778     sqlite3DbFree(db, v->zErrMsg);
   66779     if( !db->mallocFailed ){
   66780       v->zErrMsg = sqlite3DbStrDup(db, zErr);
   66781       v->rc = rc2;
   66782     } else {
   66783       v->zErrMsg = 0;
   66784       v->rc = rc = SQLITE_NOMEM;
   66785     }
   66786   }
   66787   rc = sqlite3ApiExit(db, rc);
   66788   sqlite3_mutex_leave(db->mutex);
   66789   return rc;
   66790 }
   66791 
   66792 
   66793 /*
   66794 ** Extract the user data from a sqlite3_context structure and return a
   66795 ** pointer to it.
   66796 */
   66797 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
   66798   assert( p && p->pFunc );
   66799   return p->pFunc->pUserData;
   66800 }
   66801 
   66802 /*
   66803 ** Extract the user data from a sqlite3_context structure and return a
   66804 ** pointer to it.
   66805 **
   66806 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
   66807 ** returns a copy of the pointer to the database connection (the 1st
   66808 ** parameter) of the sqlite3_create_function() and
   66809 ** sqlite3_create_function16() routines that originally registered the
   66810 ** application defined function.
   66811 */
   66812 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
   66813   assert( p && p->pFunc );
   66814   return p->s.db;
   66815 }
   66816 
   66817 /*
   66818 ** Return the current time for a statement
   66819 */
   66820 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
   66821   Vdbe *v = p->pVdbe;
   66822   int rc;
   66823   if( v->iCurrentTime==0 ){
   66824     rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
   66825     if( rc ) v->iCurrentTime = 0;
   66826   }
   66827   return v->iCurrentTime;
   66828 }
   66829 
   66830 /*
   66831 ** The following is the implementation of an SQL function that always
   66832 ** fails with an error message stating that the function is used in the
   66833 ** wrong context.  The sqlite3_overload_function() API might construct
   66834 ** SQL function that use this routine so that the functions will exist
   66835 ** for name resolution but are actually overloaded by the xFindFunction
   66836 ** method of virtual tables.
   66837 */
   66838 SQLITE_PRIVATE void sqlite3InvalidFunction(
   66839   sqlite3_context *context,  /* The function calling context */
   66840   int NotUsed,               /* Number of arguments to the function */
   66841   sqlite3_value **NotUsed2   /* Value of each argument */
   66842 ){
   66843   const char *zName = context->pFunc->zName;
   66844   char *zErr;
   66845   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   66846   zErr = sqlite3_mprintf(
   66847       "unable to use function %s in the requested context", zName);
   66848   sqlite3_result_error(context, zErr, -1);
   66849   sqlite3_free(zErr);
   66850 }
   66851 
   66852 /*
   66853 ** Allocate or return the aggregate context for a user function.  A new
   66854 ** context is allocated on the first call.  Subsequent calls return the
   66855 ** same context that was returned on prior calls.
   66856 */
   66857 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
   66858   Mem *pMem;
   66859   assert( p && p->pFunc && p->pFunc->xStep );
   66860   assert( sqlite3_mutex_held(p->s.db->mutex) );
   66861   pMem = p->pMem;
   66862   testcase( nByte<0 );
   66863   if( (pMem->flags & MEM_Agg)==0 ){
   66864     if( nByte<=0 ){
   66865       sqlite3VdbeMemReleaseExternal(pMem);
   66866       pMem->flags = MEM_Null;
   66867       pMem->z = 0;
   66868     }else{
   66869       sqlite3VdbeMemGrow(pMem, nByte, 0);
   66870       pMem->flags = MEM_Agg;
   66871       pMem->u.pDef = p->pFunc;
   66872       if( pMem->z ){
   66873         memset(pMem->z, 0, nByte);
   66874       }
   66875     }
   66876   }
   66877   return (void*)pMem->z;
   66878 }
   66879 
   66880 /*
   66881 ** Return the auxilary data pointer, if any, for the iArg'th argument to
   66882 ** the user-function defined by pCtx.
   66883 */
   66884 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
   66885   AuxData *pAuxData;
   66886 
   66887   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66888   for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
   66889     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
   66890   }
   66891 
   66892   return (pAuxData ? pAuxData->pAux : 0);
   66893 }
   66894 
   66895 /*
   66896 ** Set the auxilary data pointer and delete function, for the iArg'th
   66897 ** argument to the user-function defined by pCtx. Any previous value is
   66898 ** deleted by calling the delete function specified when it was set.
   66899 */
   66900 SQLITE_API void sqlite3_set_auxdata(
   66901   sqlite3_context *pCtx,
   66902   int iArg,
   66903   void *pAux,
   66904   void (*xDelete)(void*)
   66905 ){
   66906   AuxData *pAuxData;
   66907   Vdbe *pVdbe = pCtx->pVdbe;
   66908 
   66909   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   66910   if( iArg<0 ) goto failed;
   66911 
   66912   for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
   66913     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
   66914   }
   66915   if( pAuxData==0 ){
   66916     pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
   66917     if( !pAuxData ) goto failed;
   66918     pAuxData->iOp = pCtx->iOp;
   66919     pAuxData->iArg = iArg;
   66920     pAuxData->pNext = pVdbe->pAuxData;
   66921     pVdbe->pAuxData = pAuxData;
   66922     if( pCtx->fErrorOrAux==0 ){
   66923       pCtx->isError = 0;
   66924       pCtx->fErrorOrAux = 1;
   66925     }
   66926   }else if( pAuxData->xDelete ){
   66927     pAuxData->xDelete(pAuxData->pAux);
   66928   }
   66929 
   66930   pAuxData->pAux = pAux;
   66931   pAuxData->xDelete = xDelete;
   66932   return;
   66933 
   66934 failed:
   66935   if( xDelete ){
   66936     xDelete(pAux);
   66937   }
   66938 }
   66939 
   66940 #ifndef SQLITE_OMIT_DEPRECATED
   66941 /*
   66942 ** Return the number of times the Step function of a aggregate has been
   66943 ** called.
   66944 **
   66945 ** This function is deprecated.  Do not use it for new code.  It is
   66946 ** provide only to avoid breaking legacy code.  New aggregate function
   66947 ** implementations should keep their own counts within their aggregate
   66948 ** context.
   66949 */
   66950 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
   66951   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
   66952   return p->pMem->n;
   66953 }
   66954 #endif
   66955 
   66956 /*
   66957 ** Return the number of columns in the result set for the statement pStmt.
   66958 */
   66959 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
   66960   Vdbe *pVm = (Vdbe *)pStmt;
   66961   return pVm ? pVm->nResColumn : 0;
   66962 }
   66963 
   66964 /*
   66965 ** Return the number of values available from the current row of the
   66966 ** currently executing statement pStmt.
   66967 */
   66968 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
   66969   Vdbe *pVm = (Vdbe *)pStmt;
   66970   if( pVm==0 || pVm->pResultSet==0 ) return 0;
   66971   return pVm->nResColumn;
   66972 }
   66973 
   66974 /*
   66975 ** Return a pointer to static memory containing an SQL NULL value.
   66976 */
   66977 static const Mem *columnNullValue(void){
   66978   /* Even though the Mem structure contains an element
   66979   ** of type i64, on certain architectures (x86) with certain compiler
   66980   ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
   66981   ** instead of an 8-byte one. This all works fine, except that when
   66982   ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
   66983   ** that a Mem structure is located on an 8-byte boundary. To prevent
   66984   ** these assert()s from failing, when building with SQLITE_DEBUG defined
   66985   ** using gcc, we force nullMem to be 8-byte aligned using the magical
   66986   ** __attribute__((aligned(8))) macro.  */
   66987   static const Mem nullMem
   66988 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
   66989     __attribute__((aligned(8)))
   66990 #endif
   66991     = {0, "", (double)0, {0}, 0, MEM_Null, 0,
   66992 #ifdef SQLITE_DEBUG
   66993        0, 0,  /* pScopyFrom, pFiller */
   66994 #endif
   66995        0, 0 };
   66996   return &nullMem;
   66997 }
   66998 
   66999 /*
   67000 ** Check to see if column iCol of the given statement is valid.  If
   67001 ** it is, return a pointer to the Mem for the value of that column.
   67002 ** If iCol is not valid, return a pointer to a Mem which has a value
   67003 ** of NULL.
   67004 */
   67005 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
   67006   Vdbe *pVm;
   67007   Mem *pOut;
   67008 
   67009   pVm = (Vdbe *)pStmt;
   67010   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
   67011     sqlite3_mutex_enter(pVm->db->mutex);
   67012     pOut = &pVm->pResultSet[i];
   67013   }else{
   67014     if( pVm && ALWAYS(pVm->db) ){
   67015       sqlite3_mutex_enter(pVm->db->mutex);
   67016       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
   67017     }
   67018     pOut = (Mem*)columnNullValue();
   67019   }
   67020   return pOut;
   67021 }
   67022 
   67023 /*
   67024 ** This function is called after invoking an sqlite3_value_XXX function on a
   67025 ** column value (i.e. a value returned by evaluating an SQL expression in the
   67026 ** select list of a SELECT statement) that may cause a malloc() failure. If
   67027 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
   67028 ** code of statement pStmt set to SQLITE_NOMEM.
   67029 **
   67030 ** Specifically, this is called from within:
   67031 **
   67032 **     sqlite3_column_int()
   67033 **     sqlite3_column_int64()
   67034 **     sqlite3_column_text()
   67035 **     sqlite3_column_text16()
   67036 **     sqlite3_column_real()
   67037 **     sqlite3_column_bytes()
   67038 **     sqlite3_column_bytes16()
   67039 **     sqiite3_column_blob()
   67040 */
   67041 static void columnMallocFailure(sqlite3_stmt *pStmt)
   67042 {
   67043   /* If malloc() failed during an encoding conversion within an
   67044   ** sqlite3_column_XXX API, then set the return code of the statement to
   67045   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
   67046   ** and _finalize() will return NOMEM.
   67047   */
   67048   Vdbe *p = (Vdbe *)pStmt;
   67049   if( p ){
   67050     p->rc = sqlite3ApiExit(p->db, p->rc);
   67051     sqlite3_mutex_leave(p->db->mutex);
   67052   }
   67053 }
   67054 
   67055 /**************************** sqlite3_column_  *******************************
   67056 ** The following routines are used to access elements of the current row
   67057 ** in the result set.
   67058 */
   67059 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   67060   const void *val;
   67061   val = sqlite3_value_blob( columnMem(pStmt,i) );
   67062   /* Even though there is no encoding conversion, value_blob() might
   67063   ** need to call malloc() to expand the result of a zeroblob()
   67064   ** expression.
   67065   */
   67066   columnMallocFailure(pStmt);
   67067   return val;
   67068 }
   67069 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
   67070   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
   67071   columnMallocFailure(pStmt);
   67072   return val;
   67073 }
   67074 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
   67075   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
   67076   columnMallocFailure(pStmt);
   67077   return val;
   67078 }
   67079 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
   67080   double val = sqlite3_value_double( columnMem(pStmt,i) );
   67081   columnMallocFailure(pStmt);
   67082   return val;
   67083 }
   67084 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
   67085   int val = sqlite3_value_int( columnMem(pStmt,i) );
   67086   columnMallocFailure(pStmt);
   67087   return val;
   67088 }
   67089 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
   67090   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
   67091   columnMallocFailure(pStmt);
   67092   return val;
   67093 }
   67094 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
   67095   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
   67096   columnMallocFailure(pStmt);
   67097   return val;
   67098 }
   67099 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
   67100   Mem *pOut = columnMem(pStmt, i);
   67101   if( pOut->flags&MEM_Static ){
   67102     pOut->flags &= ~MEM_Static;
   67103     pOut->flags |= MEM_Ephem;
   67104   }
   67105   columnMallocFailure(pStmt);
   67106   return (sqlite3_value *)pOut;
   67107 }
   67108 #ifndef SQLITE_OMIT_UTF16
   67109 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
   67110   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
   67111   columnMallocFailure(pStmt);
   67112   return val;
   67113 }
   67114 #endif /* SQLITE_OMIT_UTF16 */
   67115 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
   67116   int iType = sqlite3_value_type( columnMem(pStmt,i) );
   67117   columnMallocFailure(pStmt);
   67118   return iType;
   67119 }
   67120 
   67121 /*
   67122 ** Convert the N-th element of pStmt->pColName[] into a string using
   67123 ** xFunc() then return that string.  If N is out of range, return 0.
   67124 **
   67125 ** There are up to 5 names for each column.  useType determines which
   67126 ** name is returned.  Here are the names:
   67127 **
   67128 **    0      The column name as it should be displayed for output
   67129 **    1      The datatype name for the column
   67130 **    2      The name of the database that the column derives from
   67131 **    3      The name of the table that the column derives from
   67132 **    4      The name of the table column that the result column derives from
   67133 **
   67134 ** If the result is not a simple column reference (if it is an expression
   67135 ** or a constant) then useTypes 2, 3, and 4 return NULL.
   67136 */
   67137 static const void *columnName(
   67138   sqlite3_stmt *pStmt,
   67139   int N,
   67140   const void *(*xFunc)(Mem*),
   67141   int useType
   67142 ){
   67143   const void *ret = 0;
   67144   Vdbe *p = (Vdbe *)pStmt;
   67145   int n;
   67146   sqlite3 *db = p->db;
   67147 
   67148   assert( db!=0 );
   67149   n = sqlite3_column_count(pStmt);
   67150   if( N<n && N>=0 ){
   67151     N += useType*n;
   67152     sqlite3_mutex_enter(db->mutex);
   67153     assert( db->mallocFailed==0 );
   67154     ret = xFunc(&p->aColName[N]);
   67155      /* A malloc may have failed inside of the xFunc() call. If this
   67156     ** is the case, clear the mallocFailed flag and return NULL.
   67157     */
   67158     if( db->mallocFailed ){
   67159       db->mallocFailed = 0;
   67160       ret = 0;
   67161     }
   67162     sqlite3_mutex_leave(db->mutex);
   67163   }
   67164   return ret;
   67165 }
   67166 
   67167 /*
   67168 ** Return the name of the Nth column of the result set returned by SQL
   67169 ** statement pStmt.
   67170 */
   67171 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
   67172   return columnName(
   67173       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
   67174 }
   67175 #ifndef SQLITE_OMIT_UTF16
   67176 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
   67177   return columnName(
   67178       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
   67179 }
   67180 #endif
   67181 
   67182 /*
   67183 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
   67184 ** not define OMIT_DECLTYPE.
   67185 */
   67186 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
   67187 # error "Must not define both SQLITE_OMIT_DECLTYPE \
   67188          and SQLITE_ENABLE_COLUMN_METADATA"
   67189 #endif
   67190 
   67191 #ifndef SQLITE_OMIT_DECLTYPE
   67192 /*
   67193 ** Return the column declaration type (if applicable) of the 'i'th column
   67194 ** of the result set of SQL statement pStmt.
   67195 */
   67196 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
   67197   return columnName(
   67198       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
   67199 }
   67200 #ifndef SQLITE_OMIT_UTF16
   67201 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
   67202   return columnName(
   67203       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
   67204 }
   67205 #endif /* SQLITE_OMIT_UTF16 */
   67206 #endif /* SQLITE_OMIT_DECLTYPE */
   67207 
   67208 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   67209 /*
   67210 ** Return the name of the database from which a result column derives.
   67211 ** NULL is returned if the result column is an expression or constant or
   67212 ** anything else which is not an unabiguous reference to a database column.
   67213 */
   67214 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
   67215   return columnName(
   67216       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
   67217 }
   67218 #ifndef SQLITE_OMIT_UTF16
   67219 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
   67220   return columnName(
   67221       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
   67222 }
   67223 #endif /* SQLITE_OMIT_UTF16 */
   67224 
   67225 /*
   67226 ** Return the name of the table from which a result column derives.
   67227 ** NULL is returned if the result column is an expression or constant or
   67228 ** anything else which is not an unabiguous reference to a database column.
   67229 */
   67230 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
   67231   return columnName(
   67232       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
   67233 }
   67234 #ifndef SQLITE_OMIT_UTF16
   67235 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
   67236   return columnName(
   67237       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
   67238 }
   67239 #endif /* SQLITE_OMIT_UTF16 */
   67240 
   67241 /*
   67242 ** Return the name of the table column from which a result column derives.
   67243 ** NULL is returned if the result column is an expression or constant or
   67244 ** anything else which is not an unabiguous reference to a database column.
   67245 */
   67246 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
   67247   return columnName(
   67248       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
   67249 }
   67250 #ifndef SQLITE_OMIT_UTF16
   67251 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
   67252   return columnName(
   67253       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
   67254 }
   67255 #endif /* SQLITE_OMIT_UTF16 */
   67256 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
   67257 
   67258 
   67259 /******************************* sqlite3_bind_  ***************************
   67260 **
   67261 ** Routines used to attach values to wildcards in a compiled SQL statement.
   67262 */
   67263 /*
   67264 ** Unbind the value bound to variable i in virtual machine p. This is the
   67265 ** the same as binding a NULL value to the column. If the "i" parameter is
   67266 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
   67267 **
   67268 ** A successful evaluation of this routine acquires the mutex on p.
   67269 ** the mutex is released if any kind of error occurs.
   67270 **
   67271 ** The error code stored in database p->db is overwritten with the return
   67272 ** value in any case.
   67273 */
   67274 static int vdbeUnbind(Vdbe *p, int i){
   67275   Mem *pVar;
   67276   if( vdbeSafetyNotNull(p) ){
   67277     return SQLITE_MISUSE_BKPT;
   67278   }
   67279   sqlite3_mutex_enter(p->db->mutex);
   67280   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
   67281     sqlite3Error(p->db, SQLITE_MISUSE, 0);
   67282     sqlite3_mutex_leave(p->db->mutex);
   67283     sqlite3_log(SQLITE_MISUSE,
   67284         "bind on a busy prepared statement: [%s]", p->zSql);
   67285     return SQLITE_MISUSE_BKPT;
   67286   }
   67287   if( i<1 || i>p->nVar ){
   67288     sqlite3Error(p->db, SQLITE_RANGE, 0);
   67289     sqlite3_mutex_leave(p->db->mutex);
   67290     return SQLITE_RANGE;
   67291   }
   67292   i--;
   67293   pVar = &p->aVar[i];
   67294   sqlite3VdbeMemRelease(pVar);
   67295   pVar->flags = MEM_Null;
   67296   sqlite3Error(p->db, SQLITE_OK, 0);
   67297 
   67298   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
   67299   ** binding a new value to this variable invalidates the current query plan.
   67300   **
   67301   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
   67302   ** parameter in the WHERE clause might influence the choice of query plan
   67303   ** for a statement, then the statement will be automatically recompiled,
   67304   ** as if there had been a schema change, on the first sqlite3_step() call
   67305   ** following any change to the bindings of that parameter.
   67306   */
   67307   if( p->isPrepareV2 &&
   67308      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
   67309   ){
   67310     p->expired = 1;
   67311   }
   67312   return SQLITE_OK;
   67313 }
   67314 
   67315 /*
   67316 ** Bind a text or BLOB value.
   67317 */
   67318 static int bindText(
   67319   sqlite3_stmt *pStmt,   /* The statement to bind against */
   67320   int i,                 /* Index of the parameter to bind */
   67321   const void *zData,     /* Pointer to the data to be bound */
   67322   int nData,             /* Number of bytes of data to be bound */
   67323   void (*xDel)(void*),   /* Destructor for the data */
   67324   u8 encoding            /* Encoding for the data */
   67325 ){
   67326   Vdbe *p = (Vdbe *)pStmt;
   67327   Mem *pVar;
   67328   int rc;
   67329 
   67330   rc = vdbeUnbind(p, i);
   67331   if( rc==SQLITE_OK ){
   67332     if( zData!=0 ){
   67333       pVar = &p->aVar[i-1];
   67334       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
   67335       if( rc==SQLITE_OK && encoding!=0 ){
   67336         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
   67337       }
   67338       sqlite3Error(p->db, rc, 0);
   67339       rc = sqlite3ApiExit(p->db, rc);
   67340     }
   67341     sqlite3_mutex_leave(p->db->mutex);
   67342   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
   67343     xDel((void*)zData);
   67344   }
   67345   return rc;
   67346 }
   67347 
   67348 
   67349 /*
   67350 ** Bind a blob value to an SQL statement variable.
   67351 */
   67352 SQLITE_API int sqlite3_bind_blob(
   67353   sqlite3_stmt *pStmt,
   67354   int i,
   67355   const void *zData,
   67356   int nData,
   67357   void (*xDel)(void*)
   67358 ){
   67359   return bindText(pStmt, i, zData, nData, xDel, 0);
   67360 }
   67361 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
   67362   int rc;
   67363   Vdbe *p = (Vdbe *)pStmt;
   67364   rc = vdbeUnbind(p, i);
   67365   if( rc==SQLITE_OK ){
   67366     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
   67367     sqlite3_mutex_leave(p->db->mutex);
   67368   }
   67369   return rc;
   67370 }
   67371 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
   67372   return sqlite3_bind_int64(p, i, (i64)iValue);
   67373 }
   67374 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
   67375   int rc;
   67376   Vdbe *p = (Vdbe *)pStmt;
   67377   rc = vdbeUnbind(p, i);
   67378   if( rc==SQLITE_OK ){
   67379     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
   67380     sqlite3_mutex_leave(p->db->mutex);
   67381   }
   67382   return rc;
   67383 }
   67384 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
   67385   int rc;
   67386   Vdbe *p = (Vdbe*)pStmt;
   67387   rc = vdbeUnbind(p, i);
   67388   if( rc==SQLITE_OK ){
   67389     sqlite3_mutex_leave(p->db->mutex);
   67390   }
   67391   return rc;
   67392 }
   67393 SQLITE_API int sqlite3_bind_text(
   67394   sqlite3_stmt *pStmt,
   67395   int i,
   67396   const char *zData,
   67397   int nData,
   67398   void (*xDel)(void*)
   67399 ){
   67400   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
   67401 }
   67402 #ifndef SQLITE_OMIT_UTF16
   67403 SQLITE_API int sqlite3_bind_text16(
   67404   sqlite3_stmt *pStmt,
   67405   int i,
   67406   const void *zData,
   67407   int nData,
   67408   void (*xDel)(void*)
   67409 ){
   67410   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
   67411 }
   67412 #endif /* SQLITE_OMIT_UTF16 */
   67413 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
   67414   int rc;
   67415   switch( sqlite3_value_type((sqlite3_value*)pValue) ){
   67416     case SQLITE_INTEGER: {
   67417       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
   67418       break;
   67419     }
   67420     case SQLITE_FLOAT: {
   67421       rc = sqlite3_bind_double(pStmt, i, pValue->r);
   67422       break;
   67423     }
   67424     case SQLITE_BLOB: {
   67425       if( pValue->flags & MEM_Zero ){
   67426         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
   67427       }else{
   67428         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
   67429       }
   67430       break;
   67431     }
   67432     case SQLITE_TEXT: {
   67433       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
   67434                               pValue->enc);
   67435       break;
   67436     }
   67437     default: {
   67438       rc = sqlite3_bind_null(pStmt, i);
   67439       break;
   67440     }
   67441   }
   67442   return rc;
   67443 }
   67444 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
   67445   int rc;
   67446   Vdbe *p = (Vdbe *)pStmt;
   67447   rc = vdbeUnbind(p, i);
   67448   if( rc==SQLITE_OK ){
   67449     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
   67450     sqlite3_mutex_leave(p->db->mutex);
   67451   }
   67452   return rc;
   67453 }
   67454 
   67455 /*
   67456 ** Return the number of wildcards that can be potentially bound to.
   67457 ** This routine is added to support DBD::SQLite.
   67458 */
   67459 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
   67460   Vdbe *p = (Vdbe*)pStmt;
   67461   return p ? p->nVar : 0;
   67462 }
   67463 
   67464 /*
   67465 ** Return the name of a wildcard parameter.  Return NULL if the index
   67466 ** is out of range or if the wildcard is unnamed.
   67467 **
   67468 ** The result is always UTF-8.
   67469 */
   67470 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
   67471   Vdbe *p = (Vdbe*)pStmt;
   67472   if( p==0 || i<1 || i>p->nzVar ){
   67473     return 0;
   67474   }
   67475   return p->azVar[i-1];
   67476 }
   67477 
   67478 /*
   67479 ** Given a wildcard parameter name, return the index of the variable
   67480 ** with that name.  If there is no variable with the given name,
   67481 ** return 0.
   67482 */
   67483 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
   67484   int i;
   67485   if( p==0 ){
   67486     return 0;
   67487   }
   67488   if( zName ){
   67489     for(i=0; i<p->nzVar; i++){
   67490       const char *z = p->azVar[i];
   67491       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
   67492         return i+1;
   67493       }
   67494     }
   67495   }
   67496   return 0;
   67497 }
   67498 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
   67499   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
   67500 }
   67501 
   67502 /*
   67503 ** Transfer all bindings from the first statement over to the second.
   67504 */
   67505 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   67506   Vdbe *pFrom = (Vdbe*)pFromStmt;
   67507   Vdbe *pTo = (Vdbe*)pToStmt;
   67508   int i;
   67509   assert( pTo->db==pFrom->db );
   67510   assert( pTo->nVar==pFrom->nVar );
   67511   sqlite3_mutex_enter(pTo->db->mutex);
   67512   for(i=0; i<pFrom->nVar; i++){
   67513     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
   67514   }
   67515   sqlite3_mutex_leave(pTo->db->mutex);
   67516   return SQLITE_OK;
   67517 }
   67518 
   67519 #ifndef SQLITE_OMIT_DEPRECATED
   67520 /*
   67521 ** Deprecated external interface.  Internal/core SQLite code
   67522 ** should call sqlite3TransferBindings.
   67523 **
   67524 ** Is is misuse to call this routine with statements from different
   67525 ** database connections.  But as this is a deprecated interface, we
   67526 ** will not bother to check for that condition.
   67527 **
   67528 ** If the two statements contain a different number of bindings, then
   67529 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
   67530 ** SQLITE_OK is returned.
   67531 */
   67532 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   67533   Vdbe *pFrom = (Vdbe*)pFromStmt;
   67534   Vdbe *pTo = (Vdbe*)pToStmt;
   67535   if( pFrom->nVar!=pTo->nVar ){
   67536     return SQLITE_ERROR;
   67537   }
   67538   if( pTo->isPrepareV2 && pTo->expmask ){
   67539     pTo->expired = 1;
   67540   }
   67541   if( pFrom->isPrepareV2 && pFrom->expmask ){
   67542     pFrom->expired = 1;
   67543   }
   67544   return sqlite3TransferBindings(pFromStmt, pToStmt);
   67545 }
   67546 #endif
   67547 
   67548 /*
   67549 ** Return the sqlite3* database handle to which the prepared statement given
   67550 ** in the argument belongs.  This is the same database handle that was
   67551 ** the first argument to the sqlite3_prepare() that was used to create
   67552 ** the statement in the first place.
   67553 */
   67554 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
   67555   return pStmt ? ((Vdbe*)pStmt)->db : 0;
   67556 }
   67557 
   67558 /*
   67559 ** Return true if the prepared statement is guaranteed to not modify the
   67560 ** database.
   67561 */
   67562 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
   67563   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
   67564 }
   67565 
   67566 /*
   67567 ** Return true if the prepared statement is in need of being reset.
   67568 */
   67569 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
   67570   Vdbe *v = (Vdbe*)pStmt;
   67571   return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
   67572 }
   67573 
   67574 /*
   67575 ** Return a pointer to the next prepared statement after pStmt associated
   67576 ** with database connection pDb.  If pStmt is NULL, return the first
   67577 ** prepared statement for the database connection.  Return NULL if there
   67578 ** are no more.
   67579 */
   67580 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
   67581   sqlite3_stmt *pNext;
   67582   sqlite3_mutex_enter(pDb->mutex);
   67583   if( pStmt==0 ){
   67584     pNext = (sqlite3_stmt*)pDb->pVdbe;
   67585   }else{
   67586     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
   67587   }
   67588   sqlite3_mutex_leave(pDb->mutex);
   67589   return pNext;
   67590 }
   67591 
   67592 /*
   67593 ** Return the value of a status counter for a prepared statement
   67594 */
   67595 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
   67596   Vdbe *pVdbe = (Vdbe*)pStmt;
   67597   u32 v = pVdbe->aCounter[op];
   67598   if( resetFlag ) pVdbe->aCounter[op] = 0;
   67599   return (int)v;
   67600 }
   67601 
   67602 /************** End of vdbeapi.c *********************************************/
   67603 /************** Begin file vdbetrace.c ***************************************/
   67604 /*
   67605 ** 2009 November 25
   67606 **
   67607 ** The author disclaims copyright to this source code.  In place of
   67608 ** a legal notice, here is a blessing:
   67609 **
   67610 **    May you do good and not evil.
   67611 **    May you find forgiveness for yourself and forgive others.
   67612 **    May you share freely, never taking more than you give.
   67613 **
   67614 *************************************************************************
   67615 **
   67616 ** This file contains code used to insert the values of host parameters
   67617 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
   67618 **
   67619 ** The Vdbe parse-tree explainer is also found here.
   67620 */
   67621 
   67622 #ifndef SQLITE_OMIT_TRACE
   67623 
   67624 /*
   67625 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
   67626 ** bytes in this text up to but excluding the first character in
   67627 ** a host parameter.  If the text contains no host parameters, return
   67628 ** the total number of bytes in the text.
   67629 */
   67630 static int findNextHostParameter(const char *zSql, int *pnToken){
   67631   int tokenType;
   67632   int nTotal = 0;
   67633   int n;
   67634 
   67635   *pnToken = 0;
   67636   while( zSql[0] ){
   67637     n = sqlite3GetToken((u8*)zSql, &tokenType);
   67638     assert( n>0 && tokenType!=TK_ILLEGAL );
   67639     if( tokenType==TK_VARIABLE ){
   67640       *pnToken = n;
   67641       break;
   67642     }
   67643     nTotal += n;
   67644     zSql += n;
   67645   }
   67646   return nTotal;
   67647 }
   67648 
   67649 /*
   67650 ** This function returns a pointer to a nul-terminated string in memory
   67651 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
   67652 ** string contains a copy of zRawSql but with host parameters expanded to
   67653 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
   67654 ** then the returned string holds a copy of zRawSql with "-- " prepended
   67655 ** to each line of text.
   67656 **
   67657 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
   67658 ** then long strings and blobs are truncated to that many bytes.  This
   67659 ** can be used to prevent unreasonably large trace strings when dealing
   67660 ** with large (multi-megabyte) strings and blobs.
   67661 **
   67662 ** The calling function is responsible for making sure the memory returned
   67663 ** is eventually freed.
   67664 **
   67665 ** ALGORITHM:  Scan the input string looking for host parameters in any of
   67666 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
   67667 ** string literals, quoted identifier names, and comments.  For text forms,
   67668 ** the host parameter index is found by scanning the perpared
   67669 ** statement for the corresponding OP_Variable opcode.  Once the host
   67670 ** parameter index is known, locate the value in p->aVar[].  Then render
   67671 ** the value as a literal in place of the host parameter name.
   67672 */
   67673 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
   67674   Vdbe *p,                 /* The prepared statement being evaluated */
   67675   const char *zRawSql      /* Raw text of the SQL statement */
   67676 ){
   67677   sqlite3 *db;             /* The database connection */
   67678   int idx = 0;             /* Index of a host parameter */
   67679   int nextIndex = 1;       /* Index of next ? host parameter */
   67680   int n;                   /* Length of a token prefix */
   67681   int nToken;              /* Length of the parameter token */
   67682   int i;                   /* Loop counter */
   67683   Mem *pVar;               /* Value of a host parameter */
   67684   StrAccum out;            /* Accumulate the output here */
   67685   char zBase[100];         /* Initial working space */
   67686 
   67687   db = p->db;
   67688   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
   67689                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   67690   out.db = db;
   67691   if( db->nVdbeExec>1 ){
   67692     while( *zRawSql ){
   67693       const char *zStart = zRawSql;
   67694       while( *(zRawSql++)!='\n' && *zRawSql );
   67695       sqlite3StrAccumAppend(&out, "-- ", 3);
   67696       assert( (zRawSql - zStart) > 0 );
   67697       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
   67698     }
   67699   }else{
   67700     while( zRawSql[0] ){
   67701       n = findNextHostParameter(zRawSql, &nToken);
   67702       assert( n>0 );
   67703       sqlite3StrAccumAppend(&out, zRawSql, n);
   67704       zRawSql += n;
   67705       assert( zRawSql[0] || nToken==0 );
   67706       if( nToken==0 ) break;
   67707       if( zRawSql[0]=='?' ){
   67708         if( nToken>1 ){
   67709           assert( sqlite3Isdigit(zRawSql[1]) );
   67710           sqlite3GetInt32(&zRawSql[1], &idx);
   67711         }else{
   67712           idx = nextIndex;
   67713         }
   67714       }else{
   67715         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
   67716         testcase( zRawSql[0]==':' );
   67717         testcase( zRawSql[0]=='$' );
   67718         testcase( zRawSql[0]=='@' );
   67719         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
   67720         assert( idx>0 );
   67721       }
   67722       zRawSql += nToken;
   67723       nextIndex = idx + 1;
   67724       assert( idx>0 && idx<=p->nVar );
   67725       pVar = &p->aVar[idx-1];
   67726       if( pVar->flags & MEM_Null ){
   67727         sqlite3StrAccumAppend(&out, "NULL", 4);
   67728       }else if( pVar->flags & MEM_Int ){
   67729         sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
   67730       }else if( pVar->flags & MEM_Real ){
   67731         sqlite3XPrintf(&out, 0, "%!.15g", pVar->r);
   67732       }else if( pVar->flags & MEM_Str ){
   67733         int nOut;  /* Number of bytes of the string text to include in output */
   67734 #ifndef SQLITE_OMIT_UTF16
   67735         u8 enc = ENC(db);
   67736         Mem utf8;
   67737         if( enc!=SQLITE_UTF8 ){
   67738           memset(&utf8, 0, sizeof(utf8));
   67739           utf8.db = db;
   67740           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
   67741           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
   67742           pVar = &utf8;
   67743         }
   67744 #endif
   67745         nOut = pVar->n;
   67746 #ifdef SQLITE_TRACE_SIZE_LIMIT
   67747         if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
   67748           nOut = SQLITE_TRACE_SIZE_LIMIT;
   67749           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
   67750         }
   67751 #endif
   67752         sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
   67753 #ifdef SQLITE_TRACE_SIZE_LIMIT
   67754         if( nOut<pVar->n ){
   67755           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
   67756         }
   67757 #endif
   67758 #ifndef SQLITE_OMIT_UTF16
   67759         if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
   67760 #endif
   67761       }else if( pVar->flags & MEM_Zero ){
   67762         sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
   67763       }else{
   67764         int nOut;  /* Number of bytes of the blob to include in output */
   67765         assert( pVar->flags & MEM_Blob );
   67766         sqlite3StrAccumAppend(&out, "x'", 2);
   67767         nOut = pVar->n;
   67768 #ifdef SQLITE_TRACE_SIZE_LIMIT
   67769         if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
   67770 #endif
   67771         for(i=0; i<nOut; i++){
   67772           sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
   67773         }
   67774         sqlite3StrAccumAppend(&out, "'", 1);
   67775 #ifdef SQLITE_TRACE_SIZE_LIMIT
   67776         if( nOut<pVar->n ){
   67777           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
   67778         }
   67779 #endif
   67780       }
   67781     }
   67782   }
   67783   return sqlite3StrAccumFinish(&out);
   67784 }
   67785 
   67786 #endif /* #ifndef SQLITE_OMIT_TRACE */
   67787 
   67788 /*****************************************************************************
   67789 ** The following code implements the data-structure explaining logic
   67790 ** for the Vdbe.
   67791 */
   67792 
   67793 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   67794 
   67795 /*
   67796 ** Allocate a new Explain object
   67797 */
   67798 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
   67799   if( pVdbe ){
   67800     Explain *p;
   67801     sqlite3BeginBenignMalloc();
   67802     p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
   67803     if( p ){
   67804       p->pVdbe = pVdbe;
   67805       sqlite3_free(pVdbe->pExplain);
   67806       pVdbe->pExplain = p;
   67807       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
   67808                           SQLITE_MAX_LENGTH);
   67809       p->str.useMalloc = 2;
   67810     }else{
   67811       sqlite3EndBenignMalloc();
   67812     }
   67813   }
   67814 }
   67815 
   67816 /*
   67817 ** Return true if the Explain ends with a new-line.
   67818 */
   67819 static int endsWithNL(Explain *p){
   67820   return p && p->str.zText && p->str.nChar
   67821            && p->str.zText[p->str.nChar-1]=='\n';
   67822 }
   67823 
   67824 /*
   67825 ** Append text to the indentation
   67826 */
   67827 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
   67828   Explain *p;
   67829   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
   67830     va_list ap;
   67831     if( p->nIndent && endsWithNL(p) ){
   67832       int n = p->nIndent;
   67833       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
   67834       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
   67835     }
   67836     va_start(ap, zFormat);
   67837     sqlite3VXPrintf(&p->str, SQLITE_PRINTF_INTERNAL, zFormat, ap);
   67838     va_end(ap);
   67839   }
   67840 }
   67841 
   67842 /*
   67843 ** Append a '\n' if there is not already one.
   67844 */
   67845 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
   67846   Explain *p;
   67847   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
   67848     sqlite3StrAccumAppend(&p->str, "\n", 1);
   67849   }
   67850 }
   67851 
   67852 /*
   67853 ** Push a new indentation level.  Subsequent lines will be indented
   67854 ** so that they begin at the current cursor position.
   67855 */
   67856 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
   67857   Explain *p;
   67858   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
   67859     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
   67860       const char *z = p->str.zText;
   67861       int i = p->str.nChar-1;
   67862       int x;
   67863       while( i>=0 && z[i]!='\n' ){ i--; }
   67864       x = (p->str.nChar - 1) - i;
   67865       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
   67866         x = p->aIndent[p->nIndent-1];
   67867       }
   67868       p->aIndent[p->nIndent] = x;
   67869     }
   67870     p->nIndent++;
   67871   }
   67872 }
   67873 
   67874 /*
   67875 ** Pop the indentation stack by one level.
   67876 */
   67877 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
   67878   if( p && p->pExplain ) p->pExplain->nIndent--;
   67879 }
   67880 
   67881 /*
   67882 ** Free the indentation structure
   67883 */
   67884 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
   67885   if( pVdbe && pVdbe->pExplain ){
   67886     sqlite3_free(pVdbe->zExplain);
   67887     sqlite3ExplainNL(pVdbe);
   67888     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
   67889     sqlite3_free(pVdbe->pExplain);
   67890     pVdbe->pExplain = 0;
   67891     sqlite3EndBenignMalloc();
   67892   }
   67893 }
   67894 
   67895 /*
   67896 ** Return the explanation of a virtual machine.
   67897 */
   67898 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
   67899   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
   67900 }
   67901 #endif /* defined(SQLITE_DEBUG) */
   67902 
   67903 /************** End of vdbetrace.c *******************************************/
   67904 /************** Begin file vdbe.c ********************************************/
   67905 /*
   67906 ** 2001 September 15
   67907 **
   67908 ** The author disclaims copyright to this source code.  In place of
   67909 ** a legal notice, here is a blessing:
   67910 **
   67911 **    May you do good and not evil.
   67912 **    May you find forgiveness for yourself and forgive others.
   67913 **    May you share freely, never taking more than you give.
   67914 **
   67915 *************************************************************************
   67916 ** The code in this file implements the function that runs the
   67917 ** bytecode of a prepared statement.
   67918 **
   67919 ** Various scripts scan this source file in order to generate HTML
   67920 ** documentation, headers files, or other derived files.  The formatting
   67921 ** of the code in this file is, therefore, important.  See other comments
   67922 ** in this file for details.  If in doubt, do not deviate from existing
   67923 ** commenting and indentation practices when changing or adding code.
   67924 */
   67925 
   67926 /*
   67927 ** Invoke this macro on memory cells just prior to changing the
   67928 ** value of the cell.  This macro verifies that shallow copies are
   67929 ** not misused.  A shallow copy of a string or blob just copies a
   67930 ** pointer to the string or blob, not the content.  If the original
   67931 ** is changed while the copy is still in use, the string or blob might
   67932 ** be changed out from under the copy.  This macro verifies that nothing
   67933 ** like that ever happens.
   67934 */
   67935 #ifdef SQLITE_DEBUG
   67936 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
   67937 #else
   67938 # define memAboutToChange(P,M)
   67939 #endif
   67940 
   67941 /*
   67942 ** The following global variable is incremented every time a cursor
   67943 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
   67944 ** procedures use this information to make sure that indices are
   67945 ** working correctly.  This variable has no function other than to
   67946 ** help verify the correct operation of the library.
   67947 */
   67948 #ifdef SQLITE_TEST
   67949 SQLITE_API int sqlite3_search_count = 0;
   67950 #endif
   67951 
   67952 /*
   67953 ** When this global variable is positive, it gets decremented once before
   67954 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
   67955 ** field of the sqlite3 structure is set in order to simulate an interrupt.
   67956 **
   67957 ** This facility is used for testing purposes only.  It does not function
   67958 ** in an ordinary build.
   67959 */
   67960 #ifdef SQLITE_TEST
   67961 SQLITE_API int sqlite3_interrupt_count = 0;
   67962 #endif
   67963 
   67964 /*
   67965 ** The next global variable is incremented each type the OP_Sort opcode
   67966 ** is executed.  The test procedures use this information to make sure that
   67967 ** sorting is occurring or not occurring at appropriate times.   This variable
   67968 ** has no function other than to help verify the correct operation of the
   67969 ** library.
   67970 */
   67971 #ifdef SQLITE_TEST
   67972 SQLITE_API int sqlite3_sort_count = 0;
   67973 #endif
   67974 
   67975 /*
   67976 ** The next global variable records the size of the largest MEM_Blob
   67977 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
   67978 ** use this information to make sure that the zero-blob functionality
   67979 ** is working correctly.   This variable has no function other than to
   67980 ** help verify the correct operation of the library.
   67981 */
   67982 #ifdef SQLITE_TEST
   67983 SQLITE_API int sqlite3_max_blobsize = 0;
   67984 static void updateMaxBlobsize(Mem *p){
   67985   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
   67986     sqlite3_max_blobsize = p->n;
   67987   }
   67988 }
   67989 #endif
   67990 
   67991 /*
   67992 ** The next global variable is incremented each time the OP_Found opcode
   67993 ** is executed. This is used to test whether or not the foreign key
   67994 ** operation implemented using OP_FkIsZero is working. This variable
   67995 ** has no function other than to help verify the correct operation of the
   67996 ** library.
   67997 */
   67998 #ifdef SQLITE_TEST
   67999 SQLITE_API int sqlite3_found_count = 0;
   68000 #endif
   68001 
   68002 /*
   68003 ** Test a register to see if it exceeds the current maximum blob size.
   68004 ** If it does, record the new maximum blob size.
   68005 */
   68006 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
   68007 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
   68008 #else
   68009 # define UPDATE_MAX_BLOBSIZE(P)
   68010 #endif
   68011 
   68012 /*
   68013 ** Invoke the VDBE coverage callback, if that callback is defined.  This
   68014 ** feature is used for test suite validation only and does not appear an
   68015 ** production builds.
   68016 **
   68017 ** M is an integer, 2 or 3, that indices how many different ways the
   68018 ** branch can go.  It is usually 2.  "I" is the direction the branch
   68019 ** goes.  0 means falls through.  1 means branch is taken.  2 means the
   68020 ** second alternative branch is taken.
   68021 **
   68022 ** iSrcLine is the source code line (from the __LINE__ macro) that
   68023 ** generated the VDBE instruction.  This instrumentation assumes that all
   68024 ** source code is in a single file (the amalgamation).  Special values 1
   68025 ** and 2 for the iSrcLine parameter mean that this particular branch is
   68026 ** always taken or never taken, respectively.
   68027 */
   68028 #if !defined(SQLITE_VDBE_COVERAGE)
   68029 # define VdbeBranchTaken(I,M)
   68030 #else
   68031 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
   68032   static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
   68033     if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
   68034       M = iSrcLine;
   68035       /* Assert the truth of VdbeCoverageAlwaysTaken() and
   68036       ** VdbeCoverageNeverTaken() */
   68037       assert( (M & I)==I );
   68038     }else{
   68039       if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
   68040       sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
   68041                                       iSrcLine,I,M);
   68042     }
   68043   }
   68044 #endif
   68045 
   68046 /*
   68047 ** Convert the given register into a string if it isn't one
   68048 ** already. Return non-zero if a malloc() fails.
   68049 */
   68050 #define Stringify(P, enc) \
   68051    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
   68052      { goto no_mem; }
   68053 
   68054 /*
   68055 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
   68056 ** a pointer to a dynamically allocated string where some other entity
   68057 ** is responsible for deallocating that string.  Because the register
   68058 ** does not control the string, it might be deleted without the register
   68059 ** knowing it.
   68060 **
   68061 ** This routine converts an ephemeral string into a dynamically allocated
   68062 ** string that the register itself controls.  In other words, it
   68063 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
   68064 */
   68065 #define Deephemeralize(P) \
   68066    if( ((P)->flags&MEM_Ephem)!=0 \
   68067        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
   68068 
   68069 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
   68070 #define isSorter(x) ((x)->pSorter!=0)
   68071 
   68072 /*
   68073 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
   68074 ** if we run out of memory.
   68075 */
   68076 static VdbeCursor *allocateCursor(
   68077   Vdbe *p,              /* The virtual machine */
   68078   int iCur,             /* Index of the new VdbeCursor */
   68079   int nField,           /* Number of fields in the table or index */
   68080   int iDb,              /* Database the cursor belongs to, or -1 */
   68081   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
   68082 ){
   68083   /* Find the memory cell that will be used to store the blob of memory
   68084   ** required for this VdbeCursor structure. It is convenient to use a
   68085   ** vdbe memory cell to manage the memory allocation required for a
   68086   ** VdbeCursor structure for the following reasons:
   68087   **
   68088   **   * Sometimes cursor numbers are used for a couple of different
   68089   **     purposes in a vdbe program. The different uses might require
   68090   **     different sized allocations. Memory cells provide growable
   68091   **     allocations.
   68092   **
   68093   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
   68094   **     be freed lazily via the sqlite3_release_memory() API. This
   68095   **     minimizes the number of malloc calls made by the system.
   68096   **
   68097   ** Memory cells for cursors are allocated at the top of the address
   68098   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
   68099   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
   68100   */
   68101   Mem *pMem = &p->aMem[p->nMem-iCur];
   68102 
   68103   int nByte;
   68104   VdbeCursor *pCx = 0;
   68105   nByte =
   68106       ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
   68107       (isBtreeCursor?sqlite3BtreeCursorSize():0);
   68108 
   68109   assert( iCur<p->nCursor );
   68110   if( p->apCsr[iCur] ){
   68111     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
   68112     p->apCsr[iCur] = 0;
   68113   }
   68114   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   68115     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
   68116     memset(pCx, 0, sizeof(VdbeCursor));
   68117     pCx->iDb = iDb;
   68118     pCx->nField = nField;
   68119     if( isBtreeCursor ){
   68120       pCx->pCursor = (BtCursor*)
   68121           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
   68122       sqlite3BtreeCursorZero(pCx->pCursor);
   68123     }
   68124   }
   68125   return pCx;
   68126 }
   68127 
   68128 /*
   68129 ** Try to convert a value into a numeric representation if we can
   68130 ** do so without loss of information.  In other words, if the string
   68131 ** looks like a number, convert it into a number.  If it does not
   68132 ** look like a number, leave it alone.
   68133 */
   68134 static void applyNumericAffinity(Mem *pRec){
   68135   double rValue;
   68136   i64 iValue;
   68137   u8 enc = pRec->enc;
   68138   if( (pRec->flags&MEM_Str)==0 ) return;
   68139   if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
   68140   if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
   68141     pRec->u.i = iValue;
   68142     pRec->flags |= MEM_Int;
   68143   }else{
   68144     pRec->r = rValue;
   68145     pRec->flags |= MEM_Real;
   68146   }
   68147 }
   68148 #define ApplyNumericAffinity(X)  \
   68149    if(((X)->flags&(MEM_Real|MEM_Int))==0){applyNumericAffinity(X);}
   68150 
   68151 /*
   68152 ** Processing is determine by the affinity parameter:
   68153 **
   68154 ** SQLITE_AFF_INTEGER:
   68155 ** SQLITE_AFF_REAL:
   68156 ** SQLITE_AFF_NUMERIC:
   68157 **    Try to convert pRec to an integer representation or a
   68158 **    floating-point representation if an integer representation
   68159 **    is not possible.  Note that the integer representation is
   68160 **    always preferred, even if the affinity is REAL, because
   68161 **    an integer representation is more space efficient on disk.
   68162 **
   68163 ** SQLITE_AFF_TEXT:
   68164 **    Convert pRec to a text representation.
   68165 **
   68166 ** SQLITE_AFF_NONE:
   68167 **    No-op.  pRec is unchanged.
   68168 */
   68169 static void applyAffinity(
   68170   Mem *pRec,          /* The value to apply affinity to */
   68171   char affinity,      /* The affinity to be applied */
   68172   u8 enc              /* Use this text encoding */
   68173 ){
   68174   if( affinity==SQLITE_AFF_TEXT ){
   68175     /* Only attempt the conversion to TEXT if there is an integer or real
   68176     ** representation (blob and NULL do not get converted) but no string
   68177     ** representation.
   68178     */
   68179     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
   68180       sqlite3VdbeMemStringify(pRec, enc);
   68181     }
   68182     pRec->flags &= ~(MEM_Real|MEM_Int);
   68183   }else if( affinity!=SQLITE_AFF_NONE ){
   68184     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
   68185              || affinity==SQLITE_AFF_NUMERIC );
   68186     ApplyNumericAffinity(pRec);
   68187     if( pRec->flags & MEM_Real ){
   68188       sqlite3VdbeIntegerAffinity(pRec);
   68189     }
   68190   }
   68191 }
   68192 
   68193 /*
   68194 ** Try to convert the type of a function argument or a result column
   68195 ** into a numeric representation.  Use either INTEGER or REAL whichever
   68196 ** is appropriate.  But only do the conversion if it is possible without
   68197 ** loss of information and return the revised type of the argument.
   68198 */
   68199 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
   68200   int eType = sqlite3_value_type(pVal);
   68201   if( eType==SQLITE_TEXT ){
   68202     Mem *pMem = (Mem*)pVal;
   68203     applyNumericAffinity(pMem);
   68204     eType = sqlite3_value_type(pVal);
   68205   }
   68206   return eType;
   68207 }
   68208 
   68209 /*
   68210 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
   68211 ** not the internal Mem* type.
   68212 */
   68213 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
   68214   sqlite3_value *pVal,
   68215   u8 affinity,
   68216   u8 enc
   68217 ){
   68218   applyAffinity((Mem *)pVal, affinity, enc);
   68219 }
   68220 
   68221 /*
   68222 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
   68223 ** none.
   68224 **
   68225 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
   68226 ** But it does set pMem->r and pMem->u.i appropriately.
   68227 */
   68228 static u16 numericType(Mem *pMem){
   68229   if( pMem->flags & (MEM_Int|MEM_Real) ){
   68230     return pMem->flags & (MEM_Int|MEM_Real);
   68231   }
   68232   if( pMem->flags & (MEM_Str|MEM_Blob) ){
   68233     if( sqlite3AtoF(pMem->z, &pMem->r, pMem->n, pMem->enc)==0 ){
   68234       return 0;
   68235     }
   68236     if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
   68237       return MEM_Int;
   68238     }
   68239     return MEM_Real;
   68240   }
   68241   return 0;
   68242 }
   68243 
   68244 #ifdef SQLITE_DEBUG
   68245 /*
   68246 ** Write a nice string representation of the contents of cell pMem
   68247 ** into buffer zBuf, length nBuf.
   68248 */
   68249 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
   68250   char *zCsr = zBuf;
   68251   int f = pMem->flags;
   68252 
   68253   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
   68254 
   68255   if( f&MEM_Blob ){
   68256     int i;
   68257     char c;
   68258     if( f & MEM_Dyn ){
   68259       c = 'z';
   68260       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   68261     }else if( f & MEM_Static ){
   68262       c = 't';
   68263       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   68264     }else if( f & MEM_Ephem ){
   68265       c = 'e';
   68266       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   68267     }else{
   68268       c = 's';
   68269     }
   68270 
   68271     sqlite3_snprintf(100, zCsr, "%c", c);
   68272     zCsr += sqlite3Strlen30(zCsr);
   68273     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
   68274     zCsr += sqlite3Strlen30(zCsr);
   68275     for(i=0; i<16 && i<pMem->n; i++){
   68276       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
   68277       zCsr += sqlite3Strlen30(zCsr);
   68278     }
   68279     for(i=0; i<16 && i<pMem->n; i++){
   68280       char z = pMem->z[i];
   68281       if( z<32 || z>126 ) *zCsr++ = '.';
   68282       else *zCsr++ = z;
   68283     }
   68284 
   68285     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
   68286     zCsr += sqlite3Strlen30(zCsr);
   68287     if( f & MEM_Zero ){
   68288       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
   68289       zCsr += sqlite3Strlen30(zCsr);
   68290     }
   68291     *zCsr = '\0';
   68292   }else if( f & MEM_Str ){
   68293     int j, k;
   68294     zBuf[0] = ' ';
   68295     if( f & MEM_Dyn ){
   68296       zBuf[1] = 'z';
   68297       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   68298     }else if( f & MEM_Static ){
   68299       zBuf[1] = 't';
   68300       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   68301     }else if( f & MEM_Ephem ){
   68302       zBuf[1] = 'e';
   68303       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   68304     }else{
   68305       zBuf[1] = 's';
   68306     }
   68307     k = 2;
   68308     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
   68309     k += sqlite3Strlen30(&zBuf[k]);
   68310     zBuf[k++] = '[';
   68311     for(j=0; j<15 && j<pMem->n; j++){
   68312       u8 c = pMem->z[j];
   68313       if( c>=0x20 && c<0x7f ){
   68314         zBuf[k++] = c;
   68315       }else{
   68316         zBuf[k++] = '.';
   68317       }
   68318     }
   68319     zBuf[k++] = ']';
   68320     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
   68321     k += sqlite3Strlen30(&zBuf[k]);
   68322     zBuf[k++] = 0;
   68323   }
   68324 }
   68325 #endif
   68326 
   68327 #ifdef SQLITE_DEBUG
   68328 /*
   68329 ** Print the value of a register for tracing purposes:
   68330 */
   68331 static void memTracePrint(Mem *p){
   68332   if( p->flags & MEM_Undefined ){
   68333     printf(" undefined");
   68334   }else if( p->flags & MEM_Null ){
   68335     printf(" NULL");
   68336   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
   68337     printf(" si:%lld", p->u.i);
   68338   }else if( p->flags & MEM_Int ){
   68339     printf(" i:%lld", p->u.i);
   68340 #ifndef SQLITE_OMIT_FLOATING_POINT
   68341   }else if( p->flags & MEM_Real ){
   68342     printf(" r:%g", p->r);
   68343 #endif
   68344   }else if( p->flags & MEM_RowSet ){
   68345     printf(" (rowset)");
   68346   }else{
   68347     char zBuf[200];
   68348     sqlite3VdbeMemPrettyPrint(p, zBuf);
   68349     printf(" %s", zBuf);
   68350   }
   68351 }
   68352 static void registerTrace(int iReg, Mem *p){
   68353   printf("REG[%d] = ", iReg);
   68354   memTracePrint(p);
   68355   printf("\n");
   68356 }
   68357 #endif
   68358 
   68359 #ifdef SQLITE_DEBUG
   68360 #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
   68361 #else
   68362 #  define REGISTER_TRACE(R,M)
   68363 #endif
   68364 
   68365 
   68366 #ifdef VDBE_PROFILE
   68367 
   68368 /*
   68369 ** hwtime.h contains inline assembler code for implementing
   68370 ** high-performance timing routines.
   68371 */
   68372 /************** Include hwtime.h in the middle of vdbe.c *********************/
   68373 /************** Begin file hwtime.h ******************************************/
   68374 /*
   68375 ** 2008 May 27
   68376 **
   68377 ** The author disclaims copyright to this source code.  In place of
   68378 ** a legal notice, here is a blessing:
   68379 **
   68380 **    May you do good and not evil.
   68381 **    May you find forgiveness for yourself and forgive others.
   68382 **    May you share freely, never taking more than you give.
   68383 **
   68384 ******************************************************************************
   68385 **
   68386 ** This file contains inline asm code for retrieving "high-performance"
   68387 ** counters for x86 class CPUs.
   68388 */
   68389 #ifndef _HWTIME_H_
   68390 #define _HWTIME_H_
   68391 
   68392 /*
   68393 ** The following routine only works on pentium-class (or newer) processors.
   68394 ** It uses the RDTSC opcode to read the cycle count value out of the
   68395 ** processor and returns that value.  This can be used for high-res
   68396 ** profiling.
   68397 */
   68398 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   68399       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   68400 
   68401   #if defined(__GNUC__)
   68402 
   68403   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   68404      unsigned int lo, hi;
   68405      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   68406      return (sqlite_uint64)hi << 32 | lo;
   68407   }
   68408 
   68409   #elif defined(_MSC_VER)
   68410 
   68411   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   68412      __asm {
   68413         rdtsc
   68414         ret       ; return value at EDX:EAX
   68415      }
   68416   }
   68417 
   68418   #endif
   68419 
   68420 #elif (defined(__GNUC__) && defined(__x86_64__))
   68421 
   68422   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   68423       unsigned long val;
   68424       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   68425       return val;
   68426   }
   68427 
   68428 #elif (defined(__GNUC__) && defined(__ppc__))
   68429 
   68430   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   68431       unsigned long long retval;
   68432       unsigned long junk;
   68433       __asm__ __volatile__ ("\n\
   68434           1:      mftbu   %1\n\
   68435                   mftb    %L0\n\
   68436                   mftbu   %0\n\
   68437                   cmpw    %0,%1\n\
   68438                   bne     1b"
   68439                   : "=r" (retval), "=r" (junk));
   68440       return retval;
   68441   }
   68442 
   68443 #else
   68444 
   68445   #error Need implementation of sqlite3Hwtime() for your platform.
   68446 
   68447   /*
   68448   ** To compile without implementing sqlite3Hwtime() for your platform,
   68449   ** you can remove the above #error and use the following
   68450   ** stub function.  You will lose timing support for many
   68451   ** of the debugging and testing utilities, but it should at
   68452   ** least compile and run.
   68453   */
   68454 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   68455 
   68456 #endif
   68457 
   68458 #endif /* !defined(_HWTIME_H_) */
   68459 
   68460 /************** End of hwtime.h **********************************************/
   68461 /************** Continuing where we left off in vdbe.c ***********************/
   68462 
   68463 #endif
   68464 
   68465 #ifndef NDEBUG
   68466 /*
   68467 ** This function is only called from within an assert() expression. It
   68468 ** checks that the sqlite3.nTransaction variable is correctly set to
   68469 ** the number of non-transaction savepoints currently in the
   68470 ** linked list starting at sqlite3.pSavepoint.
   68471 **
   68472 ** Usage:
   68473 **
   68474 **     assert( checkSavepointCount(db) );
   68475 */
   68476 static int checkSavepointCount(sqlite3 *db){
   68477   int n = 0;
   68478   Savepoint *p;
   68479   for(p=db->pSavepoint; p; p=p->pNext) n++;
   68480   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
   68481   return 1;
   68482 }
   68483 #endif
   68484 
   68485 
   68486 /*
   68487 ** Execute as much of a VDBE program as we can.
   68488 ** This is the core of sqlite3_step().
   68489 */
   68490 SQLITE_PRIVATE int sqlite3VdbeExec(
   68491   Vdbe *p                    /* The VDBE */
   68492 ){
   68493   int pc=0;                  /* The program counter */
   68494   Op *aOp = p->aOp;          /* Copy of p->aOp */
   68495   Op *pOp;                   /* Current operation */
   68496   int rc = SQLITE_OK;        /* Value to return */
   68497   sqlite3 *db = p->db;       /* The database */
   68498   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
   68499   u8 encoding = ENC(db);     /* The database encoding */
   68500   int iCompare = 0;          /* Result of last OP_Compare operation */
   68501   unsigned nVmStep = 0;      /* Number of virtual machine steps */
   68502 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   68503   unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
   68504 #endif
   68505   Mem *aMem = p->aMem;       /* Copy of p->aMem */
   68506   Mem *pIn1 = 0;             /* 1st input operand */
   68507   Mem *pIn2 = 0;             /* 2nd input operand */
   68508   Mem *pIn3 = 0;             /* 3rd input operand */
   68509   Mem *pOut = 0;             /* Output operand */
   68510   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
   68511   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
   68512 #ifdef VDBE_PROFILE
   68513   u64 start;                 /* CPU clock count at start of opcode */
   68514 #endif
   68515   /*** INSERT STACK UNION HERE ***/
   68516 
   68517   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   68518   sqlite3VdbeEnter(p);
   68519   if( p->rc==SQLITE_NOMEM ){
   68520     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   68521     ** sqlite3_column_text16() failed.  */
   68522     goto no_mem;
   68523   }
   68524   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   68525   assert( p->bIsReader || p->readOnly!=0 );
   68526   p->rc = SQLITE_OK;
   68527   p->iCurrentTime = 0;
   68528   assert( p->explain==0 );
   68529   p->pResultSet = 0;
   68530   db->busyHandler.nBusy = 0;
   68531   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   68532   sqlite3VdbeIOTraceSql(p);
   68533 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   68534   if( db->xProgress ){
   68535     assert( 0 < db->nProgressOps );
   68536     nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
   68537     if( nProgressLimit==0 ){
   68538       nProgressLimit = db->nProgressOps;
   68539     }else{
   68540       nProgressLimit %= (unsigned)db->nProgressOps;
   68541     }
   68542   }
   68543 #endif
   68544 #ifdef SQLITE_DEBUG
   68545   sqlite3BeginBenignMalloc();
   68546   if( p->pc==0
   68547    && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
   68548   ){
   68549     int i;
   68550     int once = 1;
   68551     sqlite3VdbePrintSql(p);
   68552     if( p->db->flags & SQLITE_VdbeListing ){
   68553       printf("VDBE Program Listing:\n");
   68554       for(i=0; i<p->nOp; i++){
   68555         sqlite3VdbePrintOp(stdout, i, &aOp[i]);
   68556       }
   68557     }
   68558     if( p->db->flags & SQLITE_VdbeEQP ){
   68559       for(i=0; i<p->nOp; i++){
   68560         if( aOp[i].opcode==OP_Explain ){
   68561           if( once ) printf("VDBE Query Plan:\n");
   68562           printf("%s\n", aOp[i].p4.z);
   68563           once = 0;
   68564         }
   68565       }
   68566     }
   68567     if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
   68568   }
   68569   sqlite3EndBenignMalloc();
   68570 #endif
   68571   for(pc=p->pc; rc==SQLITE_OK; pc++){
   68572     assert( pc>=0 && pc<p->nOp );
   68573     if( db->mallocFailed ) goto no_mem;
   68574 #ifdef VDBE_PROFILE
   68575     start = sqlite3Hwtime();
   68576 #endif
   68577     nVmStep++;
   68578     pOp = &aOp[pc];
   68579 
   68580     /* Only allow tracing if SQLITE_DEBUG is defined.
   68581     */
   68582 #ifdef SQLITE_DEBUG
   68583     if( db->flags & SQLITE_VdbeTrace ){
   68584       sqlite3VdbePrintOp(stdout, pc, pOp);
   68585     }
   68586 #endif
   68587 
   68588 
   68589     /* Check to see if we need to simulate an interrupt.  This only happens
   68590     ** if we have a special test build.
   68591     */
   68592 #ifdef SQLITE_TEST
   68593     if( sqlite3_interrupt_count>0 ){
   68594       sqlite3_interrupt_count--;
   68595       if( sqlite3_interrupt_count==0 ){
   68596         sqlite3_interrupt(db);
   68597       }
   68598     }
   68599 #endif
   68600 
   68601     /* On any opcode with the "out2-prerelease" tag, free any
   68602     ** external allocations out of mem[p2] and set mem[p2] to be
   68603     ** an undefined integer.  Opcodes will either fill in the integer
   68604     ** value or convert mem[p2] to a different type.
   68605     */
   68606     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
   68607     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
   68608       assert( pOp->p2>0 );
   68609       assert( pOp->p2<=(p->nMem-p->nCursor) );
   68610       pOut = &aMem[pOp->p2];
   68611       memAboutToChange(p, pOut);
   68612       VdbeMemRelease(pOut);
   68613       pOut->flags = MEM_Int;
   68614     }
   68615 
   68616     /* Sanity checking on other operands */
   68617 #ifdef SQLITE_DEBUG
   68618     if( (pOp->opflags & OPFLG_IN1)!=0 ){
   68619       assert( pOp->p1>0 );
   68620       assert( pOp->p1<=(p->nMem-p->nCursor) );
   68621       assert( memIsValid(&aMem[pOp->p1]) );
   68622       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
   68623       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
   68624     }
   68625     if( (pOp->opflags & OPFLG_IN2)!=0 ){
   68626       assert( pOp->p2>0 );
   68627       assert( pOp->p2<=(p->nMem-p->nCursor) );
   68628       assert( memIsValid(&aMem[pOp->p2]) );
   68629       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
   68630       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
   68631     }
   68632     if( (pOp->opflags & OPFLG_IN3)!=0 ){
   68633       assert( pOp->p3>0 );
   68634       assert( pOp->p3<=(p->nMem-p->nCursor) );
   68635       assert( memIsValid(&aMem[pOp->p3]) );
   68636       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
   68637       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
   68638     }
   68639     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
   68640       assert( pOp->p2>0 );
   68641       assert( pOp->p2<=(p->nMem-p->nCursor) );
   68642       memAboutToChange(p, &aMem[pOp->p2]);
   68643     }
   68644     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
   68645       assert( pOp->p3>0 );
   68646       assert( pOp->p3<=(p->nMem-p->nCursor) );
   68647       memAboutToChange(p, &aMem[pOp->p3]);
   68648     }
   68649 #endif
   68650 
   68651     switch( pOp->opcode ){
   68652 
   68653 /*****************************************************************************
   68654 ** What follows is a massive switch statement where each case implements a
   68655 ** separate instruction in the virtual machine.  If we follow the usual
   68656 ** indentation conventions, each case should be indented by 6 spaces.  But
   68657 ** that is a lot of wasted space on the left margin.  So the code within
   68658 ** the switch statement will break with convention and be flush-left. Another
   68659 ** big comment (similar to this one) will mark the point in the code where
   68660 ** we transition back to normal indentation.
   68661 **
   68662 ** The formatting of each case is important.  The makefile for SQLite
   68663 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
   68664 ** file looking for lines that begin with "case OP_".  The opcodes.h files
   68665 ** will be filled with #defines that give unique integer values to each
   68666 ** opcode and the opcodes.c file is filled with an array of strings where
   68667 ** each string is the symbolic name for the corresponding opcode.  If the
   68668 ** case statement is followed by a comment of the form "/# same as ... #/"
   68669 ** that comment is used to determine the particular value of the opcode.
   68670 **
   68671 ** Other keywords in the comment that follows each case are used to
   68672 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
   68673 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
   68674 ** the mkopcodeh.awk script for additional information.
   68675 **
   68676 ** Documentation about VDBE opcodes is generated by scanning this file
   68677 ** for lines of that contain "Opcode:".  That line and all subsequent
   68678 ** comment lines are used in the generation of the opcode.html documentation
   68679 ** file.
   68680 **
   68681 ** SUMMARY:
   68682 **
   68683 **     Formatting is important to scripts that scan this file.
   68684 **     Do not deviate from the formatting style currently in use.
   68685 **
   68686 *****************************************************************************/
   68687 
   68688 /* Opcode:  Goto * P2 * * *
   68689 **
   68690 ** An unconditional jump to address P2.
   68691 ** The next instruction executed will be
   68692 ** the one at index P2 from the beginning of
   68693 ** the program.
   68694 **
   68695 ** The P1 parameter is not actually used by this opcode.  However, it
   68696 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
   68697 ** that this Goto is the bottom of a loop and that the lines from P2 down
   68698 ** to the current line should be indented for EXPLAIN output.
   68699 */
   68700 case OP_Goto: {             /* jump */
   68701   pc = pOp->p2 - 1;
   68702 
   68703   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
   68704   ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
   68705   ** completion.  Check to see if sqlite3_interrupt() has been called
   68706   ** or if the progress callback needs to be invoked.
   68707   **
   68708   ** This code uses unstructured "goto" statements and does not look clean.
   68709   ** But that is not due to sloppy coding habits. The code is written this
   68710   ** way for performance, to avoid having to run the interrupt and progress
   68711   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
   68712   ** faster according to "valgrind --tool=cachegrind" */
   68713 check_for_interrupt:
   68714   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   68715 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   68716   /* Call the progress callback if it is configured and the required number
   68717   ** of VDBE ops have been executed (either since this invocation of
   68718   ** sqlite3VdbeExec() or since last time the progress callback was called).
   68719   ** If the progress callback returns non-zero, exit the virtual machine with
   68720   ** a return code SQLITE_ABORT.
   68721   */
   68722   if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
   68723     assert( db->nProgressOps!=0 );
   68724     nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
   68725     if( db->xProgress(db->pProgressArg) ){
   68726       rc = SQLITE_INTERRUPT;
   68727       goto vdbe_error_halt;
   68728     }
   68729   }
   68730 #endif
   68731 
   68732   break;
   68733 }
   68734 
   68735 /* Opcode:  Gosub P1 P2 * * *
   68736 **
   68737 ** Write the current address onto register P1
   68738 ** and then jump to address P2.
   68739 */
   68740 case OP_Gosub: {            /* jump */
   68741   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
   68742   pIn1 = &aMem[pOp->p1];
   68743   assert( VdbeMemDynamic(pIn1)==0 );
   68744   memAboutToChange(p, pIn1);
   68745   pIn1->flags = MEM_Int;
   68746   pIn1->u.i = pc;
   68747   REGISTER_TRACE(pOp->p1, pIn1);
   68748   pc = pOp->p2 - 1;
   68749   break;
   68750 }
   68751 
   68752 /* Opcode:  Return P1 * * * *
   68753 **
   68754 ** Jump to the next instruction after the address in register P1.  After
   68755 ** the jump, register P1 becomes undefined.
   68756 */
   68757 case OP_Return: {           /* in1 */
   68758   pIn1 = &aMem[pOp->p1];
   68759   assert( pIn1->flags==MEM_Int );
   68760   pc = (int)pIn1->u.i;
   68761   pIn1->flags = MEM_Undefined;
   68762   break;
   68763 }
   68764 
   68765 /* Opcode: InitCoroutine P1 P2 P3 * *
   68766 **
   68767 ** Set up register P1 so that it will Yield to the coroutine
   68768 ** located at address P3.
   68769 **
   68770 ** If P2!=0 then the coroutine implementation immediately follows
   68771 ** this opcode.  So jump over the coroutine implementation to
   68772 ** address P2.
   68773 **
   68774 ** See also: EndCoroutine
   68775 */
   68776 case OP_InitCoroutine: {     /* jump */
   68777   assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
   68778   assert( pOp->p2>=0 && pOp->p2<p->nOp );
   68779   assert( pOp->p3>=0 && pOp->p3<p->nOp );
   68780   pOut = &aMem[pOp->p1];
   68781   assert( !VdbeMemDynamic(pOut) );
   68782   pOut->u.i = pOp->p3 - 1;
   68783   pOut->flags = MEM_Int;
   68784   if( pOp->p2 ) pc = pOp->p2 - 1;
   68785   break;
   68786 }
   68787 
   68788 /* Opcode:  EndCoroutine P1 * * * *
   68789 **
   68790 ** The instruction at the address in register P1 is a Yield.
   68791 ** Jump to the P2 parameter of that Yield.
   68792 ** After the jump, register P1 becomes undefined.
   68793 **
   68794 ** See also: InitCoroutine
   68795 */
   68796 case OP_EndCoroutine: {           /* in1 */
   68797   VdbeOp *pCaller;
   68798   pIn1 = &aMem[pOp->p1];
   68799   assert( pIn1->flags==MEM_Int );
   68800   assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
   68801   pCaller = &aOp[pIn1->u.i];
   68802   assert( pCaller->opcode==OP_Yield );
   68803   assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
   68804   pc = pCaller->p2 - 1;
   68805   pIn1->flags = MEM_Undefined;
   68806   break;
   68807 }
   68808 
   68809 /* Opcode:  Yield P1 P2 * * *
   68810 **
   68811 ** Swap the program counter with the value in register P1.  This
   68812 ** has the effect of yielding to a coroutine.
   68813 **
   68814 ** If the coroutine that is launched by this instruction ends with
   68815 ** Yield or Return then continue to the next instruction.  But if
   68816 ** the coroutine launched by this instruction ends with
   68817 ** EndCoroutine, then jump to P2 rather than continuing with the
   68818 ** next instruction.
   68819 **
   68820 ** See also: InitCoroutine
   68821 */
   68822 case OP_Yield: {            /* in1, jump */
   68823   int pcDest;
   68824   pIn1 = &aMem[pOp->p1];
   68825   assert( VdbeMemDynamic(pIn1)==0 );
   68826   pIn1->flags = MEM_Int;
   68827   pcDest = (int)pIn1->u.i;
   68828   pIn1->u.i = pc;
   68829   REGISTER_TRACE(pOp->p1, pIn1);
   68830   pc = pcDest;
   68831   break;
   68832 }
   68833 
   68834 /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
   68835 ** Synopsis:  if r[P3]=null halt
   68836 **
   68837 ** Check the value in register P3.  If it is NULL then Halt using
   68838 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
   68839 ** value in register P3 is not NULL, then this routine is a no-op.
   68840 ** The P5 parameter should be 1.
   68841 */
   68842 case OP_HaltIfNull: {      /* in3 */
   68843   pIn3 = &aMem[pOp->p3];
   68844   if( (pIn3->flags & MEM_Null)==0 ) break;
   68845   /* Fall through into OP_Halt */
   68846 }
   68847 
   68848 /* Opcode:  Halt P1 P2 * P4 P5
   68849 **
   68850 ** Exit immediately.  All open cursors, etc are closed
   68851 ** automatically.
   68852 **
   68853 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
   68854 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
   68855 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
   68856 ** whether or not to rollback the current transaction.  Do not rollback
   68857 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
   68858 ** then back out all changes that have occurred during this execution of the
   68859 ** VDBE, but do not rollback the transaction.
   68860 **
   68861 ** If P4 is not null then it is an error message string.
   68862 **
   68863 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
   68864 **
   68865 **    0:  (no change)
   68866 **    1:  NOT NULL contraint failed: P4
   68867 **    2:  UNIQUE constraint failed: P4
   68868 **    3:  CHECK constraint failed: P4
   68869 **    4:  FOREIGN KEY constraint failed: P4
   68870 **
   68871 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
   68872 ** omitted.
   68873 **
   68874 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
   68875 ** every program.  So a jump past the last instruction of the program
   68876 ** is the same as executing Halt.
   68877 */
   68878 case OP_Halt: {
   68879   const char *zType;
   68880   const char *zLogFmt;
   68881 
   68882   if( pOp->p1==SQLITE_OK && p->pFrame ){
   68883     /* Halt the sub-program. Return control to the parent frame. */
   68884     VdbeFrame *pFrame = p->pFrame;
   68885     p->pFrame = pFrame->pParent;
   68886     p->nFrame--;
   68887     sqlite3VdbeSetChanges(db, p->nChange);
   68888     pc = sqlite3VdbeFrameRestore(pFrame);
   68889     lastRowid = db->lastRowid;
   68890     if( pOp->p2==OE_Ignore ){
   68891       /* Instruction pc is the OP_Program that invoked the sub-program
   68892       ** currently being halted. If the p2 instruction of this OP_Halt
   68893       ** instruction is set to OE_Ignore, then the sub-program is throwing
   68894       ** an IGNORE exception. In this case jump to the address specified
   68895       ** as the p2 of the calling OP_Program.  */
   68896       pc = p->aOp[pc].p2-1;
   68897     }
   68898     aOp = p->aOp;
   68899     aMem = p->aMem;
   68900     break;
   68901   }
   68902   p->rc = pOp->p1;
   68903   p->errorAction = (u8)pOp->p2;
   68904   p->pc = pc;
   68905   if( p->rc ){
   68906     if( pOp->p5 ){
   68907       static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
   68908                                              "FOREIGN KEY" };
   68909       assert( pOp->p5>=1 && pOp->p5<=4 );
   68910       testcase( pOp->p5==1 );
   68911       testcase( pOp->p5==2 );
   68912       testcase( pOp->p5==3 );
   68913       testcase( pOp->p5==4 );
   68914       zType = azType[pOp->p5-1];
   68915     }else{
   68916       zType = 0;
   68917     }
   68918     assert( zType!=0 || pOp->p4.z!=0 );
   68919     zLogFmt = "abort at %d in [%s]: %s";
   68920     if( zType && pOp->p4.z ){
   68921       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
   68922                        zType, pOp->p4.z);
   68923     }else if( pOp->p4.z ){
   68924       sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
   68925     }else{
   68926       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
   68927     }
   68928     sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
   68929   }
   68930   rc = sqlite3VdbeHalt(p);
   68931   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
   68932   if( rc==SQLITE_BUSY ){
   68933     p->rc = rc = SQLITE_BUSY;
   68934   }else{
   68935     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
   68936     assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
   68937     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
   68938   }
   68939   goto vdbe_return;
   68940 }
   68941 
   68942 /* Opcode: Integer P1 P2 * * *
   68943 ** Synopsis: r[P2]=P1
   68944 **
   68945 ** The 32-bit integer value P1 is written into register P2.
   68946 */
   68947 case OP_Integer: {         /* out2-prerelease */
   68948   pOut->u.i = pOp->p1;
   68949   break;
   68950 }
   68951 
   68952 /* Opcode: Int64 * P2 * P4 *
   68953 ** Synopsis: r[P2]=P4
   68954 **
   68955 ** P4 is a pointer to a 64-bit integer value.
   68956 ** Write that value into register P2.
   68957 */
   68958 case OP_Int64: {           /* out2-prerelease */
   68959   assert( pOp->p4.pI64!=0 );
   68960   pOut->u.i = *pOp->p4.pI64;
   68961   break;
   68962 }
   68963 
   68964 #ifndef SQLITE_OMIT_FLOATING_POINT
   68965 /* Opcode: Real * P2 * P4 *
   68966 ** Synopsis: r[P2]=P4
   68967 **
   68968 ** P4 is a pointer to a 64-bit floating point value.
   68969 ** Write that value into register P2.
   68970 */
   68971 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
   68972   pOut->flags = MEM_Real;
   68973   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
   68974   pOut->r = *pOp->p4.pReal;
   68975   break;
   68976 }
   68977 #endif
   68978 
   68979 /* Opcode: String8 * P2 * P4 *
   68980 ** Synopsis: r[P2]='P4'
   68981 **
   68982 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
   68983 ** into a String before it is executed for the first time.  During
   68984 ** this transformation, the length of string P4 is computed and stored
   68985 ** as the P1 parameter.
   68986 */
   68987 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
   68988   assert( pOp->p4.z!=0 );
   68989   pOp->opcode = OP_String;
   68990   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
   68991 
   68992 #ifndef SQLITE_OMIT_UTF16
   68993   if( encoding!=SQLITE_UTF8 ){
   68994     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
   68995     if( rc==SQLITE_TOOBIG ) goto too_big;
   68996     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
   68997     assert( pOut->zMalloc==pOut->z );
   68998     assert( VdbeMemDynamic(pOut)==0 );
   68999     pOut->zMalloc = 0;
   69000     pOut->flags |= MEM_Static;
   69001     if( pOp->p4type==P4_DYNAMIC ){
   69002       sqlite3DbFree(db, pOp->p4.z);
   69003     }
   69004     pOp->p4type = P4_DYNAMIC;
   69005     pOp->p4.z = pOut->z;
   69006     pOp->p1 = pOut->n;
   69007   }
   69008 #endif
   69009   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   69010     goto too_big;
   69011   }
   69012   /* Fall through to the next case, OP_String */
   69013 }
   69014 
   69015 /* Opcode: String P1 P2 * P4 *
   69016 ** Synopsis: r[P2]='P4' (len=P1)
   69017 **
   69018 ** The string value P4 of length P1 (bytes) is stored in register P2.
   69019 */
   69020 case OP_String: {          /* out2-prerelease */
   69021   assert( pOp->p4.z!=0 );
   69022   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   69023   pOut->z = pOp->p4.z;
   69024   pOut->n = pOp->p1;
   69025   pOut->enc = encoding;
   69026   UPDATE_MAX_BLOBSIZE(pOut);
   69027   break;
   69028 }
   69029 
   69030 /* Opcode: Null P1 P2 P3 * *
   69031 ** Synopsis:  r[P2..P3]=NULL
   69032 **
   69033 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
   69034 ** NULL into register P3 and every register in between P2 and P3.  If P3
   69035 ** is less than P2 (typically P3 is zero) then only register P2 is
   69036 ** set to NULL.
   69037 **
   69038 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
   69039 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
   69040 ** OP_Ne or OP_Eq.
   69041 */
   69042 case OP_Null: {           /* out2-prerelease */
   69043   int cnt;
   69044   u16 nullFlag;
   69045   cnt = pOp->p3-pOp->p2;
   69046   assert( pOp->p3<=(p->nMem-p->nCursor) );
   69047   pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
   69048   while( cnt>0 ){
   69049     pOut++;
   69050     memAboutToChange(p, pOut);
   69051     VdbeMemRelease(pOut);
   69052     pOut->flags = nullFlag;
   69053     cnt--;
   69054   }
   69055   break;
   69056 }
   69057 
   69058 /* Opcode: SoftNull P1 * * * *
   69059 ** Synopsis:  r[P1]=NULL
   69060 **
   69061 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
   69062 ** instruction, but do not free any string or blob memory associated with
   69063 ** the register, so that if the value was a string or blob that was
   69064 ** previously copied using OP_SCopy, the copies will continue to be valid.
   69065 */
   69066 case OP_SoftNull: {
   69067   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
   69068   pOut = &aMem[pOp->p1];
   69069   pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
   69070   break;
   69071 }
   69072 
   69073 /* Opcode: Blob P1 P2 * P4 *
   69074 ** Synopsis: r[P2]=P4 (len=P1)
   69075 **
   69076 ** P4 points to a blob of data P1 bytes long.  Store this
   69077 ** blob in register P2.
   69078 */
   69079 case OP_Blob: {                /* out2-prerelease */
   69080   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
   69081   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
   69082   pOut->enc = encoding;
   69083   UPDATE_MAX_BLOBSIZE(pOut);
   69084   break;
   69085 }
   69086 
   69087 /* Opcode: Variable P1 P2 * P4 *
   69088 ** Synopsis: r[P2]=parameter(P1,P4)
   69089 **
   69090 ** Transfer the values of bound parameter P1 into register P2
   69091 **
   69092 ** If the parameter is named, then its name appears in P4.
   69093 ** The P4 value is used by sqlite3_bind_parameter_name().
   69094 */
   69095 case OP_Variable: {            /* out2-prerelease */
   69096   Mem *pVar;       /* Value being transferred */
   69097 
   69098   assert( pOp->p1>0 && pOp->p1<=p->nVar );
   69099   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
   69100   pVar = &p->aVar[pOp->p1 - 1];
   69101   if( sqlite3VdbeMemTooBig(pVar) ){
   69102     goto too_big;
   69103   }
   69104   sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
   69105   UPDATE_MAX_BLOBSIZE(pOut);
   69106   break;
   69107 }
   69108 
   69109 /* Opcode: Move P1 P2 P3 * *
   69110 ** Synopsis:  r[P2@P3]=r[P1@P3]
   69111 **
   69112 ** Move the P3 values in register P1..P1+P3-1 over into
   69113 ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
   69114 ** left holding a NULL.  It is an error for register ranges
   69115 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
   69116 ** for P3 to be less than 1.
   69117 */
   69118 case OP_Move: {
   69119   char *zMalloc;   /* Holding variable for allocated memory */
   69120   int n;           /* Number of registers left to copy */
   69121   int p1;          /* Register to copy from */
   69122   int p2;          /* Register to copy to */
   69123 
   69124   n = pOp->p3;
   69125   p1 = pOp->p1;
   69126   p2 = pOp->p2;
   69127   assert( n>0 && p1>0 && p2>0 );
   69128   assert( p1+n<=p2 || p2+n<=p1 );
   69129 
   69130   pIn1 = &aMem[p1];
   69131   pOut = &aMem[p2];
   69132   do{
   69133     assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
   69134     assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
   69135     assert( memIsValid(pIn1) );
   69136     memAboutToChange(p, pOut);
   69137     VdbeMemRelease(pOut);
   69138     zMalloc = pOut->zMalloc;
   69139     memcpy(pOut, pIn1, sizeof(Mem));
   69140 #ifdef SQLITE_DEBUG
   69141     if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
   69142       pOut->pScopyFrom += p1 - pOp->p2;
   69143     }
   69144 #endif
   69145     pIn1->flags = MEM_Undefined;
   69146     pIn1->xDel = 0;
   69147     pIn1->zMalloc = zMalloc;
   69148     REGISTER_TRACE(p2++, pOut);
   69149     pIn1++;
   69150     pOut++;
   69151   }while( --n );
   69152   break;
   69153 }
   69154 
   69155 /* Opcode: Copy P1 P2 P3 * *
   69156 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
   69157 **
   69158 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
   69159 **
   69160 ** This instruction makes a deep copy of the value.  A duplicate
   69161 ** is made of any string or blob constant.  See also OP_SCopy.
   69162 */
   69163 case OP_Copy: {
   69164   int n;
   69165 
   69166   n = pOp->p3;
   69167   pIn1 = &aMem[pOp->p1];
   69168   pOut = &aMem[pOp->p2];
   69169   assert( pOut!=pIn1 );
   69170   while( 1 ){
   69171     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   69172     Deephemeralize(pOut);
   69173 #ifdef SQLITE_DEBUG
   69174     pOut->pScopyFrom = 0;
   69175 #endif
   69176     REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
   69177     if( (n--)==0 ) break;
   69178     pOut++;
   69179     pIn1++;
   69180   }
   69181   break;
   69182 }
   69183 
   69184 /* Opcode: SCopy P1 P2 * * *
   69185 ** Synopsis: r[P2]=r[P1]
   69186 **
   69187 ** Make a shallow copy of register P1 into register P2.
   69188 **
   69189 ** This instruction makes a shallow copy of the value.  If the value
   69190 ** is a string or blob, then the copy is only a pointer to the
   69191 ** original and hence if the original changes so will the copy.
   69192 ** Worse, if the original is deallocated, the copy becomes invalid.
   69193 ** Thus the program must guarantee that the original will not change
   69194 ** during the lifetime of the copy.  Use OP_Copy to make a complete
   69195 ** copy.
   69196 */
   69197 case OP_SCopy: {            /* out2 */
   69198   pIn1 = &aMem[pOp->p1];
   69199   pOut = &aMem[pOp->p2];
   69200   assert( pOut!=pIn1 );
   69201   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   69202 #ifdef SQLITE_DEBUG
   69203   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
   69204 #endif
   69205   break;
   69206 }
   69207 
   69208 /* Opcode: ResultRow P1 P2 * * *
   69209 ** Synopsis:  output=r[P1@P2]
   69210 **
   69211 ** The registers P1 through P1+P2-1 contain a single row of
   69212 ** results. This opcode causes the sqlite3_step() call to terminate
   69213 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
   69214 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
   69215 ** the result row.
   69216 */
   69217 case OP_ResultRow: {
   69218   Mem *pMem;
   69219   int i;
   69220   assert( p->nResColumn==pOp->p2 );
   69221   assert( pOp->p1>0 );
   69222   assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
   69223 
   69224 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   69225   /* Run the progress counter just before returning.
   69226   */
   69227   if( db->xProgress!=0
   69228    && nVmStep>=nProgressLimit
   69229    && db->xProgress(db->pProgressArg)!=0
   69230   ){
   69231     rc = SQLITE_INTERRUPT;
   69232     goto vdbe_error_halt;
   69233   }
   69234 #endif
   69235 
   69236   /* If this statement has violated immediate foreign key constraints, do
   69237   ** not return the number of rows modified. And do not RELEASE the statement
   69238   ** transaction. It needs to be rolled back.  */
   69239   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
   69240     assert( db->flags&SQLITE_CountRows );
   69241     assert( p->usesStmtJournal );
   69242     break;
   69243   }
   69244 
   69245   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
   69246   ** DML statements invoke this opcode to return the number of rows
   69247   ** modified to the user. This is the only way that a VM that
   69248   ** opens a statement transaction may invoke this opcode.
   69249   **
   69250   ** In case this is such a statement, close any statement transaction
   69251   ** opened by this VM before returning control to the user. This is to
   69252   ** ensure that statement-transactions are always nested, not overlapping.
   69253   ** If the open statement-transaction is not closed here, then the user
   69254   ** may step another VM that opens its own statement transaction. This
   69255   ** may lead to overlapping statement transactions.
   69256   **
   69257   ** The statement transaction is never a top-level transaction.  Hence
   69258   ** the RELEASE call below can never fail.
   69259   */
   69260   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
   69261   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
   69262   if( NEVER(rc!=SQLITE_OK) ){
   69263     break;
   69264   }
   69265 
   69266   /* Invalidate all ephemeral cursor row caches */
   69267   p->cacheCtr = (p->cacheCtr + 2)|1;
   69268 
   69269   /* Make sure the results of the current row are \000 terminated
   69270   ** and have an assigned type.  The results are de-ephemeralized as
   69271   ** a side effect.
   69272   */
   69273   pMem = p->pResultSet = &aMem[pOp->p1];
   69274   for(i=0; i<pOp->p2; i++){
   69275     assert( memIsValid(&pMem[i]) );
   69276     Deephemeralize(&pMem[i]);
   69277     assert( (pMem[i].flags & MEM_Ephem)==0
   69278             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
   69279     sqlite3VdbeMemNulTerminate(&pMem[i]);
   69280     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
   69281   }
   69282   if( db->mallocFailed ) goto no_mem;
   69283 
   69284   /* Return SQLITE_ROW
   69285   */
   69286   p->pc = pc + 1;
   69287   rc = SQLITE_ROW;
   69288   goto vdbe_return;
   69289 }
   69290 
   69291 /* Opcode: Concat P1 P2 P3 * *
   69292 ** Synopsis: r[P3]=r[P2]+r[P1]
   69293 **
   69294 ** Add the text in register P1 onto the end of the text in
   69295 ** register P2 and store the result in register P3.
   69296 ** If either the P1 or P2 text are NULL then store NULL in P3.
   69297 **
   69298 **   P3 = P2 || P1
   69299 **
   69300 ** It is illegal for P1 and P3 to be the same register. Sometimes,
   69301 ** if P3 is the same register as P2, the implementation is able
   69302 ** to avoid a memcpy().
   69303 */
   69304 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
   69305   i64 nByte;
   69306 
   69307   pIn1 = &aMem[pOp->p1];
   69308   pIn2 = &aMem[pOp->p2];
   69309   pOut = &aMem[pOp->p3];
   69310   assert( pIn1!=pOut );
   69311   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   69312     sqlite3VdbeMemSetNull(pOut);
   69313     break;
   69314   }
   69315   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
   69316   Stringify(pIn1, encoding);
   69317   Stringify(pIn2, encoding);
   69318   nByte = pIn1->n + pIn2->n;
   69319   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   69320     goto too_big;
   69321   }
   69322   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
   69323     goto no_mem;
   69324   }
   69325   MemSetTypeFlag(pOut, MEM_Str);
   69326   if( pOut!=pIn2 ){
   69327     memcpy(pOut->z, pIn2->z, pIn2->n);
   69328   }
   69329   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
   69330   pOut->z[nByte]=0;
   69331   pOut->z[nByte+1] = 0;
   69332   pOut->flags |= MEM_Term;
   69333   pOut->n = (int)nByte;
   69334   pOut->enc = encoding;
   69335   UPDATE_MAX_BLOBSIZE(pOut);
   69336   break;
   69337 }
   69338 
   69339 /* Opcode: Add P1 P2 P3 * *
   69340 ** Synopsis:  r[P3]=r[P1]+r[P2]
   69341 **
   69342 ** Add the value in register P1 to the value in register P2
   69343 ** and store the result in register P3.
   69344 ** If either input is NULL, the result is NULL.
   69345 */
   69346 /* Opcode: Multiply P1 P2 P3 * *
   69347 ** Synopsis:  r[P3]=r[P1]*r[P2]
   69348 **
   69349 **
   69350 ** Multiply the value in register P1 by the value in register P2
   69351 ** and store the result in register P3.
   69352 ** If either input is NULL, the result is NULL.
   69353 */
   69354 /* Opcode: Subtract P1 P2 P3 * *
   69355 ** Synopsis:  r[P3]=r[P2]-r[P1]
   69356 **
   69357 ** Subtract the value in register P1 from the value in register P2
   69358 ** and store the result in register P3.
   69359 ** If either input is NULL, the result is NULL.
   69360 */
   69361 /* Opcode: Divide P1 P2 P3 * *
   69362 ** Synopsis:  r[P3]=r[P2]/r[P1]
   69363 **
   69364 ** Divide the value in register P1 by the value in register P2
   69365 ** and store the result in register P3 (P3=P2/P1). If the value in
   69366 ** register P1 is zero, then the result is NULL. If either input is
   69367 ** NULL, the result is NULL.
   69368 */
   69369 /* Opcode: Remainder P1 P2 P3 * *
   69370 ** Synopsis:  r[P3]=r[P2]%r[P1]
   69371 **
   69372 ** Compute the remainder after integer register P2 is divided by
   69373 ** register P1 and store the result in register P3.
   69374 ** If the value in register P1 is zero the result is NULL.
   69375 ** If either operand is NULL, the result is NULL.
   69376 */
   69377 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
   69378 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
   69379 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
   69380 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
   69381 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
   69382   char bIntint;   /* Started out as two integer operands */
   69383   u16 flags;      /* Combined MEM_* flags from both inputs */
   69384   u16 type1;      /* Numeric type of left operand */
   69385   u16 type2;      /* Numeric type of right operand */
   69386   i64 iA;         /* Integer value of left operand */
   69387   i64 iB;         /* Integer value of right operand */
   69388   double rA;      /* Real value of left operand */
   69389   double rB;      /* Real value of right operand */
   69390 
   69391   pIn1 = &aMem[pOp->p1];
   69392   type1 = numericType(pIn1);
   69393   pIn2 = &aMem[pOp->p2];
   69394   type2 = numericType(pIn2);
   69395   pOut = &aMem[pOp->p3];
   69396   flags = pIn1->flags | pIn2->flags;
   69397   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
   69398   if( (type1 & type2 & MEM_Int)!=0 ){
   69399     iA = pIn1->u.i;
   69400     iB = pIn2->u.i;
   69401     bIntint = 1;
   69402     switch( pOp->opcode ){
   69403       case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
   69404       case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
   69405       case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
   69406       case OP_Divide: {
   69407         if( iA==0 ) goto arithmetic_result_is_null;
   69408         if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
   69409         iB /= iA;
   69410         break;
   69411       }
   69412       default: {
   69413         if( iA==0 ) goto arithmetic_result_is_null;
   69414         if( iA==-1 ) iA = 1;
   69415         iB %= iA;
   69416         break;
   69417       }
   69418     }
   69419     pOut->u.i = iB;
   69420     MemSetTypeFlag(pOut, MEM_Int);
   69421   }else{
   69422     bIntint = 0;
   69423 fp_math:
   69424     rA = sqlite3VdbeRealValue(pIn1);
   69425     rB = sqlite3VdbeRealValue(pIn2);
   69426     switch( pOp->opcode ){
   69427       case OP_Add:         rB += rA;       break;
   69428       case OP_Subtract:    rB -= rA;       break;
   69429       case OP_Multiply:    rB *= rA;       break;
   69430       case OP_Divide: {
   69431         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   69432         if( rA==(double)0 ) goto arithmetic_result_is_null;
   69433         rB /= rA;
   69434         break;
   69435       }
   69436       default: {
   69437         iA = (i64)rA;
   69438         iB = (i64)rB;
   69439         if( iA==0 ) goto arithmetic_result_is_null;
   69440         if( iA==-1 ) iA = 1;
   69441         rB = (double)(iB % iA);
   69442         break;
   69443       }
   69444     }
   69445 #ifdef SQLITE_OMIT_FLOATING_POINT
   69446     pOut->u.i = rB;
   69447     MemSetTypeFlag(pOut, MEM_Int);
   69448 #else
   69449     if( sqlite3IsNaN(rB) ){
   69450       goto arithmetic_result_is_null;
   69451     }
   69452     pOut->r = rB;
   69453     MemSetTypeFlag(pOut, MEM_Real);
   69454     if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
   69455       sqlite3VdbeIntegerAffinity(pOut);
   69456     }
   69457 #endif
   69458   }
   69459   break;
   69460 
   69461 arithmetic_result_is_null:
   69462   sqlite3VdbeMemSetNull(pOut);
   69463   break;
   69464 }
   69465 
   69466 /* Opcode: CollSeq P1 * * P4
   69467 **
   69468 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
   69469 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
   69470 ** be returned. This is used by the built-in min(), max() and nullif()
   69471 ** functions.
   69472 **
   69473 ** If P1 is not zero, then it is a register that a subsequent min() or
   69474 ** max() aggregate will set to 1 if the current row is not the minimum or
   69475 ** maximum.  The P1 register is initialized to 0 by this instruction.
   69476 **
   69477 ** The interface used by the implementation of the aforementioned functions
   69478 ** to retrieve the collation sequence set by this opcode is not available
   69479 ** publicly, only to user functions defined in func.c.
   69480 */
   69481 case OP_CollSeq: {
   69482   assert( pOp->p4type==P4_COLLSEQ );
   69483   if( pOp->p1 ){
   69484     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
   69485   }
   69486   break;
   69487 }
   69488 
   69489 /* Opcode: Function P1 P2 P3 P4 P5
   69490 ** Synopsis: r[P3]=func(r[P2@P5])
   69491 **
   69492 ** Invoke a user function (P4 is a pointer to a Function structure that
   69493 ** defines the function) with P5 arguments taken from register P2 and
   69494 ** successors.  The result of the function is stored in register P3.
   69495 ** Register P3 must not be one of the function inputs.
   69496 **
   69497 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
   69498 ** function was determined to be constant at compile time. If the first
   69499 ** argument was constant then bit 0 of P1 is set. This is used to determine
   69500 ** whether meta data associated with a user function argument using the
   69501 ** sqlite3_set_auxdata() API may be safely retained until the next
   69502 ** invocation of this opcode.
   69503 **
   69504 ** See also: AggStep and AggFinal
   69505 */
   69506 case OP_Function: {
   69507   int i;
   69508   Mem *pArg;
   69509   sqlite3_context ctx;
   69510   sqlite3_value **apVal;
   69511   int n;
   69512 
   69513   n = pOp->p5;
   69514   apVal = p->apArg;
   69515   assert( apVal || n==0 );
   69516   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   69517   pOut = &aMem[pOp->p3];
   69518   memAboutToChange(p, pOut);
   69519 
   69520   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
   69521   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
   69522   pArg = &aMem[pOp->p2];
   69523   for(i=0; i<n; i++, pArg++){
   69524     assert( memIsValid(pArg) );
   69525     apVal[i] = pArg;
   69526     Deephemeralize(pArg);
   69527     REGISTER_TRACE(pOp->p2+i, pArg);
   69528   }
   69529 
   69530   assert( pOp->p4type==P4_FUNCDEF );
   69531   ctx.pFunc = pOp->p4.pFunc;
   69532   ctx.iOp = pc;
   69533   ctx.pVdbe = p;
   69534 
   69535   /* The output cell may already have a buffer allocated. Move
   69536   ** the pointer to ctx.s so in case the user-function can use
   69537   ** the already allocated buffer instead of allocating a new one.
   69538   */
   69539   memcpy(&ctx.s, pOut, sizeof(Mem));
   69540   pOut->flags = MEM_Null;
   69541   pOut->xDel = 0;
   69542   pOut->zMalloc = 0;
   69543   MemSetTypeFlag(&ctx.s, MEM_Null);
   69544 
   69545   ctx.fErrorOrAux = 0;
   69546   if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   69547     assert( pOp>aOp );
   69548     assert( pOp[-1].p4type==P4_COLLSEQ );
   69549     assert( pOp[-1].opcode==OP_CollSeq );
   69550     ctx.pColl = pOp[-1].p4.pColl;
   69551   }
   69552   db->lastRowid = lastRowid;
   69553   (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
   69554   lastRowid = db->lastRowid;
   69555 
   69556   if( db->mallocFailed ){
   69557     /* Even though a malloc() has failed, the implementation of the
   69558     ** user function may have called an sqlite3_result_XXX() function
   69559     ** to return a value. The following call releases any resources
   69560     ** associated with such a value.
   69561     */
   69562     sqlite3VdbeMemRelease(&ctx.s);
   69563     goto no_mem;
   69564   }
   69565 
   69566   /* If the function returned an error, throw an exception */
   69567   if( ctx.fErrorOrAux ){
   69568     if( ctx.isError ){
   69569       sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
   69570       rc = ctx.isError;
   69571     }
   69572     sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
   69573   }
   69574 
   69575   /* Copy the result of the function into register P3 */
   69576   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
   69577   assert( pOut->flags==MEM_Null );
   69578   memcpy(pOut, &ctx.s, sizeof(Mem));
   69579   if( sqlite3VdbeMemTooBig(pOut) ){
   69580     goto too_big;
   69581   }
   69582 
   69583 #if 0
   69584   /* The app-defined function has done something that as caused this
   69585   ** statement to expire.  (Perhaps the function called sqlite3_exec()
   69586   ** with a CREATE TABLE statement.)
   69587   */
   69588   if( p->expired ) rc = SQLITE_ABORT;
   69589 #endif
   69590 
   69591   REGISTER_TRACE(pOp->p3, pOut);
   69592   UPDATE_MAX_BLOBSIZE(pOut);
   69593   break;
   69594 }
   69595 
   69596 /* Opcode: BitAnd P1 P2 P3 * *
   69597 ** Synopsis:  r[P3]=r[P1]&r[P2]
   69598 **
   69599 ** Take the bit-wise AND of the values in register P1 and P2 and
   69600 ** store the result in register P3.
   69601 ** If either input is NULL, the result is NULL.
   69602 */
   69603 /* Opcode: BitOr P1 P2 P3 * *
   69604 ** Synopsis:  r[P3]=r[P1]|r[P2]
   69605 **
   69606 ** Take the bit-wise OR of the values in register P1 and P2 and
   69607 ** store the result in register P3.
   69608 ** If either input is NULL, the result is NULL.
   69609 */
   69610 /* Opcode: ShiftLeft P1 P2 P3 * *
   69611 ** Synopsis:  r[P3]=r[P2]<<r[P1]
   69612 **
   69613 ** Shift the integer value in register P2 to the left by the
   69614 ** number of bits specified by the integer in register P1.
   69615 ** Store the result in register P3.
   69616 ** If either input is NULL, the result is NULL.
   69617 */
   69618 /* Opcode: ShiftRight P1 P2 P3 * *
   69619 ** Synopsis:  r[P3]=r[P2]>>r[P1]
   69620 **
   69621 ** Shift the integer value in register P2 to the right by the
   69622 ** number of bits specified by the integer in register P1.
   69623 ** Store the result in register P3.
   69624 ** If either input is NULL, the result is NULL.
   69625 */
   69626 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
   69627 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
   69628 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
   69629 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
   69630   i64 iA;
   69631   u64 uA;
   69632   i64 iB;
   69633   u8 op;
   69634 
   69635   pIn1 = &aMem[pOp->p1];
   69636   pIn2 = &aMem[pOp->p2];
   69637   pOut = &aMem[pOp->p3];
   69638   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   69639     sqlite3VdbeMemSetNull(pOut);
   69640     break;
   69641   }
   69642   iA = sqlite3VdbeIntValue(pIn2);
   69643   iB = sqlite3VdbeIntValue(pIn1);
   69644   op = pOp->opcode;
   69645   if( op==OP_BitAnd ){
   69646     iA &= iB;
   69647   }else if( op==OP_BitOr ){
   69648     iA |= iB;
   69649   }else if( iB!=0 ){
   69650     assert( op==OP_ShiftRight || op==OP_ShiftLeft );
   69651 
   69652     /* If shifting by a negative amount, shift in the other direction */
   69653     if( iB<0 ){
   69654       assert( OP_ShiftRight==OP_ShiftLeft+1 );
   69655       op = 2*OP_ShiftLeft + 1 - op;
   69656       iB = iB>(-64) ? -iB : 64;
   69657     }
   69658 
   69659     if( iB>=64 ){
   69660       iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
   69661     }else{
   69662       memcpy(&uA, &iA, sizeof(uA));
   69663       if( op==OP_ShiftLeft ){
   69664         uA <<= iB;
   69665       }else{
   69666         uA >>= iB;
   69667         /* Sign-extend on a right shift of a negative number */
   69668         if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
   69669       }
   69670       memcpy(&iA, &uA, sizeof(iA));
   69671     }
   69672   }
   69673   pOut->u.i = iA;
   69674   MemSetTypeFlag(pOut, MEM_Int);
   69675   break;
   69676 }
   69677 
   69678 /* Opcode: AddImm  P1 P2 * * *
   69679 ** Synopsis:  r[P1]=r[P1]+P2
   69680 **
   69681 ** Add the constant P2 to the value in register P1.
   69682 ** The result is always an integer.
   69683 **
   69684 ** To force any register to be an integer, just add 0.
   69685 */
   69686 case OP_AddImm: {            /* in1 */
   69687   pIn1 = &aMem[pOp->p1];
   69688   memAboutToChange(p, pIn1);
   69689   sqlite3VdbeMemIntegerify(pIn1);
   69690   pIn1->u.i += pOp->p2;
   69691   break;
   69692 }
   69693 
   69694 /* Opcode: MustBeInt P1 P2 * * *
   69695 **
   69696 ** Force the value in register P1 to be an integer.  If the value
   69697 ** in P1 is not an integer and cannot be converted into an integer
   69698 ** without data loss, then jump immediately to P2, or if P2==0
   69699 ** raise an SQLITE_MISMATCH exception.
   69700 */
   69701 case OP_MustBeInt: {            /* jump, in1 */
   69702   pIn1 = &aMem[pOp->p1];
   69703   if( (pIn1->flags & MEM_Int)==0 ){
   69704     applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
   69705     VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
   69706     if( (pIn1->flags & MEM_Int)==0 ){
   69707       if( pOp->p2==0 ){
   69708         rc = SQLITE_MISMATCH;
   69709         goto abort_due_to_error;
   69710       }else{
   69711         pc = pOp->p2 - 1;
   69712         break;
   69713       }
   69714     }
   69715   }
   69716   MemSetTypeFlag(pIn1, MEM_Int);
   69717   break;
   69718 }
   69719 
   69720 #ifndef SQLITE_OMIT_FLOATING_POINT
   69721 /* Opcode: RealAffinity P1 * * * *
   69722 **
   69723 ** If register P1 holds an integer convert it to a real value.
   69724 **
   69725 ** This opcode is used when extracting information from a column that
   69726 ** has REAL affinity.  Such column values may still be stored as
   69727 ** integers, for space efficiency, but after extraction we want them
   69728 ** to have only a real value.
   69729 */
   69730 case OP_RealAffinity: {                  /* in1 */
   69731   pIn1 = &aMem[pOp->p1];
   69732   if( pIn1->flags & MEM_Int ){
   69733     sqlite3VdbeMemRealify(pIn1);
   69734   }
   69735   break;
   69736 }
   69737 #endif
   69738 
   69739 #ifndef SQLITE_OMIT_CAST
   69740 /* Opcode: ToText P1 * * * *
   69741 **
   69742 ** Force the value in register P1 to be text.
   69743 ** If the value is numeric, convert it to a string using the
   69744 ** equivalent of sprintf().  Blob values are unchanged and
   69745 ** are afterwards simply interpreted as text.
   69746 **
   69747 ** A NULL value is not changed by this routine.  It remains NULL.
   69748 */
   69749 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
   69750   pIn1 = &aMem[pOp->p1];
   69751   memAboutToChange(p, pIn1);
   69752   if( pIn1->flags & MEM_Null ) break;
   69753   assert( MEM_Str==(MEM_Blob>>3) );
   69754   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
   69755   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   69756   rc = ExpandBlob(pIn1);
   69757   assert( pIn1->flags & MEM_Str || db->mallocFailed );
   69758   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
   69759   UPDATE_MAX_BLOBSIZE(pIn1);
   69760   break;
   69761 }
   69762 
   69763 /* Opcode: ToBlob P1 * * * *
   69764 **
   69765 ** Force the value in register P1 to be a BLOB.
   69766 ** If the value is numeric, convert it to a string first.
   69767 ** Strings are simply reinterpreted as blobs with no change
   69768 ** to the underlying data.
   69769 **
   69770 ** A NULL value is not changed by this routine.  It remains NULL.
   69771 */
   69772 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
   69773   pIn1 = &aMem[pOp->p1];
   69774   if( pIn1->flags & MEM_Null ) break;
   69775   if( (pIn1->flags & MEM_Blob)==0 ){
   69776     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   69777     assert( pIn1->flags & MEM_Str || db->mallocFailed );
   69778     MemSetTypeFlag(pIn1, MEM_Blob);
   69779   }else{
   69780     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
   69781   }
   69782   UPDATE_MAX_BLOBSIZE(pIn1);
   69783   break;
   69784 }
   69785 
   69786 /* Opcode: ToNumeric P1 * * * *
   69787 **
   69788 ** Force the value in register P1 to be numeric (either an
   69789 ** integer or a floating-point number.)
   69790 ** If the value is text or blob, try to convert it to an using the
   69791 ** equivalent of atoi() or atof() and store 0 if no such conversion
   69792 ** is possible.
   69793 **
   69794 ** A NULL value is not changed by this routine.  It remains NULL.
   69795 */
   69796 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
   69797   pIn1 = &aMem[pOp->p1];
   69798   sqlite3VdbeMemNumerify(pIn1);
   69799   break;
   69800 }
   69801 #endif /* SQLITE_OMIT_CAST */
   69802 
   69803 /* Opcode: ToInt P1 * * * *
   69804 **
   69805 ** Force the value in register P1 to be an integer.  If
   69806 ** The value is currently a real number, drop its fractional part.
   69807 ** If the value is text or blob, try to convert it to an integer using the
   69808 ** equivalent of atoi() and store 0 if no such conversion is possible.
   69809 **
   69810 ** A NULL value is not changed by this routine.  It remains NULL.
   69811 */
   69812 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
   69813   pIn1 = &aMem[pOp->p1];
   69814   if( (pIn1->flags & MEM_Null)==0 ){
   69815     sqlite3VdbeMemIntegerify(pIn1);
   69816   }
   69817   break;
   69818 }
   69819 
   69820 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
   69821 /* Opcode: ToReal P1 * * * *
   69822 **
   69823 ** Force the value in register P1 to be a floating point number.
   69824 ** If The value is currently an integer, convert it.
   69825 ** If the value is text or blob, try to convert it to an integer using the
   69826 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
   69827 **
   69828 ** A NULL value is not changed by this routine.  It remains NULL.
   69829 */
   69830 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
   69831   pIn1 = &aMem[pOp->p1];
   69832   memAboutToChange(p, pIn1);
   69833   if( (pIn1->flags & MEM_Null)==0 ){
   69834     sqlite3VdbeMemRealify(pIn1);
   69835   }
   69836   break;
   69837 }
   69838 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
   69839 
   69840 /* Opcode: Lt P1 P2 P3 P4 P5
   69841 ** Synopsis: if r[P1]<r[P3] goto P2
   69842 **
   69843 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
   69844 ** jump to address P2.
   69845 **
   69846 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
   69847 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
   69848 ** bit is clear then fall through if either operand is NULL.
   69849 **
   69850 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
   69851 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
   69852 ** to coerce both inputs according to this affinity before the
   69853 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
   69854 ** affinity is used. Note that the affinity conversions are stored
   69855 ** back into the input registers P1 and P3.  So this opcode can cause
   69856 ** persistent changes to registers P1 and P3.
   69857 **
   69858 ** Once any conversions have taken place, and neither value is NULL,
   69859 ** the values are compared. If both values are blobs then memcmp() is
   69860 ** used to determine the results of the comparison.  If both values
   69861 ** are text, then the appropriate collating function specified in
   69862 ** P4 is  used to do the comparison.  If P4 is not specified then
   69863 ** memcmp() is used to compare text string.  If both values are
   69864 ** numeric, then a numeric comparison is used. If the two values
   69865 ** are of different types, then numbers are considered less than
   69866 ** strings and strings are considered less than blobs.
   69867 **
   69868 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
   69869 ** store a boolean result (either 0, or 1, or NULL) in register P2.
   69870 **
   69871 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
   69872 ** equal to one another, provided that they do not have their MEM_Cleared
   69873 ** bit set.
   69874 */
   69875 /* Opcode: Ne P1 P2 P3 P4 P5
   69876 ** Synopsis: if r[P1]!=r[P3] goto P2
   69877 **
   69878 ** This works just like the Lt opcode except that the jump is taken if
   69879 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
   69880 ** additional information.
   69881 **
   69882 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   69883 ** true or false and is never NULL.  If both operands are NULL then the result
   69884 ** of comparison is false.  If either operand is NULL then the result is true.
   69885 ** If neither operand is NULL the result is the same as it would be if
   69886 ** the SQLITE_NULLEQ flag were omitted from P5.
   69887 */
   69888 /* Opcode: Eq P1 P2 P3 P4 P5
   69889 ** Synopsis: if r[P1]==r[P3] goto P2
   69890 **
   69891 ** This works just like the Lt opcode except that the jump is taken if
   69892 ** the operands in registers P1 and P3 are equal.
   69893 ** See the Lt opcode for additional information.
   69894 **
   69895 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   69896 ** true or false and is never NULL.  If both operands are NULL then the result
   69897 ** of comparison is true.  If either operand is NULL then the result is false.
   69898 ** If neither operand is NULL the result is the same as it would be if
   69899 ** the SQLITE_NULLEQ flag were omitted from P5.
   69900 */
   69901 /* Opcode: Le P1 P2 P3 P4 P5
   69902 ** Synopsis: if r[P1]<=r[P3] goto P2
   69903 **
   69904 ** This works just like the Lt opcode except that the jump is taken if
   69905 ** the content of register P3 is less than or equal to the content of
   69906 ** register P1.  See the Lt opcode for additional information.
   69907 */
   69908 /* Opcode: Gt P1 P2 P3 P4 P5
   69909 ** Synopsis: if r[P1]>r[P3] goto P2
   69910 **
   69911 ** This works just like the Lt opcode except that the jump is taken if
   69912 ** the content of register P3 is greater than the content of
   69913 ** register P1.  See the Lt opcode for additional information.
   69914 */
   69915 /* Opcode: Ge P1 P2 P3 P4 P5
   69916 ** Synopsis: if r[P1]>=r[P3] goto P2
   69917 **
   69918 ** This works just like the Lt opcode except that the jump is taken if
   69919 ** the content of register P3 is greater than or equal to the content of
   69920 ** register P1.  See the Lt opcode for additional information.
   69921 */
   69922 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
   69923 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
   69924 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
   69925 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
   69926 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
   69927 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
   69928   int res;            /* Result of the comparison of pIn1 against pIn3 */
   69929   char affinity;      /* Affinity to use for comparison */
   69930   u16 flags1;         /* Copy of initial value of pIn1->flags */
   69931   u16 flags3;         /* Copy of initial value of pIn3->flags */
   69932 
   69933   pIn1 = &aMem[pOp->p1];
   69934   pIn3 = &aMem[pOp->p3];
   69935   flags1 = pIn1->flags;
   69936   flags3 = pIn3->flags;
   69937   if( (flags1 | flags3)&MEM_Null ){
   69938     /* One or both operands are NULL */
   69939     if( pOp->p5 & SQLITE_NULLEQ ){
   69940       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
   69941       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
   69942       ** or not both operands are null.
   69943       */
   69944       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
   69945       assert( (flags1 & MEM_Cleared)==0 );
   69946       assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
   69947       if( (flags1&MEM_Null)!=0
   69948        && (flags3&MEM_Null)!=0
   69949        && (flags3&MEM_Cleared)==0
   69950       ){
   69951         res = 0;  /* Results are equal */
   69952       }else{
   69953         res = 1;  /* Results are not equal */
   69954       }
   69955     }else{
   69956       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
   69957       ** then the result is always NULL.
   69958       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
   69959       */
   69960       if( pOp->p5 & SQLITE_STOREP2 ){
   69961         pOut = &aMem[pOp->p2];
   69962         MemSetTypeFlag(pOut, MEM_Null);
   69963         REGISTER_TRACE(pOp->p2, pOut);
   69964       }else{
   69965         VdbeBranchTaken(2,3);
   69966         if( pOp->p5 & SQLITE_JUMPIFNULL ){
   69967           pc = pOp->p2-1;
   69968         }
   69969       }
   69970       break;
   69971     }
   69972   }else{
   69973     /* Neither operand is NULL.  Do a comparison. */
   69974     affinity = pOp->p5 & SQLITE_AFF_MASK;
   69975     if( affinity ){
   69976       applyAffinity(pIn1, affinity, encoding);
   69977       applyAffinity(pIn3, affinity, encoding);
   69978       if( db->mallocFailed ) goto no_mem;
   69979     }
   69980 
   69981     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
   69982     ExpandBlob(pIn1);
   69983     ExpandBlob(pIn3);
   69984     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
   69985   }
   69986   switch( pOp->opcode ){
   69987     case OP_Eq:    res = res==0;     break;
   69988     case OP_Ne:    res = res!=0;     break;
   69989     case OP_Lt:    res = res<0;      break;
   69990     case OP_Le:    res = res<=0;     break;
   69991     case OP_Gt:    res = res>0;      break;
   69992     default:       res = res>=0;     break;
   69993   }
   69994 
   69995   if( pOp->p5 & SQLITE_STOREP2 ){
   69996     pOut = &aMem[pOp->p2];
   69997     memAboutToChange(p, pOut);
   69998     MemSetTypeFlag(pOut, MEM_Int);
   69999     pOut->u.i = res;
   70000     REGISTER_TRACE(pOp->p2, pOut);
   70001   }else{
   70002     VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
   70003     if( res ){
   70004       pc = pOp->p2-1;
   70005     }
   70006   }
   70007   /* Undo any changes made by applyAffinity() to the input registers. */
   70008   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask);
   70009   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask);
   70010   break;
   70011 }
   70012 
   70013 /* Opcode: Permutation * * * P4 *
   70014 **
   70015 ** Set the permutation used by the OP_Compare operator to be the array
   70016 ** of integers in P4.
   70017 **
   70018 ** The permutation is only valid until the next OP_Compare that has
   70019 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
   70020 ** occur immediately prior to the OP_Compare.
   70021 */
   70022 case OP_Permutation: {
   70023   assert( pOp->p4type==P4_INTARRAY );
   70024   assert( pOp->p4.ai );
   70025   aPermute = pOp->p4.ai;
   70026   break;
   70027 }
   70028 
   70029 /* Opcode: Compare P1 P2 P3 P4 P5
   70030 ** Synopsis: r[P1@P3] <-> r[P2@P3]
   70031 **
   70032 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
   70033 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
   70034 ** the comparison for use by the next OP_Jump instruct.
   70035 **
   70036 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
   70037 ** determined by the most recent OP_Permutation operator.  If the
   70038 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
   70039 ** order.
   70040 **
   70041 ** P4 is a KeyInfo structure that defines collating sequences and sort
   70042 ** orders for the comparison.  The permutation applies to registers
   70043 ** only.  The KeyInfo elements are used sequentially.
   70044 **
   70045 ** The comparison is a sort comparison, so NULLs compare equal,
   70046 ** NULLs are less than numbers, numbers are less than strings,
   70047 ** and strings are less than blobs.
   70048 */
   70049 case OP_Compare: {
   70050   int n;
   70051   int i;
   70052   int p1;
   70053   int p2;
   70054   const KeyInfo *pKeyInfo;
   70055   int idx;
   70056   CollSeq *pColl;    /* Collating sequence to use on this term */
   70057   int bRev;          /* True for DESCENDING sort order */
   70058 
   70059   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
   70060   n = pOp->p3;
   70061   pKeyInfo = pOp->p4.pKeyInfo;
   70062   assert( n>0 );
   70063   assert( pKeyInfo!=0 );
   70064   p1 = pOp->p1;
   70065   p2 = pOp->p2;
   70066 #if SQLITE_DEBUG
   70067   if( aPermute ){
   70068     int k, mx = 0;
   70069     for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
   70070     assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
   70071     assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
   70072   }else{
   70073     assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
   70074     assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
   70075   }
   70076 #endif /* SQLITE_DEBUG */
   70077   for(i=0; i<n; i++){
   70078     idx = aPermute ? aPermute[i] : i;
   70079     assert( memIsValid(&aMem[p1+idx]) );
   70080     assert( memIsValid(&aMem[p2+idx]) );
   70081     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
   70082     REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
   70083     assert( i<pKeyInfo->nField );
   70084     pColl = pKeyInfo->aColl[i];
   70085     bRev = pKeyInfo->aSortOrder[i];
   70086     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
   70087     if( iCompare ){
   70088       if( bRev ) iCompare = -iCompare;
   70089       break;
   70090     }
   70091   }
   70092   aPermute = 0;
   70093   break;
   70094 }
   70095 
   70096 /* Opcode: Jump P1 P2 P3 * *
   70097 **
   70098 ** Jump to the instruction at address P1, P2, or P3 depending on whether
   70099 ** in the most recent OP_Compare instruction the P1 vector was less than
   70100 ** equal to, or greater than the P2 vector, respectively.
   70101 */
   70102 case OP_Jump: {             /* jump */
   70103   if( iCompare<0 ){
   70104     pc = pOp->p1 - 1;  VdbeBranchTaken(0,3);
   70105   }else if( iCompare==0 ){
   70106     pc = pOp->p2 - 1;  VdbeBranchTaken(1,3);
   70107   }else{
   70108     pc = pOp->p3 - 1;  VdbeBranchTaken(2,3);
   70109   }
   70110   break;
   70111 }
   70112 
   70113 /* Opcode: And P1 P2 P3 * *
   70114 ** Synopsis: r[P3]=(r[P1] && r[P2])
   70115 **
   70116 ** Take the logical AND of the values in registers P1 and P2 and
   70117 ** write the result into register P3.
   70118 **
   70119 ** If either P1 or P2 is 0 (false) then the result is 0 even if
   70120 ** the other input is NULL.  A NULL and true or two NULLs give
   70121 ** a NULL output.
   70122 */
   70123 /* Opcode: Or P1 P2 P3 * *
   70124 ** Synopsis: r[P3]=(r[P1] || r[P2])
   70125 **
   70126 ** Take the logical OR of the values in register P1 and P2 and
   70127 ** store the answer in register P3.
   70128 **
   70129 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
   70130 ** even if the other input is NULL.  A NULL and false or two NULLs
   70131 ** give a NULL output.
   70132 */
   70133 case OP_And:              /* same as TK_AND, in1, in2, out3 */
   70134 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
   70135   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   70136   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   70137 
   70138   pIn1 = &aMem[pOp->p1];
   70139   if( pIn1->flags & MEM_Null ){
   70140     v1 = 2;
   70141   }else{
   70142     v1 = sqlite3VdbeIntValue(pIn1)!=0;
   70143   }
   70144   pIn2 = &aMem[pOp->p2];
   70145   if( pIn2->flags & MEM_Null ){
   70146     v2 = 2;
   70147   }else{
   70148     v2 = sqlite3VdbeIntValue(pIn2)!=0;
   70149   }
   70150   if( pOp->opcode==OP_And ){
   70151     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
   70152     v1 = and_logic[v1*3+v2];
   70153   }else{
   70154     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
   70155     v1 = or_logic[v1*3+v2];
   70156   }
   70157   pOut = &aMem[pOp->p3];
   70158   if( v1==2 ){
   70159     MemSetTypeFlag(pOut, MEM_Null);
   70160   }else{
   70161     pOut->u.i = v1;
   70162     MemSetTypeFlag(pOut, MEM_Int);
   70163   }
   70164   break;
   70165 }
   70166 
   70167 /* Opcode: Not P1 P2 * * *
   70168 ** Synopsis: r[P2]= !r[P1]
   70169 **
   70170 ** Interpret the value in register P1 as a boolean value.  Store the
   70171 ** boolean complement in register P2.  If the value in register P1 is
   70172 ** NULL, then a NULL is stored in P2.
   70173 */
   70174 case OP_Not: {                /* same as TK_NOT, in1, out2 */
   70175   pIn1 = &aMem[pOp->p1];
   70176   pOut = &aMem[pOp->p2];
   70177   if( pIn1->flags & MEM_Null ){
   70178     sqlite3VdbeMemSetNull(pOut);
   70179   }else{
   70180     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
   70181   }
   70182   break;
   70183 }
   70184 
   70185 /* Opcode: BitNot P1 P2 * * *
   70186 ** Synopsis: r[P1]= ~r[P1]
   70187 **
   70188 ** Interpret the content of register P1 as an integer.  Store the
   70189 ** ones-complement of the P1 value into register P2.  If P1 holds
   70190 ** a NULL then store a NULL in P2.
   70191 */
   70192 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
   70193   pIn1 = &aMem[pOp->p1];
   70194   pOut = &aMem[pOp->p2];
   70195   if( pIn1->flags & MEM_Null ){
   70196     sqlite3VdbeMemSetNull(pOut);
   70197   }else{
   70198     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
   70199   }
   70200   break;
   70201 }
   70202 
   70203 /* Opcode: Once P1 P2 * * *
   70204 **
   70205 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
   70206 ** Otherwise, set the flag and fall through to the next instruction.
   70207 ** In other words, this opcode causes all following opcodes up through P2
   70208 ** (but not including P2) to run just once and to be skipped on subsequent
   70209 ** times through the loop.
   70210 **
   70211 ** All "once" flags are initially cleared whenever a prepared statement
   70212 ** first begins to run.
   70213 */
   70214 case OP_Once: {             /* jump */
   70215   assert( pOp->p1<p->nOnceFlag );
   70216   VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
   70217   if( p->aOnceFlag[pOp->p1] ){
   70218     pc = pOp->p2-1;
   70219   }else{
   70220     p->aOnceFlag[pOp->p1] = 1;
   70221   }
   70222   break;
   70223 }
   70224 
   70225 /* Opcode: If P1 P2 P3 * *
   70226 **
   70227 ** Jump to P2 if the value in register P1 is true.  The value
   70228 ** is considered true if it is numeric and non-zero.  If the value
   70229 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
   70230 */
   70231 /* Opcode: IfNot P1 P2 P3 * *
   70232 **
   70233 ** Jump to P2 if the value in register P1 is False.  The value
   70234 ** is considered false if it has a numeric value of zero.  If the value
   70235 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
   70236 */
   70237 case OP_If:                 /* jump, in1 */
   70238 case OP_IfNot: {            /* jump, in1 */
   70239   int c;
   70240   pIn1 = &aMem[pOp->p1];
   70241   if( pIn1->flags & MEM_Null ){
   70242     c = pOp->p3;
   70243   }else{
   70244 #ifdef SQLITE_OMIT_FLOATING_POINT
   70245     c = sqlite3VdbeIntValue(pIn1)!=0;
   70246 #else
   70247     c = sqlite3VdbeRealValue(pIn1)!=0.0;
   70248 #endif
   70249     if( pOp->opcode==OP_IfNot ) c = !c;
   70250   }
   70251   VdbeBranchTaken(c!=0, 2);
   70252   if( c ){
   70253     pc = pOp->p2-1;
   70254   }
   70255   break;
   70256 }
   70257 
   70258 /* Opcode: IsNull P1 P2 * * *
   70259 ** Synopsis:  if r[P1]==NULL goto P2
   70260 **
   70261 ** Jump to P2 if the value in register P1 is NULL.
   70262 */
   70263 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
   70264   pIn1 = &aMem[pOp->p1];
   70265   VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
   70266   if( (pIn1->flags & MEM_Null)!=0 ){
   70267     pc = pOp->p2 - 1;
   70268   }
   70269   break;
   70270 }
   70271 
   70272 /* Opcode: NotNull P1 P2 * * *
   70273 ** Synopsis: if r[P1]!=NULL goto P2
   70274 **
   70275 ** Jump to P2 if the value in register P1 is not NULL.
   70276 */
   70277 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
   70278   pIn1 = &aMem[pOp->p1];
   70279   VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
   70280   if( (pIn1->flags & MEM_Null)==0 ){
   70281     pc = pOp->p2 - 1;
   70282   }
   70283   break;
   70284 }
   70285 
   70286 /* Opcode: Column P1 P2 P3 P4 P5
   70287 ** Synopsis:  r[P3]=PX
   70288 **
   70289 ** Interpret the data that cursor P1 points to as a structure built using
   70290 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
   70291 ** information about the format of the data.)  Extract the P2-th column
   70292 ** from this record.  If there are less that (P2+1)
   70293 ** values in the record, extract a NULL.
   70294 **
   70295 ** The value extracted is stored in register P3.
   70296 **
   70297 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
   70298 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
   70299 ** the result.
   70300 **
   70301 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
   70302 ** then the cache of the cursor is reset prior to extracting the column.
   70303 ** The first OP_Column against a pseudo-table after the value of the content
   70304 ** register has changed should have this bit set.
   70305 **
   70306 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
   70307 ** the result is guaranteed to only be used as the argument of a length()
   70308 ** or typeof() function, respectively.  The loading of large blobs can be
   70309 ** skipped for length() and all content loading can be skipped for typeof().
   70310 */
   70311 case OP_Column: {
   70312   i64 payloadSize64; /* Number of bytes in the record */
   70313   int p2;            /* column number to retrieve */
   70314   VdbeCursor *pC;    /* The VDBE cursor */
   70315   BtCursor *pCrsr;   /* The BTree cursor */
   70316   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   70317   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   70318   int len;           /* The length of the serialized data for the column */
   70319   int i;             /* Loop counter */
   70320   Mem *pDest;        /* Where to write the extracted value */
   70321   Mem sMem;          /* For storing the record being decoded */
   70322   const u8 *zData;   /* Part of the record being decoded */
   70323   const u8 *zHdr;    /* Next unparsed byte of the header */
   70324   const u8 *zEndHdr; /* Pointer to first byte after the header */
   70325   u32 offset;        /* Offset into the data */
   70326   u32 szField;       /* Number of bytes in the content of a field */
   70327   u32 avail;         /* Number of bytes of available data */
   70328   u32 t;             /* A type code from the record header */
   70329   Mem *pReg;         /* PseudoTable input register */
   70330 
   70331   p2 = pOp->p2;
   70332   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   70333   pDest = &aMem[pOp->p3];
   70334   memAboutToChange(p, pDest);
   70335   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   70336   pC = p->apCsr[pOp->p1];
   70337   assert( pC!=0 );
   70338   assert( p2<pC->nField );
   70339   aType = pC->aType;
   70340   aOffset = aType + pC->nField;
   70341 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70342   assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
   70343 #endif
   70344   pCrsr = pC->pCursor;
   70345   assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
   70346   assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
   70347 
   70348   /* If the cursor cache is stale, bring it up-to-date */
   70349   rc = sqlite3VdbeCursorMoveto(pC);
   70350   if( rc ) goto abort_due_to_error;
   70351   if( pC->cacheStatus!=p->cacheCtr || (pOp->p5&OPFLAG_CLEARCACHE)!=0 ){
   70352     if( pC->nullRow ){
   70353       if( pCrsr==0 ){
   70354         assert( pC->pseudoTableReg>0 );
   70355         pReg = &aMem[pC->pseudoTableReg];
   70356         assert( pReg->flags & MEM_Blob );
   70357         assert( memIsValid(pReg) );
   70358         pC->payloadSize = pC->szRow = avail = pReg->n;
   70359         pC->aRow = (u8*)pReg->z;
   70360       }else{
   70361         MemSetTypeFlag(pDest, MEM_Null);
   70362         goto op_column_out;
   70363       }
   70364     }else{
   70365       assert( pCrsr );
   70366       if( pC->isTable==0 ){
   70367         assert( sqlite3BtreeCursorIsValid(pCrsr) );
   70368         VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
   70369         assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
   70370         /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
   70371         ** payload size, so it is impossible for payloadSize64 to be
   70372         ** larger than 32 bits. */
   70373         assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
   70374         pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
   70375         pC->payloadSize = (u32)payloadSize64;
   70376       }else{
   70377         assert( sqlite3BtreeCursorIsValid(pCrsr) );
   70378         VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
   70379         assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
   70380         pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
   70381       }
   70382       assert( avail<=65536 );  /* Maximum page size is 64KiB */
   70383       if( pC->payloadSize <= (u32)avail ){
   70384         pC->szRow = pC->payloadSize;
   70385       }else{
   70386         pC->szRow = avail;
   70387       }
   70388       if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   70389         goto too_big;
   70390       }
   70391     }
   70392     pC->cacheStatus = p->cacheCtr;
   70393     pC->iHdrOffset = getVarint32(pC->aRow, offset);
   70394     pC->nHdrParsed = 0;
   70395     aOffset[0] = offset;
   70396     if( avail<offset ){
   70397       /* pC->aRow does not have to hold the entire row, but it does at least
   70398       ** need to cover the header of the record.  If pC->aRow does not contain
   70399       ** the complete header, then set it to zero, forcing the header to be
   70400       ** dynamically allocated. */
   70401       pC->aRow = 0;
   70402       pC->szRow = 0;
   70403     }
   70404 
   70405     /* Make sure a corrupt database has not given us an oversize header.
   70406     ** Do this now to avoid an oversize memory allocation.
   70407     **
   70408     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
   70409     ** types use so much data space that there can only be 4096 and 32 of
   70410     ** them, respectively.  So the maximum header length results from a
   70411     ** 3-byte type for each of the maximum of 32768 columns plus three
   70412     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
   70413     */
   70414     if( offset > 98307 || offset > pC->payloadSize ){
   70415       rc = SQLITE_CORRUPT_BKPT;
   70416       goto op_column_error;
   70417     }
   70418   }
   70419 
   70420   /* Make sure at least the first p2+1 entries of the header have been
   70421   ** parsed and valid information is in aOffset[] and aType[].
   70422   */
   70423   if( pC->nHdrParsed<=p2 ){
   70424     /* If there is more header available for parsing in the record, try
   70425     ** to extract additional fields up through the p2+1-th field
   70426     */
   70427     if( pC->iHdrOffset<aOffset[0] ){
   70428       /* Make sure zData points to enough of the record to cover the header. */
   70429       if( pC->aRow==0 ){
   70430         memset(&sMem, 0, sizeof(sMem));
   70431         rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
   70432                                      !pC->isTable, &sMem);
   70433         if( rc!=SQLITE_OK ){
   70434           goto op_column_error;
   70435         }
   70436         zData = (u8*)sMem.z;
   70437       }else{
   70438         zData = pC->aRow;
   70439       }
   70440 
   70441       /* Fill in aType[i] and aOffset[i] values through the p2-th field. */
   70442       i = pC->nHdrParsed;
   70443       offset = aOffset[i];
   70444       zHdr = zData + pC->iHdrOffset;
   70445       zEndHdr = zData + aOffset[0];
   70446       assert( i<=p2 && zHdr<zEndHdr );
   70447       do{
   70448         if( zHdr[0]<0x80 ){
   70449           t = zHdr[0];
   70450           zHdr++;
   70451         }else{
   70452           zHdr += sqlite3GetVarint32(zHdr, &t);
   70453         }
   70454         aType[i] = t;
   70455         szField = sqlite3VdbeSerialTypeLen(t);
   70456         offset += szField;
   70457         if( offset<szField ){  /* True if offset overflows */
   70458           zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
   70459           break;
   70460         }
   70461         i++;
   70462         aOffset[i] = offset;
   70463       }while( i<=p2 && zHdr<zEndHdr );
   70464       pC->nHdrParsed = i;
   70465       pC->iHdrOffset = (u32)(zHdr - zData);
   70466       if( pC->aRow==0 ){
   70467         sqlite3VdbeMemRelease(&sMem);
   70468         sMem.flags = MEM_Null;
   70469       }
   70470 
   70471       /* If we have read more header data than was contained in the header,
   70472       ** or if the end of the last field appears to be past the end of the
   70473       ** record, or if the end of the last field appears to be before the end
   70474       ** of the record (when all fields present), then we must be dealing
   70475       ** with a corrupt database.
   70476       */
   70477       if( (zHdr > zEndHdr)
   70478        || (offset > pC->payloadSize)
   70479        || (zHdr==zEndHdr && offset!=pC->payloadSize)
   70480       ){
   70481         rc = SQLITE_CORRUPT_BKPT;
   70482         goto op_column_error;
   70483       }
   70484     }
   70485 
   70486     /* If after trying to extra new entries from the header, nHdrParsed is
   70487     ** still not up to p2, that means that the record has fewer than p2
   70488     ** columns.  So the result will be either the default value or a NULL.
   70489     */
   70490     if( pC->nHdrParsed<=p2 ){
   70491       if( pOp->p4type==P4_MEM ){
   70492         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
   70493       }else{
   70494         MemSetTypeFlag(pDest, MEM_Null);
   70495       }
   70496       goto op_column_out;
   70497     }
   70498   }
   70499 
   70500   /* Extract the content for the p2+1-th column.  Control can only
   70501   ** reach this point if aOffset[p2], aOffset[p2+1], and aType[p2] are
   70502   ** all valid.
   70503   */
   70504   assert( p2<pC->nHdrParsed );
   70505   assert( rc==SQLITE_OK );
   70506   assert( sqlite3VdbeCheckMemInvariants(pDest) );
   70507   if( pC->szRow>=aOffset[p2+1] ){
   70508     /* This is the common case where the desired content fits on the original
   70509     ** page - where the content is not on an overflow page */
   70510     VdbeMemRelease(pDest);
   70511     sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], aType[p2], pDest);
   70512   }else{
   70513     /* This branch happens only when content is on overflow pages */
   70514     t = aType[p2];
   70515     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
   70516           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
   70517      || (len = sqlite3VdbeSerialTypeLen(t))==0
   70518     ){
   70519       /* Content is irrelevant for the typeof() function and for
   70520       ** the length(X) function if X is a blob.  So we might as well use
   70521       ** bogus content rather than reading content from disk.  NULL works
   70522       ** for text and blob and whatever is in the payloadSize64 variable
   70523       ** will work for everything else.  Content is also irrelevant if
   70524       ** the content length is 0. */
   70525       zData = t<=13 ? (u8*)&payloadSize64 : 0;
   70526       sMem.zMalloc = 0;
   70527     }else{
   70528       memset(&sMem, 0, sizeof(sMem));
   70529       sqlite3VdbeMemMove(&sMem, pDest);
   70530       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
   70531                                    &sMem);
   70532       if( rc!=SQLITE_OK ){
   70533         goto op_column_error;
   70534       }
   70535       zData = (u8*)sMem.z;
   70536     }
   70537     sqlite3VdbeSerialGet(zData, t, pDest);
   70538     /* If we dynamically allocated space to hold the data (in the
   70539     ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
   70540     ** dynamically allocated space over to the pDest structure.
   70541     ** This prevents a memory copy. */
   70542     if( sMem.zMalloc ){
   70543       assert( sMem.z==sMem.zMalloc );
   70544       assert( VdbeMemDynamic(pDest)==0 );
   70545       assert( (pDest->flags & (MEM_Blob|MEM_Str))==0 || pDest->z==sMem.z );
   70546       pDest->flags &= ~(MEM_Ephem|MEM_Static);
   70547       pDest->flags |= MEM_Term;
   70548       pDest->z = sMem.z;
   70549       pDest->zMalloc = sMem.zMalloc;
   70550     }
   70551   }
   70552   pDest->enc = encoding;
   70553 
   70554 op_column_out:
   70555   Deephemeralize(pDest);
   70556 op_column_error:
   70557   UPDATE_MAX_BLOBSIZE(pDest);
   70558   REGISTER_TRACE(pOp->p3, pDest);
   70559   break;
   70560 }
   70561 
   70562 /* Opcode: Affinity P1 P2 * P4 *
   70563 ** Synopsis: affinity(r[P1@P2])
   70564 **
   70565 ** Apply affinities to a range of P2 registers starting with P1.
   70566 **
   70567 ** P4 is a string that is P2 characters long. The nth character of the
   70568 ** string indicates the column affinity that should be used for the nth
   70569 ** memory cell in the range.
   70570 */
   70571 case OP_Affinity: {
   70572   const char *zAffinity;   /* The affinity to be applied */
   70573   char cAff;               /* A single character of affinity */
   70574 
   70575   zAffinity = pOp->p4.z;
   70576   assert( zAffinity!=0 );
   70577   assert( zAffinity[pOp->p2]==0 );
   70578   pIn1 = &aMem[pOp->p1];
   70579   while( (cAff = *(zAffinity++))!=0 ){
   70580     assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
   70581     assert( memIsValid(pIn1) );
   70582     applyAffinity(pIn1, cAff, encoding);
   70583     pIn1++;
   70584   }
   70585   break;
   70586 }
   70587 
   70588 /* Opcode: MakeRecord P1 P2 P3 P4 *
   70589 ** Synopsis: r[P3]=mkrec(r[P1@P2])
   70590 **
   70591 ** Convert P2 registers beginning with P1 into the [record format]
   70592 ** use as a data record in a database table or as a key
   70593 ** in an index.  The OP_Column opcode can decode the record later.
   70594 **
   70595 ** P4 may be a string that is P2 characters long.  The nth character of the
   70596 ** string indicates the column affinity that should be used for the nth
   70597 ** field of the index key.
   70598 **
   70599 ** The mapping from character to affinity is given by the SQLITE_AFF_
   70600 ** macros defined in sqliteInt.h.
   70601 **
   70602 ** If P4 is NULL then all index fields have the affinity NONE.
   70603 */
   70604 case OP_MakeRecord: {
   70605   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   70606   Mem *pRec;             /* The new record */
   70607   u64 nData;             /* Number of bytes of data space */
   70608   int nHdr;              /* Number of bytes of header space */
   70609   i64 nByte;             /* Data space required for this record */
   70610   int nZero;             /* Number of zero bytes at the end of the record */
   70611   int nVarint;           /* Number of bytes in a varint */
   70612   u32 serial_type;       /* Type field */
   70613   Mem *pData0;           /* First field to be combined into the record */
   70614   Mem *pLast;            /* Last field of the record */
   70615   int nField;            /* Number of fields in the record */
   70616   char *zAffinity;       /* The affinity string for the record */
   70617   int file_format;       /* File format to use for encoding */
   70618   int i;                 /* Space used in zNewRecord[] header */
   70619   int j;                 /* Space used in zNewRecord[] content */
   70620   int len;               /* Length of a field */
   70621 
   70622   /* Assuming the record contains N fields, the record format looks
   70623   ** like this:
   70624   **
   70625   ** ------------------------------------------------------------------------
   70626   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
   70627   ** ------------------------------------------------------------------------
   70628   **
   70629   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
   70630   ** and so froth.
   70631   **
   70632   ** Each type field is a varint representing the serial type of the
   70633   ** corresponding data element (see sqlite3VdbeSerialType()). The
   70634   ** hdr-size field is also a varint which is the offset from the beginning
   70635   ** of the record to data0.
   70636   */
   70637   nData = 0;         /* Number of bytes of data space */
   70638   nHdr = 0;          /* Number of bytes of header space */
   70639   nZero = 0;         /* Number of zero bytes at the end of the record */
   70640   nField = pOp->p1;
   70641   zAffinity = pOp->p4.z;
   70642   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
   70643   pData0 = &aMem[nField];
   70644   nField = pOp->p2;
   70645   pLast = &pData0[nField-1];
   70646   file_format = p->minWriteFileFormat;
   70647 
   70648   /* Identify the output register */
   70649   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
   70650   pOut = &aMem[pOp->p3];
   70651   memAboutToChange(p, pOut);
   70652 
   70653   /* Apply the requested affinity to all inputs
   70654   */
   70655   assert( pData0<=pLast );
   70656   if( zAffinity ){
   70657     pRec = pData0;
   70658     do{
   70659       applyAffinity(pRec++, *(zAffinity++), encoding);
   70660       assert( zAffinity[0]==0 || pRec<=pLast );
   70661     }while( zAffinity[0] );
   70662   }
   70663 
   70664   /* Loop through the elements that will make up the record to figure
   70665   ** out how much space is required for the new record.
   70666   */
   70667   pRec = pLast;
   70668   do{
   70669     assert( memIsValid(pRec) );
   70670     serial_type = sqlite3VdbeSerialType(pRec, file_format);
   70671     len = sqlite3VdbeSerialTypeLen(serial_type);
   70672     if( pRec->flags & MEM_Zero ){
   70673       if( nData ){
   70674         sqlite3VdbeMemExpandBlob(pRec);
   70675       }else{
   70676         nZero += pRec->u.nZero;
   70677         len -= pRec->u.nZero;
   70678       }
   70679     }
   70680     nData += len;
   70681     testcase( serial_type==127 );
   70682     testcase( serial_type==128 );
   70683     nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
   70684   }while( (--pRec)>=pData0 );
   70685 
   70686   /* Add the initial header varint and total the size */
   70687   testcase( nHdr==126 );
   70688   testcase( nHdr==127 );
   70689   if( nHdr<=126 ){
   70690     /* The common case */
   70691     nHdr += 1;
   70692   }else{
   70693     /* Rare case of a really large header */
   70694     nVarint = sqlite3VarintLen(nHdr);
   70695     nHdr += nVarint;
   70696     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
   70697   }
   70698   nByte = nHdr+nData;
   70699   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   70700     goto too_big;
   70701   }
   70702 
   70703   /* Make sure the output register has a buffer large enough to store
   70704   ** the new record. The output register (pOp->p3) is not allowed to
   70705   ** be one of the input registers (because the following call to
   70706   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
   70707   */
   70708   if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
   70709     goto no_mem;
   70710   }
   70711   zNewRecord = (u8 *)pOut->z;
   70712 
   70713   /* Write the record */
   70714   i = putVarint32(zNewRecord, nHdr);
   70715   j = nHdr;
   70716   assert( pData0<=pLast );
   70717   pRec = pData0;
   70718   do{
   70719     serial_type = sqlite3VdbeSerialType(pRec, file_format);
   70720     i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
   70721     j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
   70722   }while( (++pRec)<=pLast );
   70723   assert( i==nHdr );
   70724   assert( j==nByte );
   70725 
   70726   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   70727   pOut->n = (int)nByte;
   70728   pOut->flags = MEM_Blob;
   70729   pOut->xDel = 0;
   70730   if( nZero ){
   70731     pOut->u.nZero = nZero;
   70732     pOut->flags |= MEM_Zero;
   70733   }
   70734   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
   70735   REGISTER_TRACE(pOp->p3, pOut);
   70736   UPDATE_MAX_BLOBSIZE(pOut);
   70737   break;
   70738 }
   70739 
   70740 /* Opcode: Count P1 P2 * * *
   70741 ** Synopsis: r[P2]=count()
   70742 **
   70743 ** Store the number of entries (an integer value) in the table or index
   70744 ** opened by cursor P1 in register P2
   70745 */
   70746 #ifndef SQLITE_OMIT_BTREECOUNT
   70747 case OP_Count: {         /* out2-prerelease */
   70748   i64 nEntry;
   70749   BtCursor *pCrsr;
   70750 
   70751   pCrsr = p->apCsr[pOp->p1]->pCursor;
   70752   assert( pCrsr );
   70753   nEntry = 0;  /* Not needed.  Only used to silence a warning. */
   70754   rc = sqlite3BtreeCount(pCrsr, &nEntry);
   70755   pOut->u.i = nEntry;
   70756   break;
   70757 }
   70758 #endif
   70759 
   70760 /* Opcode: Savepoint P1 * * P4 *
   70761 **
   70762 ** Open, release or rollback the savepoint named by parameter P4, depending
   70763 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
   70764 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
   70765 */
   70766 case OP_Savepoint: {
   70767   int p1;                         /* Value of P1 operand */
   70768   char *zName;                    /* Name of savepoint */
   70769   int nName;
   70770   Savepoint *pNew;
   70771   Savepoint *pSavepoint;
   70772   Savepoint *pTmp;
   70773   int iSavepoint;
   70774   int ii;
   70775 
   70776   p1 = pOp->p1;
   70777   zName = pOp->p4.z;
   70778 
   70779   /* Assert that the p1 parameter is valid. Also that if there is no open
   70780   ** transaction, then there cannot be any savepoints.
   70781   */
   70782   assert( db->pSavepoint==0 || db->autoCommit==0 );
   70783   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
   70784   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
   70785   assert( checkSavepointCount(db) );
   70786   assert( p->bIsReader );
   70787 
   70788   if( p1==SAVEPOINT_BEGIN ){
   70789     if( db->nVdbeWrite>0 ){
   70790       /* A new savepoint cannot be created if there are active write
   70791       ** statements (i.e. open read/write incremental blob handles).
   70792       */
   70793       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
   70794         "SQL statements in progress");
   70795       rc = SQLITE_BUSY;
   70796     }else{
   70797       nName = sqlite3Strlen30(zName);
   70798 
   70799 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70800       /* This call is Ok even if this savepoint is actually a transaction
   70801       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
   70802       ** If this is a transaction savepoint being opened, it is guaranteed
   70803       ** that the db->aVTrans[] array is empty.  */
   70804       assert( db->autoCommit==0 || db->nVTrans==0 );
   70805       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
   70806                                 db->nStatement+db->nSavepoint);
   70807       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   70808 #endif
   70809 
   70810       /* Create a new savepoint structure. */
   70811       pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
   70812       if( pNew ){
   70813         pNew->zName = (char *)&pNew[1];
   70814         memcpy(pNew->zName, zName, nName+1);
   70815 
   70816         /* If there is no open transaction, then mark this as a special
   70817         ** "transaction savepoint". */
   70818         if( db->autoCommit ){
   70819           db->autoCommit = 0;
   70820           db->isTransactionSavepoint = 1;
   70821         }else{
   70822           db->nSavepoint++;
   70823         }
   70824 
   70825         /* Link the new savepoint into the database handle's list. */
   70826         pNew->pNext = db->pSavepoint;
   70827         db->pSavepoint = pNew;
   70828         pNew->nDeferredCons = db->nDeferredCons;
   70829         pNew->nDeferredImmCons = db->nDeferredImmCons;
   70830       }
   70831     }
   70832   }else{
   70833     iSavepoint = 0;
   70834 
   70835     /* Find the named savepoint. If there is no such savepoint, then an
   70836     ** an error is returned to the user.  */
   70837     for(
   70838       pSavepoint = db->pSavepoint;
   70839       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
   70840       pSavepoint = pSavepoint->pNext
   70841     ){
   70842       iSavepoint++;
   70843     }
   70844     if( !pSavepoint ){
   70845       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
   70846       rc = SQLITE_ERROR;
   70847     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
   70848       /* It is not possible to release (commit) a savepoint if there are
   70849       ** active write statements.
   70850       */
   70851       sqlite3SetString(&p->zErrMsg, db,
   70852         "cannot release savepoint - SQL statements in progress"
   70853       );
   70854       rc = SQLITE_BUSY;
   70855     }else{
   70856 
   70857       /* Determine whether or not this is a transaction savepoint. If so,
   70858       ** and this is a RELEASE command, then the current transaction
   70859       ** is committed.
   70860       */
   70861       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
   70862       if( isTransaction && p1==SAVEPOINT_RELEASE ){
   70863         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   70864           goto vdbe_return;
   70865         }
   70866         db->autoCommit = 1;
   70867         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   70868           p->pc = pc;
   70869           db->autoCommit = 0;
   70870           p->rc = rc = SQLITE_BUSY;
   70871           goto vdbe_return;
   70872         }
   70873         db->isTransactionSavepoint = 0;
   70874         rc = p->rc;
   70875       }else{
   70876         iSavepoint = db->nSavepoint - iSavepoint - 1;
   70877         if( p1==SAVEPOINT_ROLLBACK ){
   70878           for(ii=0; ii<db->nDb; ii++){
   70879             sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT);
   70880           }
   70881         }
   70882         for(ii=0; ii<db->nDb; ii++){
   70883           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
   70884           if( rc!=SQLITE_OK ){
   70885             goto abort_due_to_error;
   70886           }
   70887         }
   70888         if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
   70889           sqlite3ExpirePreparedStatements(db);
   70890           sqlite3ResetAllSchemasOfConnection(db);
   70891           db->flags = (db->flags | SQLITE_InternChanges);
   70892         }
   70893       }
   70894 
   70895       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
   70896       ** savepoints nested inside of the savepoint being operated on. */
   70897       while( db->pSavepoint!=pSavepoint ){
   70898         pTmp = db->pSavepoint;
   70899         db->pSavepoint = pTmp->pNext;
   70900         sqlite3DbFree(db, pTmp);
   70901         db->nSavepoint--;
   70902       }
   70903 
   70904       /* If it is a RELEASE, then destroy the savepoint being operated on
   70905       ** too. If it is a ROLLBACK TO, then set the number of deferred
   70906       ** constraint violations present in the database to the value stored
   70907       ** when the savepoint was created.  */
   70908       if( p1==SAVEPOINT_RELEASE ){
   70909         assert( pSavepoint==db->pSavepoint );
   70910         db->pSavepoint = pSavepoint->pNext;
   70911         sqlite3DbFree(db, pSavepoint);
   70912         if( !isTransaction ){
   70913           db->nSavepoint--;
   70914         }
   70915       }else{
   70916         db->nDeferredCons = pSavepoint->nDeferredCons;
   70917         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
   70918       }
   70919 
   70920       if( !isTransaction ){
   70921         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
   70922         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   70923       }
   70924     }
   70925   }
   70926 
   70927   break;
   70928 }
   70929 
   70930 /* Opcode: AutoCommit P1 P2 * * *
   70931 **
   70932 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
   70933 ** back any currently active btree transactions. If there are any active
   70934 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
   70935 ** there are active writing VMs or active VMs that use shared cache.
   70936 **
   70937 ** This instruction causes the VM to halt.
   70938 */
   70939 case OP_AutoCommit: {
   70940   int desiredAutoCommit;
   70941   int iRollback;
   70942   int turnOnAC;
   70943 
   70944   desiredAutoCommit = pOp->p1;
   70945   iRollback = pOp->p2;
   70946   turnOnAC = desiredAutoCommit && !db->autoCommit;
   70947   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
   70948   assert( desiredAutoCommit==1 || iRollback==0 );
   70949   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
   70950   assert( p->bIsReader );
   70951 
   70952 #if 0
   70953   if( turnOnAC && iRollback && db->nVdbeActive>1 ){
   70954     /* If this instruction implements a ROLLBACK and other VMs are
   70955     ** still running, and a transaction is active, return an error indicating
   70956     ** that the other VMs must complete first.
   70957     */
   70958     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
   70959         "SQL statements in progress");
   70960     rc = SQLITE_BUSY;
   70961   }else
   70962 #endif
   70963   if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
   70964     /* If this instruction implements a COMMIT and other VMs are writing
   70965     ** return an error indicating that the other VMs must complete first.
   70966     */
   70967     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
   70968         "SQL statements in progress");
   70969     rc = SQLITE_BUSY;
   70970   }else if( desiredAutoCommit!=db->autoCommit ){
   70971     if( iRollback ){
   70972       assert( desiredAutoCommit==1 );
   70973       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   70974       db->autoCommit = 1;
   70975     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   70976       goto vdbe_return;
   70977     }else{
   70978       db->autoCommit = (u8)desiredAutoCommit;
   70979       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   70980         p->pc = pc;
   70981         db->autoCommit = (u8)(1-desiredAutoCommit);
   70982         p->rc = rc = SQLITE_BUSY;
   70983         goto vdbe_return;
   70984       }
   70985     }
   70986     assert( db->nStatement==0 );
   70987     sqlite3CloseSavepoints(db);
   70988     if( p->rc==SQLITE_OK ){
   70989       rc = SQLITE_DONE;
   70990     }else{
   70991       rc = SQLITE_ERROR;
   70992     }
   70993     goto vdbe_return;
   70994   }else{
   70995     sqlite3SetString(&p->zErrMsg, db,
   70996         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
   70997         (iRollback)?"cannot rollback - no transaction is active":
   70998                    "cannot commit - no transaction is active"));
   70999 
   71000     rc = SQLITE_ERROR;
   71001   }
   71002   break;
   71003 }
   71004 
   71005 /* Opcode: Transaction P1 P2 P3 P4 P5
   71006 **
   71007 ** Begin a transaction on database P1 if a transaction is not already
   71008 ** active.
   71009 ** If P2 is non-zero, then a write-transaction is started, or if a
   71010 ** read-transaction is already active, it is upgraded to a write-transaction.
   71011 ** If P2 is zero, then a read-transaction is started.
   71012 **
   71013 ** P1 is the index of the database file on which the transaction is
   71014 ** started.  Index 0 is the main database file and index 1 is the
   71015 ** file used for temporary tables.  Indices of 2 or more are used for
   71016 ** attached databases.
   71017 **
   71018 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
   71019 ** true (this flag is set if the Vdbe may modify more than one row and may
   71020 ** throw an ABORT exception), a statement transaction may also be opened.
   71021 ** More specifically, a statement transaction is opened iff the database
   71022 ** connection is currently not in autocommit mode, or if there are other
   71023 ** active statements. A statement transaction allows the changes made by this
   71024 ** VDBE to be rolled back after an error without having to roll back the
   71025 ** entire transaction. If no error is encountered, the statement transaction
   71026 ** will automatically commit when the VDBE halts.
   71027 **
   71028 ** If P5!=0 then this opcode also checks the schema cookie against P3
   71029 ** and the schema generation counter against P4.
   71030 ** The cookie changes its value whenever the database schema changes.
   71031 ** This operation is used to detect when that the cookie has changed
   71032 ** and that the current process needs to reread the schema.  If the schema
   71033 ** cookie in P3 differs from the schema cookie in the database header or
   71034 ** if the schema generation counter in P4 differs from the current
   71035 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
   71036 ** halts.  The sqlite3_step() wrapper function might then reprepare the
   71037 ** statement and rerun it from the beginning.
   71038 */
   71039 case OP_Transaction: {
   71040   Btree *pBt;
   71041   int iMeta;
   71042   int iGen;
   71043 
   71044   assert( p->bIsReader );
   71045   assert( p->readOnly==0 || pOp->p2==0 );
   71046   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   71047   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   71048   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
   71049     rc = SQLITE_READONLY;
   71050     goto abort_due_to_error;
   71051   }
   71052   pBt = db->aDb[pOp->p1].pBt;
   71053 
   71054   if( pBt ){
   71055     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
   71056     if( rc==SQLITE_BUSY ){
   71057       p->pc = pc;
   71058       p->rc = rc = SQLITE_BUSY;
   71059       goto vdbe_return;
   71060     }
   71061     if( rc!=SQLITE_OK ){
   71062       goto abort_due_to_error;
   71063     }
   71064 
   71065     if( pOp->p2 && p->usesStmtJournal
   71066      && (db->autoCommit==0 || db->nVdbeRead>1)
   71067     ){
   71068       assert( sqlite3BtreeIsInTrans(pBt) );
   71069       if( p->iStatement==0 ){
   71070         assert( db->nStatement>=0 && db->nSavepoint>=0 );
   71071         db->nStatement++;
   71072         p->iStatement = db->nSavepoint + db->nStatement;
   71073       }
   71074 
   71075       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
   71076       if( rc==SQLITE_OK ){
   71077         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
   71078       }
   71079 
   71080       /* Store the current value of the database handles deferred constraint
   71081       ** counter. If the statement transaction needs to be rolled back,
   71082       ** the value of this counter needs to be restored too.  */
   71083       p->nStmtDefCons = db->nDeferredCons;
   71084       p->nStmtDefImmCons = db->nDeferredImmCons;
   71085     }
   71086 
   71087     /* Gather the schema version number for checking */
   71088     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
   71089     iGen = db->aDb[pOp->p1].pSchema->iGeneration;
   71090   }else{
   71091     iGen = iMeta = 0;
   71092   }
   71093   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
   71094   if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
   71095     sqlite3DbFree(db, p->zErrMsg);
   71096     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
   71097     /* If the schema-cookie from the database file matches the cookie
   71098     ** stored with the in-memory representation of the schema, do
   71099     ** not reload the schema from the database file.
   71100     **
   71101     ** If virtual-tables are in use, this is not just an optimization.
   71102     ** Often, v-tables store their data in other SQLite tables, which
   71103     ** are queried from within xNext() and other v-table methods using
   71104     ** prepared queries. If such a query is out-of-date, we do not want to
   71105     ** discard the database schema, as the user code implementing the
   71106     ** v-table would have to be ready for the sqlite3_vtab structure itself
   71107     ** to be invalidated whenever sqlite3_step() is called from within
   71108     ** a v-table method.
   71109     */
   71110     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
   71111       sqlite3ResetOneSchema(db, pOp->p1);
   71112     }
   71113     p->expired = 1;
   71114     rc = SQLITE_SCHEMA;
   71115   }
   71116   break;
   71117 }
   71118 
   71119 /* Opcode: ReadCookie P1 P2 P3 * *
   71120 **
   71121 ** Read cookie number P3 from database P1 and write it into register P2.
   71122 ** P3==1 is the schema version.  P3==2 is the database format.
   71123 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
   71124 ** the main database file and P1==1 is the database file used to store
   71125 ** temporary tables.
   71126 **
   71127 ** There must be a read-lock on the database (either a transaction
   71128 ** must be started or there must be an open cursor) before
   71129 ** executing this instruction.
   71130 */
   71131 case OP_ReadCookie: {               /* out2-prerelease */
   71132   int iMeta;
   71133   int iDb;
   71134   int iCookie;
   71135 
   71136   assert( p->bIsReader );
   71137   iDb = pOp->p1;
   71138   iCookie = pOp->p3;
   71139   assert( pOp->p3<SQLITE_N_BTREE_META );
   71140   assert( iDb>=0 && iDb<db->nDb );
   71141   assert( db->aDb[iDb].pBt!=0 );
   71142   assert( DbMaskTest(p->btreeMask, iDb) );
   71143 
   71144   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
   71145   pOut->u.i = iMeta;
   71146   break;
   71147 }
   71148 
   71149 /* Opcode: SetCookie P1 P2 P3 * *
   71150 **
   71151 ** Write the content of register P3 (interpreted as an integer)
   71152 ** into cookie number P2 of database P1.  P2==1 is the schema version.
   71153 ** P2==2 is the database format. P2==3 is the recommended pager cache
   71154 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
   71155 ** database file used to store temporary tables.
   71156 **
   71157 ** A transaction must be started before executing this opcode.
   71158 */
   71159 case OP_SetCookie: {       /* in3 */
   71160   Db *pDb;
   71161   assert( pOp->p2<SQLITE_N_BTREE_META );
   71162   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   71163   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   71164   assert( p->readOnly==0 );
   71165   pDb = &db->aDb[pOp->p1];
   71166   assert( pDb->pBt!=0 );
   71167   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
   71168   pIn3 = &aMem[pOp->p3];
   71169   sqlite3VdbeMemIntegerify(pIn3);
   71170   /* See note about index shifting on OP_ReadCookie */
   71171   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
   71172   if( pOp->p2==BTREE_SCHEMA_VERSION ){
   71173     /* When the schema cookie changes, record the new cookie internally */
   71174     pDb->pSchema->schema_cookie = (int)pIn3->u.i;
   71175     db->flags |= SQLITE_InternChanges;
   71176   }else if( pOp->p2==BTREE_FILE_FORMAT ){
   71177     /* Record changes in the file format */
   71178     pDb->pSchema->file_format = (u8)pIn3->u.i;
   71179   }
   71180   if( pOp->p1==1 ){
   71181     /* Invalidate all prepared statements whenever the TEMP database
   71182     ** schema is changed.  Ticket #1644 */
   71183     sqlite3ExpirePreparedStatements(db);
   71184     p->expired = 0;
   71185   }
   71186   break;
   71187 }
   71188 
   71189 /* Opcode: OpenRead P1 P2 P3 P4 P5
   71190 ** Synopsis: root=P2 iDb=P3
   71191 **
   71192 ** Open a read-only cursor for the database table whose root page is
   71193 ** P2 in a database file.  The database file is determined by P3.
   71194 ** P3==0 means the main database, P3==1 means the database used for
   71195 ** temporary tables, and P3>1 means used the corresponding attached
   71196 ** database.  Give the new cursor an identifier of P1.  The P1
   71197 ** values need not be contiguous but all P1 values should be small integers.
   71198 ** It is an error for P1 to be negative.
   71199 **
   71200 ** If P5!=0 then use the content of register P2 as the root page, not
   71201 ** the value of P2 itself.
   71202 **
   71203 ** There will be a read lock on the database whenever there is an
   71204 ** open cursor.  If the database was unlocked prior to this instruction
   71205 ** then a read lock is acquired as part of this instruction.  A read
   71206 ** lock allows other processes to read the database but prohibits
   71207 ** any other process from modifying the database.  The read lock is
   71208 ** released when all cursors are closed.  If this instruction attempts
   71209 ** to get a read lock but fails, the script terminates with an
   71210 ** SQLITE_BUSY error code.
   71211 **
   71212 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   71213 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   71214 ** structure, then said structure defines the content and collating
   71215 ** sequence of the index being opened. Otherwise, if P4 is an integer
   71216 ** value, it is set to the number of columns in the table.
   71217 **
   71218 ** See also: OpenWrite, ReopenIdx
   71219 */
   71220 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
   71221 ** Synopsis: root=P2 iDb=P3
   71222 **
   71223 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
   71224 ** checks to see if the cursor on P1 is already open with a root page
   71225 ** number of P2 and if it is this opcode becomes a no-op.  In other words,
   71226 ** if the cursor is already open, do not reopen it.
   71227 **
   71228 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
   71229 ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
   71230 ** every other ReopenIdx or OpenRead for the same cursor number.
   71231 **
   71232 ** See the OpenRead opcode documentation for additional information.
   71233 */
   71234 /* Opcode: OpenWrite P1 P2 P3 P4 P5
   71235 ** Synopsis: root=P2 iDb=P3
   71236 **
   71237 ** Open a read/write cursor named P1 on the table or index whose root
   71238 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
   71239 ** root page.
   71240 **
   71241 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   71242 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   71243 ** structure, then said structure defines the content and collating
   71244 ** sequence of the index being opened. Otherwise, if P4 is an integer
   71245 ** value, it is set to the number of columns in the table, or to the
   71246 ** largest index of any column of the table that is actually used.
   71247 **
   71248 ** This instruction works just like OpenRead except that it opens the cursor
   71249 ** in read/write mode.  For a given table, there can be one or more read-only
   71250 ** cursors or a single read/write cursor but not both.
   71251 **
   71252 ** See also OpenRead.
   71253 */
   71254 case OP_ReopenIdx: {
   71255   VdbeCursor *pCur;
   71256 
   71257   assert( pOp->p5==0 );
   71258   assert( pOp->p4type==P4_KEYINFO );
   71259   pCur = p->apCsr[pOp->p1];
   71260   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
   71261     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
   71262     break;
   71263   }
   71264   /* If the cursor is not currently open or is open on a different
   71265   ** index, then fall through into OP_OpenRead to force a reopen */
   71266 }
   71267 case OP_OpenRead:
   71268 case OP_OpenWrite: {
   71269   int nField;
   71270   KeyInfo *pKeyInfo;
   71271   int p2;
   71272   int iDb;
   71273   int wrFlag;
   71274   Btree *pX;
   71275   VdbeCursor *pCur;
   71276   Db *pDb;
   71277 
   71278   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
   71279   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
   71280   assert( p->bIsReader );
   71281   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
   71282           || p->readOnly==0 );
   71283 
   71284   if( p->expired ){
   71285     rc = SQLITE_ABORT;
   71286     break;
   71287   }
   71288 
   71289   nField = 0;
   71290   pKeyInfo = 0;
   71291   p2 = pOp->p2;
   71292   iDb = pOp->p3;
   71293   assert( iDb>=0 && iDb<db->nDb );
   71294   assert( DbMaskTest(p->btreeMask, iDb) );
   71295   pDb = &db->aDb[iDb];
   71296   pX = pDb->pBt;
   71297   assert( pX!=0 );
   71298   if( pOp->opcode==OP_OpenWrite ){
   71299     wrFlag = 1;
   71300     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   71301     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
   71302       p->minWriteFileFormat = pDb->pSchema->file_format;
   71303     }
   71304   }else{
   71305     wrFlag = 0;
   71306   }
   71307   if( pOp->p5 & OPFLAG_P2ISREG ){
   71308     assert( p2>0 );
   71309     assert( p2<=(p->nMem-p->nCursor) );
   71310     pIn2 = &aMem[p2];
   71311     assert( memIsValid(pIn2) );
   71312     assert( (pIn2->flags & MEM_Int)!=0 );
   71313     sqlite3VdbeMemIntegerify(pIn2);
   71314     p2 = (int)pIn2->u.i;
   71315     /* The p2 value always comes from a prior OP_CreateTable opcode and
   71316     ** that opcode will always set the p2 value to 2 or more or else fail.
   71317     ** If there were a failure, the prepared statement would have halted
   71318     ** before reaching this instruction. */
   71319     if( NEVER(p2<2) ) {
   71320       rc = SQLITE_CORRUPT_BKPT;
   71321       goto abort_due_to_error;
   71322     }
   71323   }
   71324   if( pOp->p4type==P4_KEYINFO ){
   71325     pKeyInfo = pOp->p4.pKeyInfo;
   71326     assert( pKeyInfo->enc==ENC(db) );
   71327     assert( pKeyInfo->db==db );
   71328     nField = pKeyInfo->nField+pKeyInfo->nXField;
   71329   }else if( pOp->p4type==P4_INT32 ){
   71330     nField = pOp->p4.i;
   71331   }
   71332   assert( pOp->p1>=0 );
   71333   assert( nField>=0 );
   71334   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
   71335   pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
   71336   if( pCur==0 ) goto no_mem;
   71337   pCur->nullRow = 1;
   71338   pCur->isOrdered = 1;
   71339   pCur->pgnoRoot = p2;
   71340   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
   71341   pCur->pKeyInfo = pKeyInfo;
   71342   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
   71343   sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
   71344 
   71345   /* Since it performs no memory allocation or IO, the only value that
   71346   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
   71347   assert( rc==SQLITE_OK );
   71348 
   71349   /* Set the VdbeCursor.isTable variable. Previous versions of
   71350   ** SQLite used to check if the root-page flags were sane at this point
   71351   ** and report database corruption if they were not, but this check has
   71352   ** since moved into the btree layer.  */
   71353   pCur->isTable = pOp->p4type!=P4_KEYINFO;
   71354   break;
   71355 }
   71356 
   71357 /* Opcode: OpenEphemeral P1 P2 * P4 P5
   71358 ** Synopsis: nColumn=P2
   71359 **
   71360 ** Open a new cursor P1 to a transient table.
   71361 ** The cursor is always opened read/write even if
   71362 ** the main database is read-only.  The ephemeral
   71363 ** table is deleted automatically when the cursor is closed.
   71364 **
   71365 ** P2 is the number of columns in the ephemeral table.
   71366 ** The cursor points to a BTree table if P4==0 and to a BTree index
   71367 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
   71368 ** that defines the format of keys in the index.
   71369 **
   71370 ** The P5 parameter can be a mask of the BTREE_* flags defined
   71371 ** in btree.h.  These flags control aspects of the operation of
   71372 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
   71373 ** added automatically.
   71374 */
   71375 /* Opcode: OpenAutoindex P1 P2 * P4 *
   71376 ** Synopsis: nColumn=P2
   71377 **
   71378 ** This opcode works the same as OP_OpenEphemeral.  It has a
   71379 ** different name to distinguish its use.  Tables created using
   71380 ** by this opcode will be used for automatically created transient
   71381 ** indices in joins.
   71382 */
   71383 case OP_OpenAutoindex:
   71384 case OP_OpenEphemeral: {
   71385   VdbeCursor *pCx;
   71386   KeyInfo *pKeyInfo;
   71387 
   71388   static const int vfsFlags =
   71389       SQLITE_OPEN_READWRITE |
   71390       SQLITE_OPEN_CREATE |
   71391       SQLITE_OPEN_EXCLUSIVE |
   71392       SQLITE_OPEN_DELETEONCLOSE |
   71393       SQLITE_OPEN_TRANSIENT_DB;
   71394   assert( pOp->p1>=0 );
   71395   assert( pOp->p2>=0 );
   71396   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   71397   if( pCx==0 ) goto no_mem;
   71398   pCx->nullRow = 1;
   71399   pCx->isEphemeral = 1;
   71400   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
   71401                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
   71402   if( rc==SQLITE_OK ){
   71403     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
   71404   }
   71405   if( rc==SQLITE_OK ){
   71406     /* If a transient index is required, create it by calling
   71407     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
   71408     ** opening it. If a transient table is required, just use the
   71409     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
   71410     */
   71411     if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
   71412       int pgno;
   71413       assert( pOp->p4type==P4_KEYINFO );
   71414       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
   71415       if( rc==SQLITE_OK ){
   71416         assert( pgno==MASTER_ROOT+1 );
   71417         assert( pKeyInfo->db==db );
   71418         assert( pKeyInfo->enc==ENC(db) );
   71419         pCx->pKeyInfo = pKeyInfo;
   71420         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
   71421       }
   71422       pCx->isTable = 0;
   71423     }else{
   71424       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
   71425       pCx->isTable = 1;
   71426     }
   71427   }
   71428   pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
   71429   break;
   71430 }
   71431 
   71432 /* Opcode: SorterOpen P1 P2 * P4 *
   71433 **
   71434 ** This opcode works like OP_OpenEphemeral except that it opens
   71435 ** a transient index that is specifically designed to sort large
   71436 ** tables using an external merge-sort algorithm.
   71437 */
   71438 case OP_SorterOpen: {
   71439   VdbeCursor *pCx;
   71440 
   71441   assert( pOp->p1>=0 );
   71442   assert( pOp->p2>=0 );
   71443   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   71444   if( pCx==0 ) goto no_mem;
   71445   pCx->pKeyInfo = pOp->p4.pKeyInfo;
   71446   assert( pCx->pKeyInfo->db==db );
   71447   assert( pCx->pKeyInfo->enc==ENC(db) );
   71448   rc = sqlite3VdbeSorterInit(db, pCx);
   71449   break;
   71450 }
   71451 
   71452 /* Opcode: OpenPseudo P1 P2 P3 * *
   71453 ** Synopsis: P3 columns in r[P2]
   71454 **
   71455 ** Open a new cursor that points to a fake table that contains a single
   71456 ** row of data.  The content of that one row is the content of memory
   71457 ** register P2.  In other words, cursor P1 becomes an alias for the
   71458 ** MEM_Blob content contained in register P2.
   71459 **
   71460 ** A pseudo-table created by this opcode is used to hold a single
   71461 ** row output from the sorter so that the row can be decomposed into
   71462 ** individual columns using the OP_Column opcode.  The OP_Column opcode
   71463 ** is the only cursor opcode that works with a pseudo-table.
   71464 **
   71465 ** P3 is the number of fields in the records that will be stored by
   71466 ** the pseudo-table.
   71467 */
   71468 case OP_OpenPseudo: {
   71469   VdbeCursor *pCx;
   71470 
   71471   assert( pOp->p1>=0 );
   71472   assert( pOp->p3>=0 );
   71473   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
   71474   if( pCx==0 ) goto no_mem;
   71475   pCx->nullRow = 1;
   71476   pCx->pseudoTableReg = pOp->p2;
   71477   pCx->isTable = 1;
   71478   assert( pOp->p5==0 );
   71479   break;
   71480 }
   71481 
   71482 /* Opcode: Close P1 * * * *
   71483 **
   71484 ** Close a cursor previously opened as P1.  If P1 is not
   71485 ** currently open, this instruction is a no-op.
   71486 */
   71487 case OP_Close: {
   71488   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71489   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
   71490   p->apCsr[pOp->p1] = 0;
   71491   break;
   71492 }
   71493 
   71494 /* Opcode: SeekGE P1 P2 P3 P4 *
   71495 ** Synopsis: key=r[P3@P4]
   71496 **
   71497 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   71498 ** use the value in register P3 as the key.  If cursor P1 refers
   71499 ** to an SQL index, then P3 is the first in an array of P4 registers
   71500 ** that are used as an unpacked index key.
   71501 **
   71502 ** Reposition cursor P1 so that  it points to the smallest entry that
   71503 ** is greater than or equal to the key value. If there are no records
   71504 ** greater than or equal to the key and P2 is not zero, then jump to P2.
   71505 **
   71506 ** This opcode leaves the cursor configured to move in forward order,
   71507 ** from the beginning toward the end.  In other words, the cursor is
   71508 ** configured to use Next, not Prev.
   71509 **
   71510 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
   71511 */
   71512 /* Opcode: SeekGT P1 P2 P3 P4 *
   71513 ** Synopsis: key=r[P3@P4]
   71514 **
   71515 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   71516 ** use the value in register P3 as a key. If cursor P1 refers
   71517 ** to an SQL index, then P3 is the first in an array of P4 registers
   71518 ** that are used as an unpacked index key.
   71519 **
   71520 ** Reposition cursor P1 so that  it points to the smallest entry that
   71521 ** is greater than the key value. If there are no records greater than
   71522 ** the key and P2 is not zero, then jump to P2.
   71523 **
   71524 ** This opcode leaves the cursor configured to move in forward order,
   71525 ** from the beginning toward the end.  In other words, the cursor is
   71526 ** configured to use Next, not Prev.
   71527 **
   71528 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
   71529 */
   71530 /* Opcode: SeekLT P1 P2 P3 P4 *
   71531 ** Synopsis: key=r[P3@P4]
   71532 **
   71533 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   71534 ** use the value in register P3 as a key. If cursor P1 refers
   71535 ** to an SQL index, then P3 is the first in an array of P4 registers
   71536 ** that are used as an unpacked index key.
   71537 **
   71538 ** Reposition cursor P1 so that  it points to the largest entry that
   71539 ** is less than the key value. If there are no records less than
   71540 ** the key and P2 is not zero, then jump to P2.
   71541 **
   71542 ** This opcode leaves the cursor configured to move in reverse order,
   71543 ** from the end toward the beginning.  In other words, the cursor is
   71544 ** configured to use Prev, not Next.
   71545 **
   71546 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
   71547 */
   71548 /* Opcode: SeekLE P1 P2 P3 P4 *
   71549 ** Synopsis: key=r[P3@P4]
   71550 **
   71551 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   71552 ** use the value in register P3 as a key. If cursor P1 refers
   71553 ** to an SQL index, then P3 is the first in an array of P4 registers
   71554 ** that are used as an unpacked index key.
   71555 **
   71556 ** Reposition cursor P1 so that it points to the largest entry that
   71557 ** is less than or equal to the key value. If there are no records
   71558 ** less than or equal to the key and P2 is not zero, then jump to P2.
   71559 **
   71560 ** This opcode leaves the cursor configured to move in reverse order,
   71561 ** from the end toward the beginning.  In other words, the cursor is
   71562 ** configured to use Prev, not Next.
   71563 **
   71564 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
   71565 */
   71566 case OP_SeekLT:         /* jump, in3 */
   71567 case OP_SeekLE:         /* jump, in3 */
   71568 case OP_SeekGE:         /* jump, in3 */
   71569 case OP_SeekGT: {       /* jump, in3 */
   71570   int res;
   71571   int oc;
   71572   VdbeCursor *pC;
   71573   UnpackedRecord r;
   71574   int nField;
   71575   i64 iKey;      /* The rowid we are to seek to */
   71576 
   71577   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71578   assert( pOp->p2!=0 );
   71579   pC = p->apCsr[pOp->p1];
   71580   assert( pC!=0 );
   71581   assert( pC->pseudoTableReg==0 );
   71582   assert( OP_SeekLE == OP_SeekLT+1 );
   71583   assert( OP_SeekGE == OP_SeekLT+2 );
   71584   assert( OP_SeekGT == OP_SeekLT+3 );
   71585   assert( pC->isOrdered );
   71586   assert( pC->pCursor!=0 );
   71587   oc = pOp->opcode;
   71588   pC->nullRow = 0;
   71589 #ifdef SQLITE_DEBUG
   71590   pC->seekOp = pOp->opcode;
   71591 #endif
   71592   if( pC->isTable ){
   71593     /* The input value in P3 might be of any type: integer, real, string,
   71594     ** blob, or NULL.  But it needs to be an integer before we can do
   71595     ** the seek, so covert it. */
   71596     pIn3 = &aMem[pOp->p3];
   71597     ApplyNumericAffinity(pIn3);
   71598     iKey = sqlite3VdbeIntValue(pIn3);
   71599     pC->rowidIsValid = 0;
   71600 
   71601     /* If the P3 value could not be converted into an integer without
   71602     ** loss of information, then special processing is required... */
   71603     if( (pIn3->flags & MEM_Int)==0 ){
   71604       if( (pIn3->flags & MEM_Real)==0 ){
   71605         /* If the P3 value cannot be converted into any kind of a number,
   71606         ** then the seek is not possible, so jump to P2 */
   71607         pc = pOp->p2 - 1;  VdbeBranchTaken(1,2);
   71608         break;
   71609       }
   71610 
   71611       /* If the approximation iKey is larger than the actual real search
   71612       ** term, substitute >= for > and < for <=. e.g. if the search term
   71613       ** is 4.9 and the integer approximation 5:
   71614       **
   71615       **        (x >  4.9)    ->     (x >= 5)
   71616       **        (x <= 4.9)    ->     (x <  5)
   71617       */
   71618       if( pIn3->r<(double)iKey ){
   71619         assert( OP_SeekGE==(OP_SeekGT-1) );
   71620         assert( OP_SeekLT==(OP_SeekLE-1) );
   71621         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
   71622         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
   71623       }
   71624 
   71625       /* If the approximation iKey is smaller than the actual real search
   71626       ** term, substitute <= for < and > for >=.  */
   71627       else if( pIn3->r>(double)iKey ){
   71628         assert( OP_SeekLE==(OP_SeekLT+1) );
   71629         assert( OP_SeekGT==(OP_SeekGE+1) );
   71630         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
   71631         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
   71632       }
   71633     }
   71634     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
   71635     if( rc!=SQLITE_OK ){
   71636       goto abort_due_to_error;
   71637     }
   71638     if( res==0 ){
   71639       pC->rowidIsValid = 1;
   71640       pC->lastRowid = iKey;
   71641     }
   71642   }else{
   71643     nField = pOp->p4.i;
   71644     assert( pOp->p4type==P4_INT32 );
   71645     assert( nField>0 );
   71646     r.pKeyInfo = pC->pKeyInfo;
   71647     r.nField = (u16)nField;
   71648 
   71649     /* The next line of code computes as follows, only faster:
   71650     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
   71651     **     r.default_rc = -1;
   71652     **   }else{
   71653     **     r.default_rc = +1;
   71654     **   }
   71655     */
   71656     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
   71657     assert( oc!=OP_SeekGT || r.default_rc==-1 );
   71658     assert( oc!=OP_SeekLE || r.default_rc==-1 );
   71659     assert( oc!=OP_SeekGE || r.default_rc==+1 );
   71660     assert( oc!=OP_SeekLT || r.default_rc==+1 );
   71661 
   71662     r.aMem = &aMem[pOp->p3];
   71663 #ifdef SQLITE_DEBUG
   71664     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
   71665 #endif
   71666     ExpandBlob(r.aMem);
   71667     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
   71668     if( rc!=SQLITE_OK ){
   71669       goto abort_due_to_error;
   71670     }
   71671     pC->rowidIsValid = 0;
   71672   }
   71673   pC->deferredMoveto = 0;
   71674   pC->cacheStatus = CACHE_STALE;
   71675 #ifdef SQLITE_TEST
   71676   sqlite3_search_count++;
   71677 #endif
   71678   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
   71679     if( res<0 || (res==0 && oc==OP_SeekGT) ){
   71680       res = 0;
   71681       rc = sqlite3BtreeNext(pC->pCursor, &res);
   71682       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   71683       pC->rowidIsValid = 0;
   71684     }else{
   71685       res = 0;
   71686     }
   71687   }else{
   71688     assert( oc==OP_SeekLT || oc==OP_SeekLE );
   71689     if( res>0 || (res==0 && oc==OP_SeekLT) ){
   71690       res = 0;
   71691       rc = sqlite3BtreePrevious(pC->pCursor, &res);
   71692       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   71693       pC->rowidIsValid = 0;
   71694     }else{
   71695       /* res might be negative because the table is empty.  Check to
   71696       ** see if this is the case.
   71697       */
   71698       res = sqlite3BtreeEof(pC->pCursor);
   71699     }
   71700   }
   71701   assert( pOp->p2>0 );
   71702   VdbeBranchTaken(res!=0,2);
   71703   if( res ){
   71704     pc = pOp->p2 - 1;
   71705   }
   71706   break;
   71707 }
   71708 
   71709 /* Opcode: Seek P1 P2 * * *
   71710 ** Synopsis:  intkey=r[P2]
   71711 **
   71712 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
   71713 ** for P1 to move so that it points to the rowid given by P2.
   71714 **
   71715 ** This is actually a deferred seek.  Nothing actually happens until
   71716 ** the cursor is used to read a record.  That way, if no reads
   71717 ** occur, no unnecessary I/O happens.
   71718 */
   71719 case OP_Seek: {    /* in2 */
   71720   VdbeCursor *pC;
   71721 
   71722   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71723   pC = p->apCsr[pOp->p1];
   71724   assert( pC!=0 );
   71725   assert( pC->pCursor!=0 );
   71726   assert( pC->isTable );
   71727   pC->nullRow = 0;
   71728   pIn2 = &aMem[pOp->p2];
   71729   pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
   71730   pC->rowidIsValid = 0;
   71731   pC->deferredMoveto = 1;
   71732   break;
   71733 }
   71734 
   71735 
   71736 /* Opcode: Found P1 P2 P3 P4 *
   71737 ** Synopsis: key=r[P3@P4]
   71738 **
   71739 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   71740 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   71741 ** record.
   71742 **
   71743 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   71744 ** is a prefix of any entry in P1 then a jump is made to P2 and
   71745 ** P1 is left pointing at the matching entry.
   71746 **
   71747 ** This operation leaves the cursor in a state where it can be
   71748 ** advanced in the forward direction.  The Next instruction will work,
   71749 ** but not the Prev instruction.
   71750 **
   71751 ** See also: NotFound, NoConflict, NotExists. SeekGe
   71752 */
   71753 /* Opcode: NotFound P1 P2 P3 P4 *
   71754 ** Synopsis: key=r[P3@P4]
   71755 **
   71756 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   71757 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   71758 ** record.
   71759 **
   71760 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   71761 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
   71762 ** does contain an entry whose prefix matches the P3/P4 record then control
   71763 ** falls through to the next instruction and P1 is left pointing at the
   71764 ** matching entry.
   71765 **
   71766 ** This operation leaves the cursor in a state where it cannot be
   71767 ** advanced in either direction.  In other words, the Next and Prev
   71768 ** opcodes do not work after this operation.
   71769 **
   71770 ** See also: Found, NotExists, NoConflict
   71771 */
   71772 /* Opcode: NoConflict P1 P2 P3 P4 *
   71773 ** Synopsis: key=r[P3@P4]
   71774 **
   71775 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   71776 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   71777 ** record.
   71778 **
   71779 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   71780 ** contains any NULL value, jump immediately to P2.  If all terms of the
   71781 ** record are not-NULL then a check is done to determine if any row in the
   71782 ** P1 index btree has a matching key prefix.  If there are no matches, jump
   71783 ** immediately to P2.  If there is a match, fall through and leave the P1
   71784 ** cursor pointing to the matching row.
   71785 **
   71786 ** This opcode is similar to OP_NotFound with the exceptions that the
   71787 ** branch is always taken if any part of the search key input is NULL.
   71788 **
   71789 ** This operation leaves the cursor in a state where it cannot be
   71790 ** advanced in either direction.  In other words, the Next and Prev
   71791 ** opcodes do not work after this operation.
   71792 **
   71793 ** See also: NotFound, Found, NotExists
   71794 */
   71795 case OP_NoConflict:     /* jump, in3 */
   71796 case OP_NotFound:       /* jump, in3 */
   71797 case OP_Found: {        /* jump, in3 */
   71798   int alreadyExists;
   71799   int ii;
   71800   VdbeCursor *pC;
   71801   int res;
   71802   char *pFree;
   71803   UnpackedRecord *pIdxKey;
   71804   UnpackedRecord r;
   71805   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
   71806 
   71807 #ifdef SQLITE_TEST
   71808   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
   71809 #endif
   71810 
   71811   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71812   assert( pOp->p4type==P4_INT32 );
   71813   pC = p->apCsr[pOp->p1];
   71814   assert( pC!=0 );
   71815 #ifdef SQLITE_DEBUG
   71816   pC->seekOp = pOp->opcode;
   71817 #endif
   71818   pIn3 = &aMem[pOp->p3];
   71819   assert( pC->pCursor!=0 );
   71820   assert( pC->isTable==0 );
   71821   pFree = 0;  /* Not needed.  Only used to suppress a compiler warning. */
   71822   if( pOp->p4.i>0 ){
   71823     r.pKeyInfo = pC->pKeyInfo;
   71824     r.nField = (u16)pOp->p4.i;
   71825     r.aMem = pIn3;
   71826     for(ii=0; ii<r.nField; ii++){
   71827       assert( memIsValid(&r.aMem[ii]) );
   71828       ExpandBlob(&r.aMem[ii]);
   71829 #ifdef SQLITE_DEBUG
   71830       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
   71831 #endif
   71832     }
   71833     pIdxKey = &r;
   71834   }else{
   71835     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
   71836         pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
   71837     );
   71838     if( pIdxKey==0 ) goto no_mem;
   71839     assert( pIn3->flags & MEM_Blob );
   71840     assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
   71841     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
   71842   }
   71843   pIdxKey->default_rc = 0;
   71844   if( pOp->opcode==OP_NoConflict ){
   71845     /* For the OP_NoConflict opcode, take the jump if any of the
   71846     ** input fields are NULL, since any key with a NULL will not
   71847     ** conflict */
   71848     for(ii=0; ii<r.nField; ii++){
   71849       if( r.aMem[ii].flags & MEM_Null ){
   71850         pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
   71851         break;
   71852       }
   71853     }
   71854   }
   71855   rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
   71856   if( pOp->p4.i==0 ){
   71857     sqlite3DbFree(db, pFree);
   71858   }
   71859   if( rc!=SQLITE_OK ){
   71860     break;
   71861   }
   71862   pC->seekResult = res;
   71863   alreadyExists = (res==0);
   71864   pC->nullRow = 1-alreadyExists;
   71865   pC->deferredMoveto = 0;
   71866   pC->cacheStatus = CACHE_STALE;
   71867   if( pOp->opcode==OP_Found ){
   71868     VdbeBranchTaken(alreadyExists!=0,2);
   71869     if( alreadyExists ) pc = pOp->p2 - 1;
   71870   }else{
   71871     VdbeBranchTaken(alreadyExists==0,2);
   71872     if( !alreadyExists ) pc = pOp->p2 - 1;
   71873   }
   71874   break;
   71875 }
   71876 
   71877 /* Opcode: NotExists P1 P2 P3 * *
   71878 ** Synopsis: intkey=r[P3]
   71879 **
   71880 ** P1 is the index of a cursor open on an SQL table btree (with integer
   71881 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
   71882 ** rowid P3 then jump immediately to P2.  If P1 does contain a record
   71883 ** with rowid P3 then leave the cursor pointing at that record and fall
   71884 ** through to the next instruction.
   71885 **
   71886 ** The OP_NotFound opcode performs the same operation on index btrees
   71887 ** (with arbitrary multi-value keys).
   71888 **
   71889 ** This opcode leaves the cursor in a state where it cannot be advanced
   71890 ** in either direction.  In other words, the Next and Prev opcodes will
   71891 ** not work following this opcode.
   71892 **
   71893 ** See also: Found, NotFound, NoConflict
   71894 */
   71895 case OP_NotExists: {        /* jump, in3 */
   71896   VdbeCursor *pC;
   71897   BtCursor *pCrsr;
   71898   int res;
   71899   u64 iKey;
   71900 
   71901   pIn3 = &aMem[pOp->p3];
   71902   assert( pIn3->flags & MEM_Int );
   71903   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71904   pC = p->apCsr[pOp->p1];
   71905   assert( pC!=0 );
   71906 #ifdef SQLITE_DEBUG
   71907   pC->seekOp = 0;
   71908 #endif
   71909   assert( pC->isTable );
   71910   assert( pC->pseudoTableReg==0 );
   71911   pCrsr = pC->pCursor;
   71912   assert( pCrsr!=0 );
   71913   res = 0;
   71914   iKey = pIn3->u.i;
   71915   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
   71916   pC->lastRowid = pIn3->u.i;
   71917   pC->rowidIsValid = res==0 ?1:0;
   71918   pC->nullRow = 0;
   71919   pC->cacheStatus = CACHE_STALE;
   71920   pC->deferredMoveto = 0;
   71921   VdbeBranchTaken(res!=0,2);
   71922   if( res!=0 ){
   71923     pc = pOp->p2 - 1;
   71924     assert( pC->rowidIsValid==0 );
   71925   }
   71926   pC->seekResult = res;
   71927   break;
   71928 }
   71929 
   71930 /* Opcode: Sequence P1 P2 * * *
   71931 ** Synopsis: r[P2]=cursor[P1].ctr++
   71932 **
   71933 ** Find the next available sequence number for cursor P1.
   71934 ** Write the sequence number into register P2.
   71935 ** The sequence number on the cursor is incremented after this
   71936 ** instruction.
   71937 */
   71938 case OP_Sequence: {           /* out2-prerelease */
   71939   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71940   assert( p->apCsr[pOp->p1]!=0 );
   71941   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
   71942   break;
   71943 }
   71944 
   71945 
   71946 /* Opcode: NewRowid P1 P2 P3 * *
   71947 ** Synopsis: r[P2]=rowid
   71948 **
   71949 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
   71950 ** The record number is not previously used as a key in the database
   71951 ** table that cursor P1 points to.  The new record number is written
   71952 ** written to register P2.
   71953 **
   71954 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
   71955 ** the largest previously generated record number. No new record numbers are
   71956 ** allowed to be less than this value. When this value reaches its maximum,
   71957 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
   71958 ** generated record number. This P3 mechanism is used to help implement the
   71959 ** AUTOINCREMENT feature.
   71960 */
   71961 case OP_NewRowid: {           /* out2-prerelease */
   71962   i64 v;                 /* The new rowid */
   71963   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   71964   int res;               /* Result of an sqlite3BtreeLast() */
   71965   int cnt;               /* Counter to limit the number of searches */
   71966   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   71967   VdbeFrame *pFrame;     /* Root frame of VDBE */
   71968 
   71969   v = 0;
   71970   res = 0;
   71971   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   71972   pC = p->apCsr[pOp->p1];
   71973   assert( pC!=0 );
   71974   if( NEVER(pC->pCursor==0) ){
   71975     /* The zero initialization above is all that is needed */
   71976   }else{
   71977     /* The next rowid or record number (different terms for the same
   71978     ** thing) is obtained in a two-step algorithm.
   71979     **
   71980     ** First we attempt to find the largest existing rowid and add one
   71981     ** to that.  But if the largest existing rowid is already the maximum
   71982     ** positive integer, we have to fall through to the second
   71983     ** probabilistic algorithm
   71984     **
   71985     ** The second algorithm is to select a rowid at random and see if
   71986     ** it already exists in the table.  If it does not exist, we have
   71987     ** succeeded.  If the random rowid does exist, we select a new one
   71988     ** and try again, up to 100 times.
   71989     */
   71990     assert( pC->isTable );
   71991 
   71992 #ifdef SQLITE_32BIT_ROWID
   71993 #   define MAX_ROWID 0x7fffffff
   71994 #else
   71995     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
   71996     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
   71997     ** to provide the constant while making all compilers happy.
   71998     */
   71999 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
   72000 #endif
   72001 
   72002     if( !pC->useRandomRowid ){
   72003       rc = sqlite3BtreeLast(pC->pCursor, &res);
   72004       if( rc!=SQLITE_OK ){
   72005         goto abort_due_to_error;
   72006       }
   72007       if( res ){
   72008         v = 1;   /* IMP: R-61914-48074 */
   72009       }else{
   72010         assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
   72011         rc = sqlite3BtreeKeySize(pC->pCursor, &v);
   72012         assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
   72013         if( v>=MAX_ROWID ){
   72014           pC->useRandomRowid = 1;
   72015         }else{
   72016           v++;   /* IMP: R-29538-34987 */
   72017         }
   72018       }
   72019     }
   72020 
   72021 #ifndef SQLITE_OMIT_AUTOINCREMENT
   72022     if( pOp->p3 ){
   72023       /* Assert that P3 is a valid memory cell. */
   72024       assert( pOp->p3>0 );
   72025       if( p->pFrame ){
   72026         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   72027         /* Assert that P3 is a valid memory cell. */
   72028         assert( pOp->p3<=pFrame->nMem );
   72029         pMem = &pFrame->aMem[pOp->p3];
   72030       }else{
   72031         /* Assert that P3 is a valid memory cell. */
   72032         assert( pOp->p3<=(p->nMem-p->nCursor) );
   72033         pMem = &aMem[pOp->p3];
   72034         memAboutToChange(p, pMem);
   72035       }
   72036       assert( memIsValid(pMem) );
   72037 
   72038       REGISTER_TRACE(pOp->p3, pMem);
   72039       sqlite3VdbeMemIntegerify(pMem);
   72040       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
   72041       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
   72042         rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
   72043         goto abort_due_to_error;
   72044       }
   72045       if( v<pMem->u.i+1 ){
   72046         v = pMem->u.i + 1;
   72047       }
   72048       pMem->u.i = v;
   72049     }
   72050 #endif
   72051     if( pC->useRandomRowid ){
   72052       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
   72053       ** largest possible integer (9223372036854775807) then the database
   72054       ** engine starts picking positive candidate ROWIDs at random until
   72055       ** it finds one that is not previously used. */
   72056       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
   72057                              ** an AUTOINCREMENT table. */
   72058       /* on the first attempt, simply do one more than previous */
   72059       v = lastRowid;
   72060       v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   72061       v++; /* ensure non-zero */
   72062       cnt = 0;
   72063       while(   ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
   72064                                                  0, &res))==SQLITE_OK)
   72065             && (res==0)
   72066             && (++cnt<100)){
   72067         /* collision - try another random rowid */
   72068         sqlite3_randomness(sizeof(v), &v);
   72069         if( cnt<5 ){
   72070           /* try "small" random rowids for the initial attempts */
   72071           v &= 0xffffff;
   72072         }else{
   72073           v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   72074         }
   72075         v++; /* ensure non-zero */
   72076       }
   72077       if( rc==SQLITE_OK && res==0 ){
   72078         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
   72079         goto abort_due_to_error;
   72080       }
   72081       assert( v>0 );  /* EV: R-40812-03570 */
   72082     }
   72083     pC->rowidIsValid = 0;
   72084     pC->deferredMoveto = 0;
   72085     pC->cacheStatus = CACHE_STALE;
   72086   }
   72087   pOut->u.i = v;
   72088   break;
   72089 }
   72090 
   72091 /* Opcode: Insert P1 P2 P3 P4 P5
   72092 ** Synopsis: intkey=r[P3] data=r[P2]
   72093 **
   72094 ** Write an entry into the table of cursor P1.  A new entry is
   72095 ** created if it doesn't already exist or the data for an existing
   72096 ** entry is overwritten.  The data is the value MEM_Blob stored in register
   72097 ** number P2. The key is stored in register P3. The key must
   72098 ** be a MEM_Int.
   72099 **
   72100 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
   72101 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
   72102 ** then rowid is stored for subsequent return by the
   72103 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
   72104 **
   72105 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
   72106 ** the last seek operation (OP_NotExists) was a success, then this
   72107 ** operation will not attempt to find the appropriate row before doing
   72108 ** the insert but will instead overwrite the row that the cursor is
   72109 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
   72110 ** has already positioned the cursor correctly.  This is an optimization
   72111 ** that boosts performance by avoiding redundant seeks.
   72112 **
   72113 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
   72114 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
   72115 ** is part of an INSERT operation.  The difference is only important to
   72116 ** the update hook.
   72117 **
   72118 ** Parameter P4 may point to a string containing the table-name, or
   72119 ** may be NULL. If it is not NULL, then the update-hook
   72120 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
   72121 **
   72122 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
   72123 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
   72124 ** and register P2 becomes ephemeral.  If the cursor is changed, the
   72125 ** value of register P2 will then change.  Make sure this does not
   72126 ** cause any problems.)
   72127 **
   72128 ** This instruction only works on tables.  The equivalent instruction
   72129 ** for indices is OP_IdxInsert.
   72130 */
   72131 /* Opcode: InsertInt P1 P2 P3 P4 P5
   72132 ** Synopsis:  intkey=P3 data=r[P2]
   72133 **
   72134 ** This works exactly like OP_Insert except that the key is the
   72135 ** integer value P3, not the value of the integer stored in register P3.
   72136 */
   72137 case OP_Insert:
   72138 case OP_InsertInt: {
   72139   Mem *pData;       /* MEM cell holding data for the record to be inserted */
   72140   Mem *pKey;        /* MEM cell holding key  for the record */
   72141   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   72142   VdbeCursor *pC;   /* Cursor to table into which insert is written */
   72143   int nZero;        /* Number of zero-bytes to append */
   72144   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   72145   const char *zDb;  /* database name - used by the update hook */
   72146   const char *zTbl; /* Table name - used by the opdate hook */
   72147   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   72148 
   72149   pData = &aMem[pOp->p2];
   72150   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72151   assert( memIsValid(pData) );
   72152   pC = p->apCsr[pOp->p1];
   72153   assert( pC!=0 );
   72154   assert( pC->pCursor!=0 );
   72155   assert( pC->pseudoTableReg==0 );
   72156   assert( pC->isTable );
   72157   REGISTER_TRACE(pOp->p2, pData);
   72158 
   72159   if( pOp->opcode==OP_Insert ){
   72160     pKey = &aMem[pOp->p3];
   72161     assert( pKey->flags & MEM_Int );
   72162     assert( memIsValid(pKey) );
   72163     REGISTER_TRACE(pOp->p3, pKey);
   72164     iKey = pKey->u.i;
   72165   }else{
   72166     assert( pOp->opcode==OP_InsertInt );
   72167     iKey = pOp->p3;
   72168   }
   72169 
   72170   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   72171   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
   72172   if( pData->flags & MEM_Null ){
   72173     pData->z = 0;
   72174     pData->n = 0;
   72175   }else{
   72176     assert( pData->flags & (MEM_Blob|MEM_Str) );
   72177   }
   72178   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
   72179   if( pData->flags & MEM_Zero ){
   72180     nZero = pData->u.nZero;
   72181   }else{
   72182     nZero = 0;
   72183   }
   72184   rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
   72185                           pData->z, pData->n, nZero,
   72186                           (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
   72187   );
   72188   pC->rowidIsValid = 0;
   72189   pC->deferredMoveto = 0;
   72190   pC->cacheStatus = CACHE_STALE;
   72191 
   72192   /* Invoke the update-hook if required. */
   72193   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   72194     zDb = db->aDb[pC->iDb].zName;
   72195     zTbl = pOp->p4.z;
   72196     op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
   72197     assert( pC->isTable );
   72198     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
   72199     assert( pC->iDb>=0 );
   72200   }
   72201   break;
   72202 }
   72203 
   72204 /* Opcode: Delete P1 P2 * P4 *
   72205 **
   72206 ** Delete the record at which the P1 cursor is currently pointing.
   72207 **
   72208 ** The cursor will be left pointing at either the next or the previous
   72209 ** record in the table. If it is left pointing at the next record, then
   72210 ** the next Next instruction will be a no-op.  Hence it is OK to delete
   72211 ** a record from within a Next loop.
   72212 **
   72213 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
   72214 ** incremented (otherwise not).
   72215 **
   72216 ** P1 must not be pseudo-table.  It has to be a real table with
   72217 ** multiple rows.
   72218 **
   72219 ** If P4 is not NULL, then it is the name of the table that P1 is
   72220 ** pointing to.  The update hook will be invoked, if it exists.
   72221 ** If P4 is not NULL then the P1 cursor must have been positioned
   72222 ** using OP_NotFound prior to invoking this opcode.
   72223 */
   72224 case OP_Delete: {
   72225   i64 iKey;
   72226   VdbeCursor *pC;
   72227 
   72228   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72229   pC = p->apCsr[pOp->p1];
   72230   assert( pC!=0 );
   72231   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
   72232   iKey = pC->lastRowid;      /* Only used for the update hook */
   72233 
   72234   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
   72235   ** OP_Column on the same table without any intervening operations that
   72236   ** might move or invalidate the cursor.  Hence cursor pC is always pointing
   72237   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
   72238   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
   72239   ** to guard against future changes to the code generator.
   72240   **/
   72241   assert( pC->deferredMoveto==0 );
   72242   rc = sqlite3VdbeCursorMoveto(pC);
   72243   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   72244 
   72245   rc = sqlite3BtreeDelete(pC->pCursor);
   72246   pC->cacheStatus = CACHE_STALE;
   72247 
   72248   /* Invoke the update-hook if required. */
   72249   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
   72250     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
   72251                         db->aDb[pC->iDb].zName, pOp->p4.z, iKey);
   72252     assert( pC->iDb>=0 );
   72253   }
   72254   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
   72255   break;
   72256 }
   72257 /* Opcode: ResetCount * * * * *
   72258 **
   72259 ** The value of the change counter is copied to the database handle
   72260 ** change counter (returned by subsequent calls to sqlite3_changes()).
   72261 ** Then the VMs internal change counter resets to 0.
   72262 ** This is used by trigger programs.
   72263 */
   72264 case OP_ResetCount: {
   72265   sqlite3VdbeSetChanges(db, p->nChange);
   72266   p->nChange = 0;
   72267   break;
   72268 }
   72269 
   72270 /* Opcode: SorterCompare P1 P2 P3 P4
   72271 ** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
   72272 **
   72273 ** P1 is a sorter cursor. This instruction compares a prefix of the
   72274 ** record blob in register P3 against a prefix of the entry that
   72275 ** the sorter cursor currently points to.  Only the first P4 fields
   72276 ** of r[P3] and the sorter record are compared.
   72277 **
   72278 ** If either P3 or the sorter contains a NULL in one of their significant
   72279 ** fields (not counting the P4 fields at the end which are ignored) then
   72280 ** the comparison is assumed to be equal.
   72281 **
   72282 ** Fall through to next instruction if the two records compare equal to
   72283 ** each other.  Jump to P2 if they are different.
   72284 */
   72285 case OP_SorterCompare: {
   72286   VdbeCursor *pC;
   72287   int res;
   72288   int nKeyCol;
   72289 
   72290   pC = p->apCsr[pOp->p1];
   72291   assert( isSorter(pC) );
   72292   assert( pOp->p4type==P4_INT32 );
   72293   pIn3 = &aMem[pOp->p3];
   72294   nKeyCol = pOp->p4.i;
   72295   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
   72296   VdbeBranchTaken(res!=0,2);
   72297   if( res ){
   72298     pc = pOp->p2-1;
   72299   }
   72300   break;
   72301 };
   72302 
   72303 /* Opcode: SorterData P1 P2 * * *
   72304 ** Synopsis: r[P2]=data
   72305 **
   72306 ** Write into register P2 the current sorter data for sorter cursor P1.
   72307 */
   72308 case OP_SorterData: {
   72309   VdbeCursor *pC;
   72310 
   72311   pOut = &aMem[pOp->p2];
   72312   pC = p->apCsr[pOp->p1];
   72313   assert( isSorter(pC) );
   72314   rc = sqlite3VdbeSorterRowkey(pC, pOut);
   72315   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
   72316   break;
   72317 }
   72318 
   72319 /* Opcode: RowData P1 P2 * * *
   72320 ** Synopsis: r[P2]=data
   72321 **
   72322 ** Write into register P2 the complete row data for cursor P1.
   72323 ** There is no interpretation of the data.
   72324 ** It is just copied onto the P2 register exactly as
   72325 ** it is found in the database file.
   72326 **
   72327 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   72328 ** of a real table, not a pseudo-table.
   72329 */
   72330 /* Opcode: RowKey P1 P2 * * *
   72331 ** Synopsis: r[P2]=key
   72332 **
   72333 ** Write into register P2 the complete row key for cursor P1.
   72334 ** There is no interpretation of the data.
   72335 ** The key is copied onto the P2 register exactly as
   72336 ** it is found in the database file.
   72337 **
   72338 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   72339 ** of a real table, not a pseudo-table.
   72340 */
   72341 case OP_RowKey:
   72342 case OP_RowData: {
   72343   VdbeCursor *pC;
   72344   BtCursor *pCrsr;
   72345   u32 n;
   72346   i64 n64;
   72347 
   72348   pOut = &aMem[pOp->p2];
   72349   memAboutToChange(p, pOut);
   72350 
   72351   /* Note that RowKey and RowData are really exactly the same instruction */
   72352   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72353   pC = p->apCsr[pOp->p1];
   72354   assert( isSorter(pC)==0 );
   72355   assert( pC->isTable || pOp->opcode!=OP_RowData );
   72356   assert( pC->isTable==0 || pOp->opcode==OP_RowData );
   72357   assert( pC!=0 );
   72358   assert( pC->nullRow==0 );
   72359   assert( pC->pseudoTableReg==0 );
   72360   assert( pC->pCursor!=0 );
   72361   pCrsr = pC->pCursor;
   72362   assert( sqlite3BtreeCursorIsValid(pCrsr) );
   72363 
   72364   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
   72365   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
   72366   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
   72367   ** a no-op and can never fail.  But we leave it in place as a safety.
   72368   */
   72369   assert( pC->deferredMoveto==0 );
   72370   rc = sqlite3VdbeCursorMoveto(pC);
   72371   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   72372 
   72373   if( pC->isTable==0 ){
   72374     assert( !pC->isTable );
   72375     VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
   72376     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
   72377     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   72378       goto too_big;
   72379     }
   72380     n = (u32)n64;
   72381   }else{
   72382     VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
   72383     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
   72384     if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   72385       goto too_big;
   72386     }
   72387   }
   72388   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
   72389     goto no_mem;
   72390   }
   72391   pOut->n = n;
   72392   MemSetTypeFlag(pOut, MEM_Blob);
   72393   if( pC->isTable==0 ){
   72394     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
   72395   }else{
   72396     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
   72397   }
   72398   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
   72399   UPDATE_MAX_BLOBSIZE(pOut);
   72400   REGISTER_TRACE(pOp->p2, pOut);
   72401   break;
   72402 }
   72403 
   72404 /* Opcode: Rowid P1 P2 * * *
   72405 ** Synopsis: r[P2]=rowid
   72406 **
   72407 ** Store in register P2 an integer which is the key of the table entry that
   72408 ** P1 is currently point to.
   72409 **
   72410 ** P1 can be either an ordinary table or a virtual table.  There used to
   72411 ** be a separate OP_VRowid opcode for use with virtual tables, but this
   72412 ** one opcode now works for both table types.
   72413 */
   72414 case OP_Rowid: {                 /* out2-prerelease */
   72415   VdbeCursor *pC;
   72416   i64 v;
   72417   sqlite3_vtab *pVtab;
   72418   const sqlite3_module *pModule;
   72419 
   72420   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72421   pC = p->apCsr[pOp->p1];
   72422   assert( pC!=0 );
   72423   assert( pC->pseudoTableReg==0 || pC->nullRow );
   72424   if( pC->nullRow ){
   72425     pOut->flags = MEM_Null;
   72426     break;
   72427   }else if( pC->deferredMoveto ){
   72428     v = pC->movetoTarget;
   72429 #ifndef SQLITE_OMIT_VIRTUALTABLE
   72430   }else if( pC->pVtabCursor ){
   72431     pVtab = pC->pVtabCursor->pVtab;
   72432     pModule = pVtab->pModule;
   72433     assert( pModule->xRowid );
   72434     rc = pModule->xRowid(pC->pVtabCursor, &v);
   72435     sqlite3VtabImportErrmsg(p, pVtab);
   72436 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   72437   }else{
   72438     assert( pC->pCursor!=0 );
   72439     rc = sqlite3VdbeCursorMoveto(pC);
   72440     if( rc ) goto abort_due_to_error;
   72441     if( pC->rowidIsValid ){
   72442       v = pC->lastRowid;
   72443     }else{
   72444       rc = sqlite3BtreeKeySize(pC->pCursor, &v);
   72445       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
   72446     }
   72447   }
   72448   pOut->u.i = v;
   72449   break;
   72450 }
   72451 
   72452 /* Opcode: NullRow P1 * * * *
   72453 **
   72454 ** Move the cursor P1 to a null row.  Any OP_Column operations
   72455 ** that occur while the cursor is on the null row will always
   72456 ** write a NULL.
   72457 */
   72458 case OP_NullRow: {
   72459   VdbeCursor *pC;
   72460 
   72461   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72462   pC = p->apCsr[pOp->p1];
   72463   assert( pC!=0 );
   72464   pC->nullRow = 1;
   72465   pC->rowidIsValid = 0;
   72466   pC->cacheStatus = CACHE_STALE;
   72467   if( pC->pCursor ){
   72468     sqlite3BtreeClearCursor(pC->pCursor);
   72469   }
   72470   break;
   72471 }
   72472 
   72473 /* Opcode: Last P1 P2 * * *
   72474 **
   72475 ** The next use of the Rowid or Column or Prev instruction for P1
   72476 ** will refer to the last entry in the database table or index.
   72477 ** If the table or index is empty and P2>0, then jump immediately to P2.
   72478 ** If P2 is 0 or if the table or index is not empty, fall through
   72479 ** to the following instruction.
   72480 **
   72481 ** This opcode leaves the cursor configured to move in reverse order,
   72482 ** from the end toward the beginning.  In other words, the cursor is
   72483 ** configured to use Prev, not Next.
   72484 */
   72485 case OP_Last: {        /* jump */
   72486   VdbeCursor *pC;
   72487   BtCursor *pCrsr;
   72488   int res;
   72489 
   72490   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72491   pC = p->apCsr[pOp->p1];
   72492   assert( pC!=0 );
   72493   pCrsr = pC->pCursor;
   72494   res = 0;
   72495   assert( pCrsr!=0 );
   72496   rc = sqlite3BtreeLast(pCrsr, &res);
   72497   pC->nullRow = (u8)res;
   72498   pC->deferredMoveto = 0;
   72499   pC->rowidIsValid = 0;
   72500   pC->cacheStatus = CACHE_STALE;
   72501 #ifdef SQLITE_DEBUG
   72502   pC->seekOp = OP_Last;
   72503 #endif
   72504   if( pOp->p2>0 ){
   72505     VdbeBranchTaken(res!=0,2);
   72506     if( res ) pc = pOp->p2 - 1;
   72507   }
   72508   break;
   72509 }
   72510 
   72511 
   72512 /* Opcode: Sort P1 P2 * * *
   72513 **
   72514 ** This opcode does exactly the same thing as OP_Rewind except that
   72515 ** it increments an undocumented global variable used for testing.
   72516 **
   72517 ** Sorting is accomplished by writing records into a sorting index,
   72518 ** then rewinding that index and playing it back from beginning to
   72519 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
   72520 ** rewinding so that the global variable will be incremented and
   72521 ** regression tests can determine whether or not the optimizer is
   72522 ** correctly optimizing out sorts.
   72523 */
   72524 case OP_SorterSort:    /* jump */
   72525 case OP_Sort: {        /* jump */
   72526 #ifdef SQLITE_TEST
   72527   sqlite3_sort_count++;
   72528   sqlite3_search_count--;
   72529 #endif
   72530   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
   72531   /* Fall through into OP_Rewind */
   72532 }
   72533 /* Opcode: Rewind P1 P2 * * *
   72534 **
   72535 ** The next use of the Rowid or Column or Next instruction for P1
   72536 ** will refer to the first entry in the database table or index.
   72537 ** If the table or index is empty and P2>0, then jump immediately to P2.
   72538 ** If P2 is 0 or if the table or index is not empty, fall through
   72539 ** to the following instruction.
   72540 **
   72541 ** This opcode leaves the cursor configured to move in forward order,
   72542 ** from the beginning toward the end.  In other words, the cursor is
   72543 ** configured to use Next, not Prev.
   72544 */
   72545 case OP_Rewind: {        /* jump */
   72546   VdbeCursor *pC;
   72547   BtCursor *pCrsr;
   72548   int res;
   72549 
   72550   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72551   pC = p->apCsr[pOp->p1];
   72552   assert( pC!=0 );
   72553   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
   72554   res = 1;
   72555 #ifdef SQLITE_DEBUG
   72556   pC->seekOp = OP_Rewind;
   72557 #endif
   72558   if( isSorter(pC) ){
   72559     rc = sqlite3VdbeSorterRewind(db, pC, &res);
   72560   }else{
   72561     pCrsr = pC->pCursor;
   72562     assert( pCrsr );
   72563     rc = sqlite3BtreeFirst(pCrsr, &res);
   72564     pC->deferredMoveto = 0;
   72565     pC->cacheStatus = CACHE_STALE;
   72566     pC->rowidIsValid = 0;
   72567   }
   72568   pC->nullRow = (u8)res;
   72569   assert( pOp->p2>0 && pOp->p2<p->nOp );
   72570   VdbeBranchTaken(res!=0,2);
   72571   if( res ){
   72572     pc = pOp->p2 - 1;
   72573   }
   72574   break;
   72575 }
   72576 
   72577 /* Opcode: Next P1 P2 P3 P4 P5
   72578 **
   72579 ** Advance cursor P1 so that it points to the next key/data pair in its
   72580 ** table or index.  If there are no more key/value pairs then fall through
   72581 ** to the following instruction.  But if the cursor advance was successful,
   72582 ** jump immediately to P2.
   72583 **
   72584 ** The Next opcode is only valid following an SeekGT, SeekGE, or
   72585 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
   72586 ** to follow SeekLT, SeekLE, or OP_Last.
   72587 **
   72588 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
   72589 ** been opened prior to this opcode or the program will segfault.
   72590 **
   72591 ** The P3 value is a hint to the btree implementation. If P3==1, that
   72592 ** means P1 is an SQL index and that this instruction could have been
   72593 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
   72594 ** always either 0 or 1.
   72595 **
   72596 ** P4 is always of type P4_ADVANCE. The function pointer points to
   72597 ** sqlite3BtreeNext().
   72598 **
   72599 ** If P5 is positive and the jump is taken, then event counter
   72600 ** number P5-1 in the prepared statement is incremented.
   72601 **
   72602 ** See also: Prev, NextIfOpen
   72603 */
   72604 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
   72605 **
   72606 ** This opcode works just like Next except that if cursor P1 is not
   72607 ** open it behaves a no-op.
   72608 */
   72609 /* Opcode: Prev P1 P2 P3 P4 P5
   72610 **
   72611 ** Back up cursor P1 so that it points to the previous key/data pair in its
   72612 ** table or index.  If there is no previous key/value pairs then fall through
   72613 ** to the following instruction.  But if the cursor backup was successful,
   72614 ** jump immediately to P2.
   72615 **
   72616 **
   72617 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
   72618 ** OP_Last opcode used to position the cursor.  Prev is not allowed
   72619 ** to follow SeekGT, SeekGE, or OP_Rewind.
   72620 **
   72621 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
   72622 ** not open then the behavior is undefined.
   72623 **
   72624 ** The P3 value is a hint to the btree implementation. If P3==1, that
   72625 ** means P1 is an SQL index and that this instruction could have been
   72626 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
   72627 ** always either 0 or 1.
   72628 **
   72629 ** P4 is always of type P4_ADVANCE. The function pointer points to
   72630 ** sqlite3BtreePrevious().
   72631 **
   72632 ** If P5 is positive and the jump is taken, then event counter
   72633 ** number P5-1 in the prepared statement is incremented.
   72634 */
   72635 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
   72636 **
   72637 ** This opcode works just like Prev except that if cursor P1 is not
   72638 ** open it behaves a no-op.
   72639 */
   72640 case OP_SorterNext: {  /* jump */
   72641   VdbeCursor *pC;
   72642   int res;
   72643 
   72644   pC = p->apCsr[pOp->p1];
   72645   assert( isSorter(pC) );
   72646   res = 0;
   72647   rc = sqlite3VdbeSorterNext(db, pC, &res);
   72648   goto next_tail;
   72649 case OP_PrevIfOpen:    /* jump */
   72650 case OP_NextIfOpen:    /* jump */
   72651   if( p->apCsr[pOp->p1]==0 ) break;
   72652   /* Fall through */
   72653 case OP_Prev:          /* jump */
   72654 case OP_Next:          /* jump */
   72655   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72656   assert( pOp->p5<ArraySize(p->aCounter) );
   72657   pC = p->apCsr[pOp->p1];
   72658   res = pOp->p3;
   72659   assert( pC!=0 );
   72660   assert( pC->deferredMoveto==0 );
   72661   assert( pC->pCursor );
   72662   assert( res==0 || (res==1 && pC->isTable==0) );
   72663   testcase( res==1 );
   72664   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
   72665   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
   72666   assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
   72667   assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
   72668 
   72669   /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
   72670   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
   72671   assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
   72672        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
   72673        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
   72674   assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
   72675        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
   72676        || pC->seekOp==OP_Last );
   72677 
   72678   rc = pOp->p4.xAdvance(pC->pCursor, &res);
   72679 next_tail:
   72680   pC->cacheStatus = CACHE_STALE;
   72681   VdbeBranchTaken(res==0,2);
   72682   if( res==0 ){
   72683     pC->nullRow = 0;
   72684     pc = pOp->p2 - 1;
   72685     p->aCounter[pOp->p5]++;
   72686 #ifdef SQLITE_TEST
   72687     sqlite3_search_count++;
   72688 #endif
   72689   }else{
   72690     pC->nullRow = 1;
   72691   }
   72692   pC->rowidIsValid = 0;
   72693   goto check_for_interrupt;
   72694 }
   72695 
   72696 /* Opcode: IdxInsert P1 P2 P3 * P5
   72697 ** Synopsis: key=r[P2]
   72698 **
   72699 ** Register P2 holds an SQL index key made using the
   72700 ** MakeRecord instructions.  This opcode writes that key
   72701 ** into the index P1.  Data for the entry is nil.
   72702 **
   72703 ** P3 is a flag that provides a hint to the b-tree layer that this
   72704 ** insert is likely to be an append.
   72705 **
   72706 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
   72707 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
   72708 ** then the change counter is unchanged.
   72709 **
   72710 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
   72711 ** just done a seek to the spot where the new entry is to be inserted.
   72712 ** This flag avoids doing an extra seek.
   72713 **
   72714 ** This instruction only works for indices.  The equivalent instruction
   72715 ** for tables is OP_Insert.
   72716 */
   72717 case OP_SorterInsert:       /* in2 */
   72718 case OP_IdxInsert: {        /* in2 */
   72719   VdbeCursor *pC;
   72720   BtCursor *pCrsr;
   72721   int nKey;
   72722   const char *zKey;
   72723 
   72724   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72725   pC = p->apCsr[pOp->p1];
   72726   assert( pC!=0 );
   72727   assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
   72728   pIn2 = &aMem[pOp->p2];
   72729   assert( pIn2->flags & MEM_Blob );
   72730   pCrsr = pC->pCursor;
   72731   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   72732   assert( pCrsr!=0 );
   72733   assert( pC->isTable==0 );
   72734   rc = ExpandBlob(pIn2);
   72735   if( rc==SQLITE_OK ){
   72736     if( isSorter(pC) ){
   72737       rc = sqlite3VdbeSorterWrite(db, pC, pIn2);
   72738     }else{
   72739       nKey = pIn2->n;
   72740       zKey = pIn2->z;
   72741       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
   72742           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
   72743           );
   72744       assert( pC->deferredMoveto==0 );
   72745       pC->cacheStatus = CACHE_STALE;
   72746     }
   72747   }
   72748   break;
   72749 }
   72750 
   72751 /* Opcode: IdxDelete P1 P2 P3 * *
   72752 ** Synopsis: key=r[P2@P3]
   72753 **
   72754 ** The content of P3 registers starting at register P2 form
   72755 ** an unpacked index key. This opcode removes that entry from the
   72756 ** index opened by cursor P1.
   72757 */
   72758 case OP_IdxDelete: {
   72759   VdbeCursor *pC;
   72760   BtCursor *pCrsr;
   72761   int res;
   72762   UnpackedRecord r;
   72763 
   72764   assert( pOp->p3>0 );
   72765   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
   72766   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72767   pC = p->apCsr[pOp->p1];
   72768   assert( pC!=0 );
   72769   pCrsr = pC->pCursor;
   72770   assert( pCrsr!=0 );
   72771   assert( pOp->p5==0 );
   72772   r.pKeyInfo = pC->pKeyInfo;
   72773   r.nField = (u16)pOp->p3;
   72774   r.default_rc = 0;
   72775   r.aMem = &aMem[pOp->p2];
   72776 #ifdef SQLITE_DEBUG
   72777   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
   72778 #endif
   72779   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
   72780   if( rc==SQLITE_OK && res==0 ){
   72781     rc = sqlite3BtreeDelete(pCrsr);
   72782   }
   72783   assert( pC->deferredMoveto==0 );
   72784   pC->cacheStatus = CACHE_STALE;
   72785   break;
   72786 }
   72787 
   72788 /* Opcode: IdxRowid P1 P2 * * *
   72789 ** Synopsis: r[P2]=rowid
   72790 **
   72791 ** Write into register P2 an integer which is the last entry in the record at
   72792 ** the end of the index key pointed to by cursor P1.  This integer should be
   72793 ** the rowid of the table entry to which this index entry points.
   72794 **
   72795 ** See also: Rowid, MakeRecord.
   72796 */
   72797 case OP_IdxRowid: {              /* out2-prerelease */
   72798   BtCursor *pCrsr;
   72799   VdbeCursor *pC;
   72800   i64 rowid;
   72801 
   72802   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72803   pC = p->apCsr[pOp->p1];
   72804   assert( pC!=0 );
   72805   pCrsr = pC->pCursor;
   72806   assert( pCrsr!=0 );
   72807   pOut->flags = MEM_Null;
   72808   rc = sqlite3VdbeCursorMoveto(pC);
   72809   if( NEVER(rc) ) goto abort_due_to_error;
   72810   assert( pC->deferredMoveto==0 );
   72811   assert( pC->isTable==0 );
   72812   if( !pC->nullRow ){
   72813     rowid = 0;  /* Not needed.  Only used to silence a warning. */
   72814     rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
   72815     if( rc!=SQLITE_OK ){
   72816       goto abort_due_to_error;
   72817     }
   72818     pOut->u.i = rowid;
   72819     pOut->flags = MEM_Int;
   72820   }
   72821   break;
   72822 }
   72823 
   72824 /* Opcode: IdxGE P1 P2 P3 P4 P5
   72825 ** Synopsis: key=r[P3@P4]
   72826 **
   72827 ** The P4 register values beginning with P3 form an unpacked index
   72828 ** key that omits the PRIMARY KEY.  Compare this key value against the index
   72829 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
   72830 ** fields at the end.
   72831 **
   72832 ** If the P1 index entry is greater than or equal to the key value
   72833 ** then jump to P2.  Otherwise fall through to the next instruction.
   72834 */
   72835 /* Opcode: IdxGT P1 P2 P3 P4 P5
   72836 ** Synopsis: key=r[P3@P4]
   72837 **
   72838 ** The P4 register values beginning with P3 form an unpacked index
   72839 ** key that omits the PRIMARY KEY.  Compare this key value against the index
   72840 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
   72841 ** fields at the end.
   72842 **
   72843 ** If the P1 index entry is greater than the key value
   72844 ** then jump to P2.  Otherwise fall through to the next instruction.
   72845 */
   72846 /* Opcode: IdxLT P1 P2 P3 P4 P5
   72847 ** Synopsis: key=r[P3@P4]
   72848 **
   72849 ** The P4 register values beginning with P3 form an unpacked index
   72850 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
   72851 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
   72852 ** ROWID on the P1 index.
   72853 **
   72854 ** If the P1 index entry is less than the key value then jump to P2.
   72855 ** Otherwise fall through to the next instruction.
   72856 */
   72857 /* Opcode: IdxLE P1 P2 P3 P4 P5
   72858 ** Synopsis: key=r[P3@P4]
   72859 **
   72860 ** The P4 register values beginning with P3 form an unpacked index
   72861 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
   72862 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
   72863 ** ROWID on the P1 index.
   72864 **
   72865 ** If the P1 index entry is less than or equal to the key value then jump
   72866 ** to P2. Otherwise fall through to the next instruction.
   72867 */
   72868 case OP_IdxLE:          /* jump */
   72869 case OP_IdxGT:          /* jump */
   72870 case OP_IdxLT:          /* jump */
   72871 case OP_IdxGE:  {       /* jump */
   72872   VdbeCursor *pC;
   72873   int res;
   72874   UnpackedRecord r;
   72875 
   72876   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   72877   pC = p->apCsr[pOp->p1];
   72878   assert( pC!=0 );
   72879   assert( pC->isOrdered );
   72880   assert( pC->pCursor!=0);
   72881   assert( pC->deferredMoveto==0 );
   72882   assert( pOp->p5==0 || pOp->p5==1 );
   72883   assert( pOp->p4type==P4_INT32 );
   72884   r.pKeyInfo = pC->pKeyInfo;
   72885   r.nField = (u16)pOp->p4.i;
   72886   if( pOp->opcode<OP_IdxLT ){
   72887     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
   72888     r.default_rc = -1;
   72889   }else{
   72890     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
   72891     r.default_rc = 0;
   72892   }
   72893   r.aMem = &aMem[pOp->p3];
   72894 #ifdef SQLITE_DEBUG
   72895   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
   72896 #endif
   72897   res = 0;  /* Not needed.  Only used to silence a warning. */
   72898   rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
   72899   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
   72900   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
   72901     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
   72902     res = -res;
   72903   }else{
   72904     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
   72905     res++;
   72906   }
   72907   VdbeBranchTaken(res>0,2);
   72908   if( res>0 ){
   72909     pc = pOp->p2 - 1 ;
   72910   }
   72911   break;
   72912 }
   72913 
   72914 /* Opcode: Destroy P1 P2 P3 * *
   72915 **
   72916 ** Delete an entire database table or index whose root page in the database
   72917 ** file is given by P1.
   72918 **
   72919 ** The table being destroyed is in the main database file if P3==0.  If
   72920 ** P3==1 then the table to be clear is in the auxiliary database file
   72921 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   72922 **
   72923 ** If AUTOVACUUM is enabled then it is possible that another root page
   72924 ** might be moved into the newly deleted root page in order to keep all
   72925 ** root pages contiguous at the beginning of the database.  The former
   72926 ** value of the root page that moved - its value before the move occurred -
   72927 ** is stored in register P2.  If no page
   72928 ** movement was required (because the table being dropped was already
   72929 ** the last one in the database) then a zero is stored in register P2.
   72930 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
   72931 **
   72932 ** See also: Clear
   72933 */
   72934 case OP_Destroy: {     /* out2-prerelease */
   72935   int iMoved;
   72936   int iCnt;
   72937   Vdbe *pVdbe;
   72938   int iDb;
   72939 
   72940   assert( p->readOnly==0 );
   72941 #ifndef SQLITE_OMIT_VIRTUALTABLE
   72942   iCnt = 0;
   72943   for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
   72944     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
   72945      && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
   72946     ){
   72947       iCnt++;
   72948     }
   72949   }
   72950 #else
   72951   iCnt = db->nVdbeRead;
   72952 #endif
   72953   pOut->flags = MEM_Null;
   72954   if( iCnt>1 ){
   72955     rc = SQLITE_LOCKED;
   72956     p->errorAction = OE_Abort;
   72957   }else{
   72958     iDb = pOp->p3;
   72959     assert( iCnt==1 );
   72960     assert( DbMaskTest(p->btreeMask, iDb) );
   72961     iMoved = 0;  /* Not needed.  Only to silence a warning. */
   72962     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
   72963     pOut->flags = MEM_Int;
   72964     pOut->u.i = iMoved;
   72965 #ifndef SQLITE_OMIT_AUTOVACUUM
   72966     if( rc==SQLITE_OK && iMoved!=0 ){
   72967       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
   72968       /* All OP_Destroy operations occur on the same btree */
   72969       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
   72970       resetSchemaOnFault = iDb+1;
   72971     }
   72972 #endif
   72973   }
   72974   break;
   72975 }
   72976 
   72977 /* Opcode: Clear P1 P2 P3
   72978 **
   72979 ** Delete all contents of the database table or index whose root page
   72980 ** in the database file is given by P1.  But, unlike Destroy, do not
   72981 ** remove the table or index from the database file.
   72982 **
   72983 ** The table being clear is in the main database file if P2==0.  If
   72984 ** P2==1 then the table to be clear is in the auxiliary database file
   72985 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   72986 **
   72987 ** If the P3 value is non-zero, then the table referred to must be an
   72988 ** intkey table (an SQL table, not an index). In this case the row change
   72989 ** count is incremented by the number of rows in the table being cleared.
   72990 ** If P3 is greater than zero, then the value stored in register P3 is
   72991 ** also incremented by the number of rows in the table being cleared.
   72992 **
   72993 ** See also: Destroy
   72994 */
   72995 case OP_Clear: {
   72996   int nChange;
   72997 
   72998   nChange = 0;
   72999   assert( p->readOnly==0 );
   73000   assert( DbMaskTest(p->btreeMask, pOp->p2) );
   73001   rc = sqlite3BtreeClearTable(
   73002       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
   73003   );
   73004   if( pOp->p3 ){
   73005     p->nChange += nChange;
   73006     if( pOp->p3>0 ){
   73007       assert( memIsValid(&aMem[pOp->p3]) );
   73008       memAboutToChange(p, &aMem[pOp->p3]);
   73009       aMem[pOp->p3].u.i += nChange;
   73010     }
   73011   }
   73012   break;
   73013 }
   73014 
   73015 /* Opcode: ResetSorter P1 * * * *
   73016 **
   73017 ** Delete all contents from the ephemeral table or sorter
   73018 ** that is open on cursor P1.
   73019 **
   73020 ** This opcode only works for cursors used for sorting and
   73021 ** opened with OP_OpenEphemeral or OP_SorterOpen.
   73022 */
   73023 case OP_ResetSorter: {
   73024   VdbeCursor *pC;
   73025 
   73026   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   73027   pC = p->apCsr[pOp->p1];
   73028   assert( pC!=0 );
   73029   if( pC->pSorter ){
   73030     sqlite3VdbeSorterReset(db, pC->pSorter);
   73031   }else{
   73032     assert( pC->isEphemeral );
   73033     rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
   73034   }
   73035   break;
   73036 }
   73037 
   73038 /* Opcode: CreateTable P1 P2 * * *
   73039 ** Synopsis: r[P2]=root iDb=P1
   73040 **
   73041 ** Allocate a new table in the main database file if P1==0 or in the
   73042 ** auxiliary database file if P1==1 or in an attached database if
   73043 ** P1>1.  Write the root page number of the new table into
   73044 ** register P2
   73045 **
   73046 ** The difference between a table and an index is this:  A table must
   73047 ** have a 4-byte integer key and can have arbitrary data.  An index
   73048 ** has an arbitrary key but no data.
   73049 **
   73050 ** See also: CreateIndex
   73051 */
   73052 /* Opcode: CreateIndex P1 P2 * * *
   73053 ** Synopsis: r[P2]=root iDb=P1
   73054 **
   73055 ** Allocate a new index in the main database file if P1==0 or in the
   73056 ** auxiliary database file if P1==1 or in an attached database if
   73057 ** P1>1.  Write the root page number of the new table into
   73058 ** register P2.
   73059 **
   73060 ** See documentation on OP_CreateTable for additional information.
   73061 */
   73062 case OP_CreateIndex:            /* out2-prerelease */
   73063 case OP_CreateTable: {          /* out2-prerelease */
   73064   int pgno;
   73065   int flags;
   73066   Db *pDb;
   73067 
   73068   pgno = 0;
   73069   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   73070   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   73071   assert( p->readOnly==0 );
   73072   pDb = &db->aDb[pOp->p1];
   73073   assert( pDb->pBt!=0 );
   73074   if( pOp->opcode==OP_CreateTable ){
   73075     /* flags = BTREE_INTKEY; */
   73076     flags = BTREE_INTKEY;
   73077   }else{
   73078     flags = BTREE_BLOBKEY;
   73079   }
   73080   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
   73081   pOut->u.i = pgno;
   73082   break;
   73083 }
   73084 
   73085 /* Opcode: ParseSchema P1 * * P4 *
   73086 **
   73087 ** Read and parse all entries from the SQLITE_MASTER table of database P1
   73088 ** that match the WHERE clause P4.
   73089 **
   73090 ** This opcode invokes the parser to create a new virtual machine,
   73091 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
   73092 */
   73093 case OP_ParseSchema: {
   73094   int iDb;
   73095   const char *zMaster;
   73096   char *zSql;
   73097   InitData initData;
   73098 
   73099   /* Any prepared statement that invokes this opcode will hold mutexes
   73100   ** on every btree.  This is a prerequisite for invoking
   73101   ** sqlite3InitCallback().
   73102   */
   73103 #ifdef SQLITE_DEBUG
   73104   for(iDb=0; iDb<db->nDb; iDb++){
   73105     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   73106   }
   73107 #endif
   73108 
   73109   iDb = pOp->p1;
   73110   assert( iDb>=0 && iDb<db->nDb );
   73111   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
   73112   /* Used to be a conditional */ {
   73113     zMaster = SCHEMA_TABLE(iDb);
   73114     initData.db = db;
   73115     initData.iDb = pOp->p1;
   73116     initData.pzErrMsg = &p->zErrMsg;
   73117     zSql = sqlite3MPrintf(db,
   73118        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
   73119        db->aDb[iDb].zName, zMaster, pOp->p4.z);
   73120     if( zSql==0 ){
   73121       rc = SQLITE_NOMEM;
   73122     }else{
   73123       assert( db->init.busy==0 );
   73124       db->init.busy = 1;
   73125       initData.rc = SQLITE_OK;
   73126       assert( !db->mallocFailed );
   73127       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   73128       if( rc==SQLITE_OK ) rc = initData.rc;
   73129       sqlite3DbFree(db, zSql);
   73130       db->init.busy = 0;
   73131     }
   73132   }
   73133   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
   73134   if( rc==SQLITE_NOMEM ){
   73135     goto no_mem;
   73136   }
   73137   break;
   73138 }
   73139 
   73140 #if !defined(SQLITE_OMIT_ANALYZE)
   73141 /* Opcode: LoadAnalysis P1 * * * *
   73142 **
   73143 ** Read the sqlite_stat1 table for database P1 and load the content
   73144 ** of that table into the internal index hash table.  This will cause
   73145 ** the analysis to be used when preparing all subsequent queries.
   73146 */
   73147 case OP_LoadAnalysis: {
   73148   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   73149   rc = sqlite3AnalysisLoad(db, pOp->p1);
   73150   break;
   73151 }
   73152 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
   73153 
   73154 /* Opcode: DropTable P1 * * P4 *
   73155 **
   73156 ** Remove the internal (in-memory) data structures that describe
   73157 ** the table named P4 in database P1.  This is called after a table
   73158 ** is dropped from disk (using the Destroy opcode) in order to keep
   73159 ** the internal representation of the
   73160 ** schema consistent with what is on disk.
   73161 */
   73162 case OP_DropTable: {
   73163   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
   73164   break;
   73165 }
   73166 
   73167 /* Opcode: DropIndex P1 * * P4 *
   73168 **
   73169 ** Remove the internal (in-memory) data structures that describe
   73170 ** the index named P4 in database P1.  This is called after an index
   73171 ** is dropped from disk (using the Destroy opcode)
   73172 ** in order to keep the internal representation of the
   73173 ** schema consistent with what is on disk.
   73174 */
   73175 case OP_DropIndex: {
   73176   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
   73177   break;
   73178 }
   73179 
   73180 /* Opcode: DropTrigger P1 * * P4 *
   73181 **
   73182 ** Remove the internal (in-memory) data structures that describe
   73183 ** the trigger named P4 in database P1.  This is called after a trigger
   73184 ** is dropped from disk (using the Destroy opcode) in order to keep
   73185 ** the internal representation of the
   73186 ** schema consistent with what is on disk.
   73187 */
   73188 case OP_DropTrigger: {
   73189   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
   73190   break;
   73191 }
   73192 
   73193 
   73194 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   73195 /* Opcode: IntegrityCk P1 P2 P3 * P5
   73196 **
   73197 ** Do an analysis of the currently open database.  Store in
   73198 ** register P1 the text of an error message describing any problems.
   73199 ** If no problems are found, store a NULL in register P1.
   73200 **
   73201 ** The register P3 contains the maximum number of allowed errors.
   73202 ** At most reg(P3) errors will be reported.
   73203 ** In other words, the analysis stops as soon as reg(P1) errors are
   73204 ** seen.  Reg(P1) is updated with the number of errors remaining.
   73205 **
   73206 ** The root page numbers of all tables in the database are integer
   73207 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
   73208 ** total.
   73209 **
   73210 ** If P5 is not zero, the check is done on the auxiliary database
   73211 ** file, not the main database file.
   73212 **
   73213 ** This opcode is used to implement the integrity_check pragma.
   73214 */
   73215 case OP_IntegrityCk: {
   73216   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   73217   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   73218   int j;          /* Loop counter */
   73219   int nErr;       /* Number of errors reported */
   73220   char *z;        /* Text of the error report */
   73221   Mem *pnErr;     /* Register keeping track of errors remaining */
   73222 
   73223   assert( p->bIsReader );
   73224   nRoot = pOp->p2;
   73225   assert( nRoot>0 );
   73226   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
   73227   if( aRoot==0 ) goto no_mem;
   73228   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   73229   pnErr = &aMem[pOp->p3];
   73230   assert( (pnErr->flags & MEM_Int)!=0 );
   73231   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
   73232   pIn1 = &aMem[pOp->p1];
   73233   for(j=0; j<nRoot; j++){
   73234     aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
   73235   }
   73236   aRoot[j] = 0;
   73237   assert( pOp->p5<db->nDb );
   73238   assert( DbMaskTest(p->btreeMask, pOp->p5) );
   73239   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
   73240                                  (int)pnErr->u.i, &nErr);
   73241   sqlite3DbFree(db, aRoot);
   73242   pnErr->u.i -= nErr;
   73243   sqlite3VdbeMemSetNull(pIn1);
   73244   if( nErr==0 ){
   73245     assert( z==0 );
   73246   }else if( z==0 ){
   73247     goto no_mem;
   73248   }else{
   73249     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
   73250   }
   73251   UPDATE_MAX_BLOBSIZE(pIn1);
   73252   sqlite3VdbeChangeEncoding(pIn1, encoding);
   73253   break;
   73254 }
   73255 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   73256 
   73257 /* Opcode: RowSetAdd P1 P2 * * *
   73258 ** Synopsis:  rowset(P1)=r[P2]
   73259 **
   73260 ** Insert the integer value held by register P2 into a boolean index
   73261 ** held in register P1.
   73262 **
   73263 ** An assertion fails if P2 is not an integer.
   73264 */
   73265 case OP_RowSetAdd: {       /* in1, in2 */
   73266   pIn1 = &aMem[pOp->p1];
   73267   pIn2 = &aMem[pOp->p2];
   73268   assert( (pIn2->flags & MEM_Int)!=0 );
   73269   if( (pIn1->flags & MEM_RowSet)==0 ){
   73270     sqlite3VdbeMemSetRowSet(pIn1);
   73271     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   73272   }
   73273   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
   73274   break;
   73275 }
   73276 
   73277 /* Opcode: RowSetRead P1 P2 P3 * *
   73278 ** Synopsis:  r[P3]=rowset(P1)
   73279 **
   73280 ** Extract the smallest value from boolean index P1 and put that value into
   73281 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
   73282 ** unchanged and jump to instruction P2.
   73283 */
   73284 case OP_RowSetRead: {       /* jump, in1, out3 */
   73285   i64 val;
   73286 
   73287   pIn1 = &aMem[pOp->p1];
   73288   if( (pIn1->flags & MEM_RowSet)==0
   73289    || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
   73290   ){
   73291     /* The boolean index is empty */
   73292     sqlite3VdbeMemSetNull(pIn1);
   73293     pc = pOp->p2 - 1;
   73294     VdbeBranchTaken(1,2);
   73295   }else{
   73296     /* A value was pulled from the index */
   73297     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
   73298     VdbeBranchTaken(0,2);
   73299   }
   73300   goto check_for_interrupt;
   73301 }
   73302 
   73303 /* Opcode: RowSetTest P1 P2 P3 P4
   73304 ** Synopsis: if r[P3] in rowset(P1) goto P2
   73305 **
   73306 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
   73307 ** contains a RowSet object and that RowSet object contains
   73308 ** the value held in P3, jump to register P2. Otherwise, insert the
   73309 ** integer in P3 into the RowSet and continue on to the
   73310 ** next opcode.
   73311 **
   73312 ** The RowSet object is optimized for the case where successive sets
   73313 ** of integers, where each set contains no duplicates. Each set
   73314 ** of values is identified by a unique P4 value. The first set
   73315 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
   73316 ** non-negative.  For non-negative values of P4 only the lower 4
   73317 ** bits are significant.
   73318 **
   73319 ** This allows optimizations: (a) when P4==0 there is no need to test
   73320 ** the rowset object for P3, as it is guaranteed not to contain it,
   73321 ** (b) when P4==-1 there is no need to insert the value, as it will
   73322 ** never be tested for, and (c) when a value that is part of set X is
   73323 ** inserted, there is no need to search to see if the same value was
   73324 ** previously inserted as part of set X (only if it was previously
   73325 ** inserted as part of some other set).
   73326 */
   73327 case OP_RowSetTest: {                     /* jump, in1, in3 */
   73328   int iSet;
   73329   int exists;
   73330 
   73331   pIn1 = &aMem[pOp->p1];
   73332   pIn3 = &aMem[pOp->p3];
   73333   iSet = pOp->p4.i;
   73334   assert( pIn3->flags&MEM_Int );
   73335 
   73336   /* If there is anything other than a rowset object in memory cell P1,
   73337   ** delete it now and initialize P1 with an empty rowset
   73338   */
   73339   if( (pIn1->flags & MEM_RowSet)==0 ){
   73340     sqlite3VdbeMemSetRowSet(pIn1);
   73341     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   73342   }
   73343 
   73344   assert( pOp->p4type==P4_INT32 );
   73345   assert( iSet==-1 || iSet>=0 );
   73346   if( iSet ){
   73347     exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
   73348     VdbeBranchTaken(exists!=0,2);
   73349     if( exists ){
   73350       pc = pOp->p2 - 1;
   73351       break;
   73352     }
   73353   }
   73354   if( iSet>=0 ){
   73355     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
   73356   }
   73357   break;
   73358 }
   73359 
   73360 
   73361 #ifndef SQLITE_OMIT_TRIGGER
   73362 
   73363 /* Opcode: Program P1 P2 P3 P4 P5
   73364 **
   73365 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
   73366 **
   73367 ** P1 contains the address of the memory cell that contains the first memory
   73368 ** cell in an array of values used as arguments to the sub-program. P2
   73369 ** contains the address to jump to if the sub-program throws an IGNORE
   73370 ** exception using the RAISE() function. Register P3 contains the address
   73371 ** of a memory cell in this (the parent) VM that is used to allocate the
   73372 ** memory required by the sub-vdbe at runtime.
   73373 **
   73374 ** P4 is a pointer to the VM containing the trigger program.
   73375 **
   73376 ** If P5 is non-zero, then recursive program invocation is enabled.
   73377 */
   73378 case OP_Program: {        /* jump */
   73379   int nMem;               /* Number of memory registers for sub-program */
   73380   int nByte;              /* Bytes of runtime space required for sub-program */
   73381   Mem *pRt;               /* Register to allocate runtime space */
   73382   Mem *pMem;              /* Used to iterate through memory cells */
   73383   Mem *pEnd;              /* Last memory cell in new array */
   73384   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   73385   SubProgram *pProgram;   /* Sub-program to execute */
   73386   void *t;                /* Token identifying trigger */
   73387 
   73388   pProgram = pOp->p4.pProgram;
   73389   pRt = &aMem[pOp->p3];
   73390   assert( pProgram->nOp>0 );
   73391 
   73392   /* If the p5 flag is clear, then recursive invocation of triggers is
   73393   ** disabled for backwards compatibility (p5 is set if this sub-program
   73394   ** is really a trigger, not a foreign key action, and the flag set
   73395   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
   73396   **
   73397   ** It is recursive invocation of triggers, at the SQL level, that is
   73398   ** disabled. In some cases a single trigger may generate more than one
   73399   ** SubProgram (if the trigger may be executed with more than one different
   73400   ** ON CONFLICT algorithm). SubProgram structures associated with a
   73401   ** single trigger all have the same value for the SubProgram.token
   73402   ** variable.  */
   73403   if( pOp->p5 ){
   73404     t = pProgram->token;
   73405     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
   73406     if( pFrame ) break;
   73407   }
   73408 
   73409   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
   73410     rc = SQLITE_ERROR;
   73411     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
   73412     break;
   73413   }
   73414 
   73415   /* Register pRt is used to store the memory required to save the state
   73416   ** of the current program, and the memory required at runtime to execute
   73417   ** the trigger program. If this trigger has been fired before, then pRt
   73418   ** is already allocated. Otherwise, it must be initialized.  */
   73419   if( (pRt->flags&MEM_Frame)==0 ){
   73420     /* SubProgram.nMem is set to the number of memory cells used by the
   73421     ** program stored in SubProgram.aOp. As well as these, one memory
   73422     ** cell is required for each cursor used by the program. Set local
   73423     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
   73424     */
   73425     nMem = pProgram->nMem + pProgram->nCsr;
   73426     nByte = ROUND8(sizeof(VdbeFrame))
   73427               + nMem * sizeof(Mem)
   73428               + pProgram->nCsr * sizeof(VdbeCursor *)
   73429               + pProgram->nOnce * sizeof(u8);
   73430     pFrame = sqlite3DbMallocZero(db, nByte);
   73431     if( !pFrame ){
   73432       goto no_mem;
   73433     }
   73434     sqlite3VdbeMemRelease(pRt);
   73435     pRt->flags = MEM_Frame;
   73436     pRt->u.pFrame = pFrame;
   73437 
   73438     pFrame->v = p;
   73439     pFrame->nChildMem = nMem;
   73440     pFrame->nChildCsr = pProgram->nCsr;
   73441     pFrame->pc = pc;
   73442     pFrame->aMem = p->aMem;
   73443     pFrame->nMem = p->nMem;
   73444     pFrame->apCsr = p->apCsr;
   73445     pFrame->nCursor = p->nCursor;
   73446     pFrame->aOp = p->aOp;
   73447     pFrame->nOp = p->nOp;
   73448     pFrame->token = pProgram->token;
   73449     pFrame->aOnceFlag = p->aOnceFlag;
   73450     pFrame->nOnceFlag = p->nOnceFlag;
   73451 
   73452     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
   73453     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
   73454       pMem->flags = MEM_Undefined;
   73455       pMem->db = db;
   73456     }
   73457   }else{
   73458     pFrame = pRt->u.pFrame;
   73459     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
   73460     assert( pProgram->nCsr==pFrame->nChildCsr );
   73461     assert( pc==pFrame->pc );
   73462   }
   73463 
   73464   p->nFrame++;
   73465   pFrame->pParent = p->pFrame;
   73466   pFrame->lastRowid = lastRowid;
   73467   pFrame->nChange = p->nChange;
   73468   p->nChange = 0;
   73469   p->pFrame = pFrame;
   73470   p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
   73471   p->nMem = pFrame->nChildMem;
   73472   p->nCursor = (u16)pFrame->nChildCsr;
   73473   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
   73474   p->aOp = aOp = pProgram->aOp;
   73475   p->nOp = pProgram->nOp;
   73476   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
   73477   p->nOnceFlag = pProgram->nOnce;
   73478   pc = -1;
   73479   memset(p->aOnceFlag, 0, p->nOnceFlag);
   73480 
   73481   break;
   73482 }
   73483 
   73484 /* Opcode: Param P1 P2 * * *
   73485 **
   73486 ** This opcode is only ever present in sub-programs called via the
   73487 ** OP_Program instruction. Copy a value currently stored in a memory
   73488 ** cell of the calling (parent) frame to cell P2 in the current frames
   73489 ** address space. This is used by trigger programs to access the new.*
   73490 ** and old.* values.
   73491 **
   73492 ** The address of the cell in the parent frame is determined by adding
   73493 ** the value of the P1 argument to the value of the P1 argument to the
   73494 ** calling OP_Program instruction.
   73495 */
   73496 case OP_Param: {           /* out2-prerelease */
   73497   VdbeFrame *pFrame;
   73498   Mem *pIn;
   73499   pFrame = p->pFrame;
   73500   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
   73501   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
   73502   break;
   73503 }
   73504 
   73505 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
   73506 
   73507 #ifndef SQLITE_OMIT_FOREIGN_KEY
   73508 /* Opcode: FkCounter P1 P2 * * *
   73509 ** Synopsis: fkctr[P1]+=P2
   73510 **
   73511 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
   73512 ** If P1 is non-zero, the database constraint counter is incremented
   73513 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
   73514 ** statement counter is incremented (immediate foreign key constraints).
   73515 */
   73516 case OP_FkCounter: {
   73517   if( db->flags & SQLITE_DeferFKs ){
   73518     db->nDeferredImmCons += pOp->p2;
   73519   }else if( pOp->p1 ){
   73520     db->nDeferredCons += pOp->p2;
   73521   }else{
   73522     p->nFkConstraint += pOp->p2;
   73523   }
   73524   break;
   73525 }
   73526 
   73527 /* Opcode: FkIfZero P1 P2 * * *
   73528 ** Synopsis: if fkctr[P1]==0 goto P2
   73529 **
   73530 ** This opcode tests if a foreign key constraint-counter is currently zero.
   73531 ** If so, jump to instruction P2. Otherwise, fall through to the next
   73532 ** instruction.
   73533 **
   73534 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
   73535 ** is zero (the one that counts deferred constraint violations). If P1 is
   73536 ** zero, the jump is taken if the statement constraint-counter is zero
   73537 ** (immediate foreign key constraint violations).
   73538 */
   73539 case OP_FkIfZero: {         /* jump */
   73540   if( pOp->p1 ){
   73541     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
   73542     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
   73543   }else{
   73544     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
   73545     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
   73546   }
   73547   break;
   73548 }
   73549 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
   73550 
   73551 #ifndef SQLITE_OMIT_AUTOINCREMENT
   73552 /* Opcode: MemMax P1 P2 * * *
   73553 ** Synopsis: r[P1]=max(r[P1],r[P2])
   73554 **
   73555 ** P1 is a register in the root frame of this VM (the root frame is
   73556 ** different from the current frame if this instruction is being executed
   73557 ** within a sub-program). Set the value of register P1 to the maximum of
   73558 ** its current value and the value in register P2.
   73559 **
   73560 ** This instruction throws an error if the memory cell is not initially
   73561 ** an integer.
   73562 */
   73563 case OP_MemMax: {        /* in2 */
   73564   VdbeFrame *pFrame;
   73565   if( p->pFrame ){
   73566     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   73567     pIn1 = &pFrame->aMem[pOp->p1];
   73568   }else{
   73569     pIn1 = &aMem[pOp->p1];
   73570   }
   73571   assert( memIsValid(pIn1) );
   73572   sqlite3VdbeMemIntegerify(pIn1);
   73573   pIn2 = &aMem[pOp->p2];
   73574   sqlite3VdbeMemIntegerify(pIn2);
   73575   if( pIn1->u.i<pIn2->u.i){
   73576     pIn1->u.i = pIn2->u.i;
   73577   }
   73578   break;
   73579 }
   73580 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   73581 
   73582 /* Opcode: IfPos P1 P2 * * *
   73583 ** Synopsis: if r[P1]>0 goto P2
   73584 **
   73585 ** If the value of register P1 is 1 or greater, jump to P2.
   73586 **
   73587 ** It is illegal to use this instruction on a register that does
   73588 ** not contain an integer.  An assertion fault will result if you try.
   73589 */
   73590 case OP_IfPos: {        /* jump, in1 */
   73591   pIn1 = &aMem[pOp->p1];
   73592   assert( pIn1->flags&MEM_Int );
   73593   VdbeBranchTaken( pIn1->u.i>0, 2);
   73594   if( pIn1->u.i>0 ){
   73595      pc = pOp->p2 - 1;
   73596   }
   73597   break;
   73598 }
   73599 
   73600 /* Opcode: IfNeg P1 P2 P3 * *
   73601 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
   73602 **
   73603 ** Register P1 must contain an integer.  Add literal P3 to the value in
   73604 ** register P1 then if the value of register P1 is less than zero, jump to P2.
   73605 */
   73606 case OP_IfNeg: {        /* jump, in1 */
   73607   pIn1 = &aMem[pOp->p1];
   73608   assert( pIn1->flags&MEM_Int );
   73609   pIn1->u.i += pOp->p3;
   73610   VdbeBranchTaken(pIn1->u.i<0, 2);
   73611   if( pIn1->u.i<0 ){
   73612      pc = pOp->p2 - 1;
   73613   }
   73614   break;
   73615 }
   73616 
   73617 /* Opcode: IfZero P1 P2 P3 * *
   73618 ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
   73619 **
   73620 ** The register P1 must contain an integer.  Add literal P3 to the
   73621 ** value in register P1.  If the result is exactly 0, jump to P2.
   73622 */
   73623 case OP_IfZero: {        /* jump, in1 */
   73624   pIn1 = &aMem[pOp->p1];
   73625   assert( pIn1->flags&MEM_Int );
   73626   pIn1->u.i += pOp->p3;
   73627   VdbeBranchTaken(pIn1->u.i==0, 2);
   73628   if( pIn1->u.i==0 ){
   73629      pc = pOp->p2 - 1;
   73630   }
   73631   break;
   73632 }
   73633 
   73634 /* Opcode: AggStep * P2 P3 P4 P5
   73635 ** Synopsis: accum=r[P3] step(r[P2@P5])
   73636 **
   73637 ** Execute the step function for an aggregate.  The
   73638 ** function has P5 arguments.   P4 is a pointer to the FuncDef
   73639 ** structure that specifies the function.  Use register
   73640 ** P3 as the accumulator.
   73641 **
   73642 ** The P5 arguments are taken from register P2 and its
   73643 ** successors.
   73644 */
   73645 case OP_AggStep: {
   73646   int n;
   73647   int i;
   73648   Mem *pMem;
   73649   Mem *pRec;
   73650   sqlite3_context ctx;
   73651   sqlite3_value **apVal;
   73652 
   73653   n = pOp->p5;
   73654   assert( n>=0 );
   73655   pRec = &aMem[pOp->p2];
   73656   apVal = p->apArg;
   73657   assert( apVal || n==0 );
   73658   for(i=0; i<n; i++, pRec++){
   73659     assert( memIsValid(pRec) );
   73660     apVal[i] = pRec;
   73661     memAboutToChange(p, pRec);
   73662   }
   73663   ctx.pFunc = pOp->p4.pFunc;
   73664   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   73665   ctx.pMem = pMem = &aMem[pOp->p3];
   73666   pMem->n++;
   73667   ctx.s.flags = MEM_Null;
   73668   ctx.s.z = 0;
   73669   ctx.s.zMalloc = 0;
   73670   ctx.s.xDel = 0;
   73671   ctx.s.db = db;
   73672   ctx.isError = 0;
   73673   ctx.pColl = 0;
   73674   ctx.skipFlag = 0;
   73675   if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   73676     assert( pOp>p->aOp );
   73677     assert( pOp[-1].p4type==P4_COLLSEQ );
   73678     assert( pOp[-1].opcode==OP_CollSeq );
   73679     ctx.pColl = pOp[-1].p4.pColl;
   73680   }
   73681   (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
   73682   if( ctx.isError ){
   73683     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
   73684     rc = ctx.isError;
   73685   }
   73686   if( ctx.skipFlag ){
   73687     assert( pOp[-1].opcode==OP_CollSeq );
   73688     i = pOp[-1].p1;
   73689     if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
   73690   }
   73691 
   73692   sqlite3VdbeMemRelease(&ctx.s);
   73693 
   73694   break;
   73695 }
   73696 
   73697 /* Opcode: AggFinal P1 P2 * P4 *
   73698 ** Synopsis: accum=r[P1] N=P2
   73699 **
   73700 ** Execute the finalizer function for an aggregate.  P1 is
   73701 ** the memory location that is the accumulator for the aggregate.
   73702 **
   73703 ** P2 is the number of arguments that the step function takes and
   73704 ** P4 is a pointer to the FuncDef for this function.  The P2
   73705 ** argument is not used by this opcode.  It is only there to disambiguate
   73706 ** functions that can take varying numbers of arguments.  The
   73707 ** P4 argument is only needed for the degenerate case where
   73708 ** the step function was not previously called.
   73709 */
   73710 case OP_AggFinal: {
   73711   Mem *pMem;
   73712   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
   73713   pMem = &aMem[pOp->p1];
   73714   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
   73715   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
   73716   if( rc ){
   73717     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
   73718   }
   73719   sqlite3VdbeChangeEncoding(pMem, encoding);
   73720   UPDATE_MAX_BLOBSIZE(pMem);
   73721   if( sqlite3VdbeMemTooBig(pMem) ){
   73722     goto too_big;
   73723   }
   73724   break;
   73725 }
   73726 
   73727 #ifndef SQLITE_OMIT_WAL
   73728 /* Opcode: Checkpoint P1 P2 P3 * *
   73729 **
   73730 ** Checkpoint database P1. This is a no-op if P1 is not currently in
   73731 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
   73732 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
   73733 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
   73734 ** WAL after the checkpoint into mem[P3+1] and the number of pages
   73735 ** in the WAL that have been checkpointed after the checkpoint
   73736 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
   73737 ** mem[P3+2] are initialized to -1.
   73738 */
   73739 case OP_Checkpoint: {
   73740   int i;                          /* Loop counter */
   73741   int aRes[3];                    /* Results */
   73742   Mem *pMem;                      /* Write results here */
   73743 
   73744   assert( p->readOnly==0 );
   73745   aRes[0] = 0;
   73746   aRes[1] = aRes[2] = -1;
   73747   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
   73748        || pOp->p2==SQLITE_CHECKPOINT_FULL
   73749        || pOp->p2==SQLITE_CHECKPOINT_RESTART
   73750   );
   73751   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
   73752   if( rc==SQLITE_BUSY ){
   73753     rc = SQLITE_OK;
   73754     aRes[0] = 1;
   73755   }
   73756   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
   73757     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
   73758   }
   73759   break;
   73760 };
   73761 #endif
   73762 
   73763 #ifndef SQLITE_OMIT_PRAGMA
   73764 /* Opcode: JournalMode P1 P2 P3 * *
   73765 **
   73766 ** Change the journal mode of database P1 to P3. P3 must be one of the
   73767 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
   73768 ** modes (delete, truncate, persist, off and memory), this is a simple
   73769 ** operation. No IO is required.
   73770 **
   73771 ** If changing into or out of WAL mode the procedure is more complicated.
   73772 **
   73773 ** Write a string containing the final journal-mode to register P2.
   73774 */
   73775 case OP_JournalMode: {    /* out2-prerelease */
   73776   Btree *pBt;                     /* Btree to change journal mode of */
   73777   Pager *pPager;                  /* Pager associated with pBt */
   73778   int eNew;                       /* New journal mode */
   73779   int eOld;                       /* The old journal mode */
   73780 #ifndef SQLITE_OMIT_WAL
   73781   const char *zFilename;          /* Name of database file for pPager */
   73782 #endif
   73783 
   73784   eNew = pOp->p3;
   73785   assert( eNew==PAGER_JOURNALMODE_DELETE
   73786        || eNew==PAGER_JOURNALMODE_TRUNCATE
   73787        || eNew==PAGER_JOURNALMODE_PERSIST
   73788        || eNew==PAGER_JOURNALMODE_OFF
   73789        || eNew==PAGER_JOURNALMODE_MEMORY
   73790        || eNew==PAGER_JOURNALMODE_WAL
   73791        || eNew==PAGER_JOURNALMODE_QUERY
   73792   );
   73793   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   73794   assert( p->readOnly==0 );
   73795 
   73796   pBt = db->aDb[pOp->p1].pBt;
   73797   pPager = sqlite3BtreePager(pBt);
   73798   eOld = sqlite3PagerGetJournalMode(pPager);
   73799   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
   73800   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
   73801 
   73802 #ifndef SQLITE_OMIT_WAL
   73803   zFilename = sqlite3PagerFilename(pPager, 1);
   73804 
   73805   /* Do not allow a transition to journal_mode=WAL for a database
   73806   ** in temporary storage or if the VFS does not support shared memory
   73807   */
   73808   if( eNew==PAGER_JOURNALMODE_WAL
   73809    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
   73810        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
   73811   ){
   73812     eNew = eOld;
   73813   }
   73814 
   73815   if( (eNew!=eOld)
   73816    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
   73817   ){
   73818     if( !db->autoCommit || db->nVdbeRead>1 ){
   73819       rc = SQLITE_ERROR;
   73820       sqlite3SetString(&p->zErrMsg, db,
   73821           "cannot change %s wal mode from within a transaction",
   73822           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
   73823       );
   73824       break;
   73825     }else{
   73826 
   73827       if( eOld==PAGER_JOURNALMODE_WAL ){
   73828         /* If leaving WAL mode, close the log file. If successful, the call
   73829         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
   73830         ** file. An EXCLUSIVE lock may still be held on the database file
   73831         ** after a successful return.
   73832         */
   73833         rc = sqlite3PagerCloseWal(pPager);
   73834         if( rc==SQLITE_OK ){
   73835           sqlite3PagerSetJournalMode(pPager, eNew);
   73836         }
   73837       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
   73838         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
   73839         ** as an intermediate */
   73840         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
   73841       }
   73842 
   73843       /* Open a transaction on the database file. Regardless of the journal
   73844       ** mode, this transaction always uses a rollback journal.
   73845       */
   73846       assert( sqlite3BtreeIsInTrans(pBt)==0 );
   73847       if( rc==SQLITE_OK ){
   73848         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
   73849       }
   73850     }
   73851   }
   73852 #endif /* ifndef SQLITE_OMIT_WAL */
   73853 
   73854   if( rc ){
   73855     eNew = eOld;
   73856   }
   73857   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
   73858 
   73859   pOut = &aMem[pOp->p2];
   73860   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   73861   pOut->z = (char *)sqlite3JournalModename(eNew);
   73862   pOut->n = sqlite3Strlen30(pOut->z);
   73863   pOut->enc = SQLITE_UTF8;
   73864   sqlite3VdbeChangeEncoding(pOut, encoding);
   73865   break;
   73866 };
   73867 #endif /* SQLITE_OMIT_PRAGMA */
   73868 
   73869 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   73870 /* Opcode: Vacuum * * * * *
   73871 **
   73872 ** Vacuum the entire database.  This opcode will cause other virtual
   73873 ** machines to be created and run.  It may not be called from within
   73874 ** a transaction.
   73875 */
   73876 case OP_Vacuum: {
   73877   assert( p->readOnly==0 );
   73878   rc = sqlite3RunVacuum(&p->zErrMsg, db);
   73879   break;
   73880 }
   73881 #endif
   73882 
   73883 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   73884 /* Opcode: IncrVacuum P1 P2 * * *
   73885 **
   73886 ** Perform a single step of the incremental vacuum procedure on
   73887 ** the P1 database. If the vacuum has finished, jump to instruction
   73888 ** P2. Otherwise, fall through to the next instruction.
   73889 */
   73890 case OP_IncrVacuum: {        /* jump */
   73891   Btree *pBt;
   73892 
   73893   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   73894   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   73895   assert( p->readOnly==0 );
   73896   pBt = db->aDb[pOp->p1].pBt;
   73897   rc = sqlite3BtreeIncrVacuum(pBt);
   73898   VdbeBranchTaken(rc==SQLITE_DONE,2);
   73899   if( rc==SQLITE_DONE ){
   73900     pc = pOp->p2 - 1;
   73901     rc = SQLITE_OK;
   73902   }
   73903   break;
   73904 }
   73905 #endif
   73906 
   73907 /* Opcode: Expire P1 * * * *
   73908 **
   73909 ** Cause precompiled statements to expire.  When an expired statement
   73910 ** is executed using sqlite3_step() it will either automatically
   73911 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
   73912 ** or it will fail with SQLITE_SCHEMA.
   73913 **
   73914 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
   73915 ** then only the currently executing statement is expired.
   73916 */
   73917 case OP_Expire: {
   73918   if( !pOp->p1 ){
   73919     sqlite3ExpirePreparedStatements(db);
   73920   }else{
   73921     p->expired = 1;
   73922   }
   73923   break;
   73924 }
   73925 
   73926 #ifndef SQLITE_OMIT_SHARED_CACHE
   73927 /* Opcode: TableLock P1 P2 P3 P4 *
   73928 ** Synopsis: iDb=P1 root=P2 write=P3
   73929 **
   73930 ** Obtain a lock on a particular table. This instruction is only used when
   73931 ** the shared-cache feature is enabled.
   73932 **
   73933 ** P1 is the index of the database in sqlite3.aDb[] of the database
   73934 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
   73935 ** a write lock if P3==1.
   73936 **
   73937 ** P2 contains the root-page of the table to lock.
   73938 **
   73939 ** P4 contains a pointer to the name of the table being locked. This is only
   73940 ** used to generate an error message if the lock cannot be obtained.
   73941 */
   73942 case OP_TableLock: {
   73943   u8 isWriteLock = (u8)pOp->p3;
   73944   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
   73945     int p1 = pOp->p1;
   73946     assert( p1>=0 && p1<db->nDb );
   73947     assert( DbMaskTest(p->btreeMask, p1) );
   73948     assert( isWriteLock==0 || isWriteLock==1 );
   73949     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
   73950     if( (rc&0xFF)==SQLITE_LOCKED ){
   73951       const char *z = pOp->p4.z;
   73952       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
   73953     }
   73954   }
   73955   break;
   73956 }
   73957 #endif /* SQLITE_OMIT_SHARED_CACHE */
   73958 
   73959 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73960 /* Opcode: VBegin * * * P4 *
   73961 **
   73962 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
   73963 ** xBegin method for that table.
   73964 **
   73965 ** Also, whether or not P4 is set, check that this is not being called from
   73966 ** within a callback to a virtual table xSync() method. If it is, the error
   73967 ** code will be set to SQLITE_LOCKED.
   73968 */
   73969 case OP_VBegin: {
   73970   VTable *pVTab;
   73971   pVTab = pOp->p4.pVtab;
   73972   rc = sqlite3VtabBegin(db, pVTab);
   73973   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
   73974   break;
   73975 }
   73976 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   73977 
   73978 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73979 /* Opcode: VCreate P1 * * P4 *
   73980 **
   73981 ** P4 is the name of a virtual table in database P1. Call the xCreate method
   73982 ** for that table.
   73983 */
   73984 case OP_VCreate: {
   73985   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
   73986   break;
   73987 }
   73988 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   73989 
   73990 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73991 /* Opcode: VDestroy P1 * * P4 *
   73992 **
   73993 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
   73994 ** of that table.
   73995 */
   73996 case OP_VDestroy: {
   73997   p->inVtabMethod = 2;
   73998   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
   73999   p->inVtabMethod = 0;
   74000   break;
   74001 }
   74002 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74003 
   74004 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74005 /* Opcode: VOpen P1 * * P4 *
   74006 **
   74007 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   74008 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
   74009 ** table and stores that cursor in P1.
   74010 */
   74011 case OP_VOpen: {
   74012   VdbeCursor *pCur;
   74013   sqlite3_vtab_cursor *pVtabCursor;
   74014   sqlite3_vtab *pVtab;
   74015   sqlite3_module *pModule;
   74016 
   74017   assert( p->bIsReader );
   74018   pCur = 0;
   74019   pVtabCursor = 0;
   74020   pVtab = pOp->p4.pVtab->pVtab;
   74021   pModule = (sqlite3_module *)pVtab->pModule;
   74022   assert(pVtab && pModule);
   74023   rc = pModule->xOpen(pVtab, &pVtabCursor);
   74024   sqlite3VtabImportErrmsg(p, pVtab);
   74025   if( SQLITE_OK==rc ){
   74026     /* Initialize sqlite3_vtab_cursor base class */
   74027     pVtabCursor->pVtab = pVtab;
   74028 
   74029     /* Initialize vdbe cursor object */
   74030     pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
   74031     if( pCur ){
   74032       pCur->pVtabCursor = pVtabCursor;
   74033     }else{
   74034       db->mallocFailed = 1;
   74035       pModule->xClose(pVtabCursor);
   74036     }
   74037   }
   74038   break;
   74039 }
   74040 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74041 
   74042 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74043 /* Opcode: VFilter P1 P2 P3 P4 *
   74044 ** Synopsis: iplan=r[P3] zplan='P4'
   74045 **
   74046 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
   74047 ** the filtered result set is empty.
   74048 **
   74049 ** P4 is either NULL or a string that was generated by the xBestIndex
   74050 ** method of the module.  The interpretation of the P4 string is left
   74051 ** to the module implementation.
   74052 **
   74053 ** This opcode invokes the xFilter method on the virtual table specified
   74054 ** by P1.  The integer query plan parameter to xFilter is stored in register
   74055 ** P3. Register P3+1 stores the argc parameter to be passed to the
   74056 ** xFilter method. Registers P3+2..P3+1+argc are the argc
   74057 ** additional parameters which are passed to
   74058 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
   74059 **
   74060 ** A jump is made to P2 if the result set after filtering would be empty.
   74061 */
   74062 case OP_VFilter: {   /* jump */
   74063   int nArg;
   74064   int iQuery;
   74065   const sqlite3_module *pModule;
   74066   Mem *pQuery;
   74067   Mem *pArgc;
   74068   sqlite3_vtab_cursor *pVtabCursor;
   74069   sqlite3_vtab *pVtab;
   74070   VdbeCursor *pCur;
   74071   int res;
   74072   int i;
   74073   Mem **apArg;
   74074 
   74075   pQuery = &aMem[pOp->p3];
   74076   pArgc = &pQuery[1];
   74077   pCur = p->apCsr[pOp->p1];
   74078   assert( memIsValid(pQuery) );
   74079   REGISTER_TRACE(pOp->p3, pQuery);
   74080   assert( pCur->pVtabCursor );
   74081   pVtabCursor = pCur->pVtabCursor;
   74082   pVtab = pVtabCursor->pVtab;
   74083   pModule = pVtab->pModule;
   74084 
   74085   /* Grab the index number and argc parameters */
   74086   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
   74087   nArg = (int)pArgc->u.i;
   74088   iQuery = (int)pQuery->u.i;
   74089 
   74090   /* Invoke the xFilter method */
   74091   {
   74092     res = 0;
   74093     apArg = p->apArg;
   74094     for(i = 0; i<nArg; i++){
   74095       apArg[i] = &pArgc[i+1];
   74096     }
   74097 
   74098     p->inVtabMethod = 1;
   74099     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
   74100     p->inVtabMethod = 0;
   74101     sqlite3VtabImportErrmsg(p, pVtab);
   74102     if( rc==SQLITE_OK ){
   74103       res = pModule->xEof(pVtabCursor);
   74104     }
   74105     VdbeBranchTaken(res!=0,2);
   74106     if( res ){
   74107       pc = pOp->p2 - 1;
   74108     }
   74109   }
   74110   pCur->nullRow = 0;
   74111 
   74112   break;
   74113 }
   74114 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74115 
   74116 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74117 /* Opcode: VColumn P1 P2 P3 * *
   74118 ** Synopsis: r[P3]=vcolumn(P2)
   74119 **
   74120 ** Store the value of the P2-th column of
   74121 ** the row of the virtual-table that the
   74122 ** P1 cursor is pointing to into register P3.
   74123 */
   74124 case OP_VColumn: {
   74125   sqlite3_vtab *pVtab;
   74126   const sqlite3_module *pModule;
   74127   Mem *pDest;
   74128   sqlite3_context sContext;
   74129 
   74130   VdbeCursor *pCur = p->apCsr[pOp->p1];
   74131   assert( pCur->pVtabCursor );
   74132   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
   74133   pDest = &aMem[pOp->p3];
   74134   memAboutToChange(p, pDest);
   74135   if( pCur->nullRow ){
   74136     sqlite3VdbeMemSetNull(pDest);
   74137     break;
   74138   }
   74139   pVtab = pCur->pVtabCursor->pVtab;
   74140   pModule = pVtab->pModule;
   74141   assert( pModule->xColumn );
   74142   memset(&sContext, 0, sizeof(sContext));
   74143 
   74144   /* The output cell may already have a buffer allocated. Move
   74145   ** the current contents to sContext.s so in case the user-function
   74146   ** can use the already allocated buffer instead of allocating a
   74147   ** new one.
   74148   */
   74149   sqlite3VdbeMemMove(&sContext.s, pDest);
   74150   MemSetTypeFlag(&sContext.s, MEM_Null);
   74151 
   74152   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
   74153   sqlite3VtabImportErrmsg(p, pVtab);
   74154   if( sContext.isError ){
   74155     rc = sContext.isError;
   74156   }
   74157 
   74158   /* Copy the result of the function to the P3 register. We
   74159   ** do this regardless of whether or not an error occurred to ensure any
   74160   ** dynamic allocation in sContext.s (a Mem struct) is  released.
   74161   */
   74162   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
   74163   sqlite3VdbeMemMove(pDest, &sContext.s);
   74164   REGISTER_TRACE(pOp->p3, pDest);
   74165   UPDATE_MAX_BLOBSIZE(pDest);
   74166 
   74167   if( sqlite3VdbeMemTooBig(pDest) ){
   74168     goto too_big;
   74169   }
   74170   break;
   74171 }
   74172 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74173 
   74174 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74175 /* Opcode: VNext P1 P2 * * *
   74176 **
   74177 ** Advance virtual table P1 to the next row in its result set and
   74178 ** jump to instruction P2.  Or, if the virtual table has reached
   74179 ** the end of its result set, then fall through to the next instruction.
   74180 */
   74181 case OP_VNext: {   /* jump */
   74182   sqlite3_vtab *pVtab;
   74183   const sqlite3_module *pModule;
   74184   int res;
   74185   VdbeCursor *pCur;
   74186 
   74187   res = 0;
   74188   pCur = p->apCsr[pOp->p1];
   74189   assert( pCur->pVtabCursor );
   74190   if( pCur->nullRow ){
   74191     break;
   74192   }
   74193   pVtab = pCur->pVtabCursor->pVtab;
   74194   pModule = pVtab->pModule;
   74195   assert( pModule->xNext );
   74196 
   74197   /* Invoke the xNext() method of the module. There is no way for the
   74198   ** underlying implementation to return an error if one occurs during
   74199   ** xNext(). Instead, if an error occurs, true is returned (indicating that
   74200   ** data is available) and the error code returned when xColumn or
   74201   ** some other method is next invoked on the save virtual table cursor.
   74202   */
   74203   p->inVtabMethod = 1;
   74204   rc = pModule->xNext(pCur->pVtabCursor);
   74205   p->inVtabMethod = 0;
   74206   sqlite3VtabImportErrmsg(p, pVtab);
   74207   if( rc==SQLITE_OK ){
   74208     res = pModule->xEof(pCur->pVtabCursor);
   74209   }
   74210   VdbeBranchTaken(!res,2);
   74211   if( !res ){
   74212     /* If there is data, jump to P2 */
   74213     pc = pOp->p2 - 1;
   74214   }
   74215   goto check_for_interrupt;
   74216 }
   74217 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74218 
   74219 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74220 /* Opcode: VRename P1 * * P4 *
   74221 **
   74222 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   74223 ** This opcode invokes the corresponding xRename method. The value
   74224 ** in register P1 is passed as the zName argument to the xRename method.
   74225 */
   74226 case OP_VRename: {
   74227   sqlite3_vtab *pVtab;
   74228   Mem *pName;
   74229 
   74230   pVtab = pOp->p4.pVtab->pVtab;
   74231   pName = &aMem[pOp->p1];
   74232   assert( pVtab->pModule->xRename );
   74233   assert( memIsValid(pName) );
   74234   assert( p->readOnly==0 );
   74235   REGISTER_TRACE(pOp->p1, pName);
   74236   assert( pName->flags & MEM_Str );
   74237   testcase( pName->enc==SQLITE_UTF8 );
   74238   testcase( pName->enc==SQLITE_UTF16BE );
   74239   testcase( pName->enc==SQLITE_UTF16LE );
   74240   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
   74241   if( rc==SQLITE_OK ){
   74242     rc = pVtab->pModule->xRename(pVtab, pName->z);
   74243     sqlite3VtabImportErrmsg(p, pVtab);
   74244     p->expired = 0;
   74245   }
   74246   break;
   74247 }
   74248 #endif
   74249 
   74250 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74251 /* Opcode: VUpdate P1 P2 P3 P4 P5
   74252 ** Synopsis: data=r[P3@P2]
   74253 **
   74254 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   74255 ** This opcode invokes the corresponding xUpdate method. P2 values
   74256 ** are contiguous memory cells starting at P3 to pass to the xUpdate
   74257 ** invocation. The value in register (P3+P2-1) corresponds to the
   74258 ** p2th element of the argv array passed to xUpdate.
   74259 **
   74260 ** The xUpdate method will do a DELETE or an INSERT or both.
   74261 ** The argv[0] element (which corresponds to memory cell P3)
   74262 ** is the rowid of a row to delete.  If argv[0] is NULL then no
   74263 ** deletion occurs.  The argv[1] element is the rowid of the new
   74264 ** row.  This can be NULL to have the virtual table select the new
   74265 ** rowid for itself.  The subsequent elements in the array are
   74266 ** the values of columns in the new row.
   74267 **
   74268 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
   74269 ** a row to delete.
   74270 **
   74271 ** P1 is a boolean flag. If it is set to true and the xUpdate call
   74272 ** is successful, then the value returned by sqlite3_last_insert_rowid()
   74273 ** is set to the value of the rowid for the row just inserted.
   74274 **
   74275 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
   74276 ** apply in the case of a constraint failure on an insert or update.
   74277 */
   74278 case OP_VUpdate: {
   74279   sqlite3_vtab *pVtab;
   74280   sqlite3_module *pModule;
   74281   int nArg;
   74282   int i;
   74283   sqlite_int64 rowid;
   74284   Mem **apArg;
   74285   Mem *pX;
   74286 
   74287   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
   74288        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
   74289   );
   74290   assert( p->readOnly==0 );
   74291   pVtab = pOp->p4.pVtab->pVtab;
   74292   pModule = (sqlite3_module *)pVtab->pModule;
   74293   nArg = pOp->p2;
   74294   assert( pOp->p4type==P4_VTAB );
   74295   if( ALWAYS(pModule->xUpdate) ){
   74296     u8 vtabOnConflict = db->vtabOnConflict;
   74297     apArg = p->apArg;
   74298     pX = &aMem[pOp->p3];
   74299     for(i=0; i<nArg; i++){
   74300       assert( memIsValid(pX) );
   74301       memAboutToChange(p, pX);
   74302       apArg[i] = pX;
   74303       pX++;
   74304     }
   74305     db->vtabOnConflict = pOp->p5;
   74306     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
   74307     db->vtabOnConflict = vtabOnConflict;
   74308     sqlite3VtabImportErrmsg(p, pVtab);
   74309     if( rc==SQLITE_OK && pOp->p1 ){
   74310       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
   74311       db->lastRowid = lastRowid = rowid;
   74312     }
   74313     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
   74314       if( pOp->p5==OE_Ignore ){
   74315         rc = SQLITE_OK;
   74316       }else{
   74317         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
   74318       }
   74319     }else{
   74320       p->nChange++;
   74321     }
   74322   }
   74323   break;
   74324 }
   74325 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   74326 
   74327 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   74328 /* Opcode: Pagecount P1 P2 * * *
   74329 **
   74330 ** Write the current number of pages in database P1 to memory cell P2.
   74331 */
   74332 case OP_Pagecount: {            /* out2-prerelease */
   74333   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
   74334   break;
   74335 }
   74336 #endif
   74337 
   74338 
   74339 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   74340 /* Opcode: MaxPgcnt P1 P2 P3 * *
   74341 **
   74342 ** Try to set the maximum page count for database P1 to the value in P3.
   74343 ** Do not let the maximum page count fall below the current page count and
   74344 ** do not change the maximum page count value if P3==0.
   74345 **
   74346 ** Store the maximum page count after the change in register P2.
   74347 */
   74348 case OP_MaxPgcnt: {            /* out2-prerelease */
   74349   unsigned int newMax;
   74350   Btree *pBt;
   74351 
   74352   pBt = db->aDb[pOp->p1].pBt;
   74353   newMax = 0;
   74354   if( pOp->p3 ){
   74355     newMax = sqlite3BtreeLastPage(pBt);
   74356     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
   74357   }
   74358   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
   74359   break;
   74360 }
   74361 #endif
   74362 
   74363 
   74364 /* Opcode: Init * P2 * P4 *
   74365 ** Synopsis:  Start at P2
   74366 **
   74367 ** Programs contain a single instance of this opcode as the very first
   74368 ** opcode.
   74369 **
   74370 ** If tracing is enabled (by the sqlite3_trace()) interface, then
   74371 ** the UTF-8 string contained in P4 is emitted on the trace callback.
   74372 ** Or if P4 is blank, use the string returned by sqlite3_sql().
   74373 **
   74374 ** If P2 is not zero, jump to instruction P2.
   74375 */
   74376 case OP_Init: {          /* jump */
   74377   char *zTrace;
   74378   char *z;
   74379 
   74380   if( pOp->p2 ){
   74381     pc = pOp->p2 - 1;
   74382   }
   74383 #ifndef SQLITE_OMIT_TRACE
   74384   if( db->xTrace
   74385    && !p->doingRerun
   74386    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
   74387   ){
   74388     z = sqlite3VdbeExpandSql(p, zTrace);
   74389     db->xTrace(db->pTraceArg, z);
   74390     sqlite3DbFree(db, z);
   74391   }
   74392 #ifdef SQLITE_USE_FCNTL_TRACE
   74393   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
   74394   if( zTrace ){
   74395     int i;
   74396     for(i=0; i<db->nDb; i++){
   74397       if( DbMaskTest(p->btreeMask, i)==0 ) continue;
   74398       sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
   74399     }
   74400   }
   74401 #endif /* SQLITE_USE_FCNTL_TRACE */
   74402 #ifdef SQLITE_DEBUG
   74403   if( (db->flags & SQLITE_SqlTrace)!=0
   74404    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
   74405   ){
   74406     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
   74407   }
   74408 #endif /* SQLITE_DEBUG */
   74409 #endif /* SQLITE_OMIT_TRACE */
   74410   break;
   74411 }
   74412 
   74413 
   74414 /* Opcode: Noop * * * * *
   74415 **
   74416 ** Do nothing.  This instruction is often useful as a jump
   74417 ** destination.
   74418 */
   74419 /*
   74420 ** The magic Explain opcode are only inserted when explain==2 (which
   74421 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
   74422 ** This opcode records information from the optimizer.  It is the
   74423 ** the same as a no-op.  This opcodesnever appears in a real VM program.
   74424 */
   74425 default: {          /* This is really OP_Noop and OP_Explain */
   74426   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
   74427   break;
   74428 }
   74429 
   74430 /*****************************************************************************
   74431 ** The cases of the switch statement above this line should all be indented
   74432 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
   74433 ** readability.  From this point on down, the normal indentation rules are
   74434 ** restored.
   74435 *****************************************************************************/
   74436     }
   74437 
   74438 #ifdef VDBE_PROFILE
   74439     {
   74440       u64 endTime = sqlite3Hwtime();
   74441       if( endTime>start ) pOp->cycles += endTime - start;
   74442       pOp->cnt++;
   74443     }
   74444 #endif
   74445 
   74446     /* The following code adds nothing to the actual functionality
   74447     ** of the program.  It is only here for testing and debugging.
   74448     ** On the other hand, it does burn CPU cycles every time through
   74449     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
   74450     */
   74451 #ifndef NDEBUG
   74452     assert( pc>=-1 && pc<p->nOp );
   74453 
   74454 #ifdef SQLITE_DEBUG
   74455     if( db->flags & SQLITE_VdbeTrace ){
   74456       if( rc!=0 ) printf("rc=%d\n",rc);
   74457       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
   74458         registerTrace(pOp->p2, &aMem[pOp->p2]);
   74459       }
   74460       if( pOp->opflags & OPFLG_OUT3 ){
   74461         registerTrace(pOp->p3, &aMem[pOp->p3]);
   74462       }
   74463     }
   74464 #endif  /* SQLITE_DEBUG */
   74465 #endif  /* NDEBUG */
   74466   }  /* The end of the for(;;) loop the loops through opcodes */
   74467 
   74468   /* If we reach this point, it means that execution is finished with
   74469   ** an error of some kind.
   74470   */
   74471 vdbe_error_halt:
   74472   assert( rc );
   74473   p->rc = rc;
   74474   testcase( sqlite3GlobalConfig.xLog!=0 );
   74475   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
   74476                    pc, p->zSql, p->zErrMsg);
   74477   sqlite3VdbeHalt(p);
   74478   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
   74479   rc = SQLITE_ERROR;
   74480   if( resetSchemaOnFault>0 ){
   74481     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
   74482   }
   74483 
   74484   /* This is the only way out of this procedure.  We have to
   74485   ** release the mutexes on btrees that were acquired at the
   74486   ** top. */
   74487 vdbe_return:
   74488   db->lastRowid = lastRowid;
   74489   testcase( nVmStep>0 );
   74490   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
   74491   sqlite3VdbeLeave(p);
   74492   return rc;
   74493 
   74494   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
   74495   ** is encountered.
   74496   */
   74497 too_big:
   74498   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
   74499   rc = SQLITE_TOOBIG;
   74500   goto vdbe_error_halt;
   74501 
   74502   /* Jump to here if a malloc() fails.
   74503   */
   74504 no_mem:
   74505   db->mallocFailed = 1;
   74506   sqlite3SetString(&p->zErrMsg, db, "out of memory");
   74507   rc = SQLITE_NOMEM;
   74508   goto vdbe_error_halt;
   74509 
   74510   /* Jump to here for any other kind of fatal error.  The "rc" variable
   74511   ** should hold the error number.
   74512   */
   74513 abort_due_to_error:
   74514   assert( p->zErrMsg==0 );
   74515   if( db->mallocFailed ) rc = SQLITE_NOMEM;
   74516   if( rc!=SQLITE_IOERR_NOMEM ){
   74517     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   74518   }
   74519   goto vdbe_error_halt;
   74520 
   74521   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
   74522   ** flag.
   74523   */
   74524 abort_due_to_interrupt:
   74525   assert( db->u1.isInterrupted );
   74526   rc = SQLITE_INTERRUPT;
   74527   p->rc = rc;
   74528   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   74529   goto vdbe_error_halt;
   74530 }
   74531 
   74532 
   74533 /************** End of vdbe.c ************************************************/
   74534 /************** Begin file vdbeblob.c ****************************************/
   74535 /*
   74536 ** 2007 May 1
   74537 **
   74538 ** The author disclaims copyright to this source code.  In place of
   74539 ** a legal notice, here is a blessing:
   74540 **
   74541 **    May you do good and not evil.
   74542 **    May you find forgiveness for yourself and forgive others.
   74543 **    May you share freely, never taking more than you give.
   74544 **
   74545 *************************************************************************
   74546 **
   74547 ** This file contains code used to implement incremental BLOB I/O.
   74548 */
   74549 
   74550 
   74551 #ifndef SQLITE_OMIT_INCRBLOB
   74552 
   74553 /*
   74554 ** Valid sqlite3_blob* handles point to Incrblob structures.
   74555 */
   74556 typedef struct Incrblob Incrblob;
   74557 struct Incrblob {
   74558   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
   74559   int nByte;              /* Size of open blob, in bytes */
   74560   int iOffset;            /* Byte offset of blob in cursor data */
   74561   int iCol;               /* Table column this handle is open on */
   74562   BtCursor *pCsr;         /* Cursor pointing at blob row */
   74563   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
   74564   sqlite3 *db;            /* The associated database */
   74565 };
   74566 
   74567 
   74568 /*
   74569 ** This function is used by both blob_open() and blob_reopen(). It seeks
   74570 ** the b-tree cursor associated with blob handle p to point to row iRow.
   74571 ** If successful, SQLITE_OK is returned and subsequent calls to
   74572 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
   74573 **
   74574 ** If an error occurs, or if the specified row does not exist or does not
   74575 ** contain a value of type TEXT or BLOB in the column nominated when the
   74576 ** blob handle was opened, then an error code is returned and *pzErr may
   74577 ** be set to point to a buffer containing an error message. It is the
   74578 ** responsibility of the caller to free the error message buffer using
   74579 ** sqlite3DbFree().
   74580 **
   74581 ** If an error does occur, then the b-tree cursor is closed. All subsequent
   74582 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
   74583 ** immediately return SQLITE_ABORT.
   74584 */
   74585 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
   74586   int rc;                         /* Error code */
   74587   char *zErr = 0;                 /* Error message */
   74588   Vdbe *v = (Vdbe *)p->pStmt;
   74589 
   74590   /* Set the value of the SQL statements only variable to integer iRow.
   74591   ** This is done directly instead of using sqlite3_bind_int64() to avoid
   74592   ** triggering asserts related to mutexes.
   74593   */
   74594   assert( v->aVar[0].flags&MEM_Int );
   74595   v->aVar[0].u.i = iRow;
   74596 
   74597   rc = sqlite3_step(p->pStmt);
   74598   if( rc==SQLITE_ROW ){
   74599     VdbeCursor *pC = v->apCsr[0];
   74600     u32 type = pC->aType[p->iCol];
   74601     if( type<12 ){
   74602       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
   74603           type==0?"null": type==7?"real": "integer"
   74604       );
   74605       rc = SQLITE_ERROR;
   74606       sqlite3_finalize(p->pStmt);
   74607       p->pStmt = 0;
   74608     }else{
   74609       p->iOffset = pC->aType[p->iCol + pC->nField];
   74610       p->nByte = sqlite3VdbeSerialTypeLen(type);
   74611       p->pCsr =  pC->pCursor;
   74612       sqlite3BtreeIncrblobCursor(p->pCsr);
   74613     }
   74614   }
   74615 
   74616   if( rc==SQLITE_ROW ){
   74617     rc = SQLITE_OK;
   74618   }else if( p->pStmt ){
   74619     rc = sqlite3_finalize(p->pStmt);
   74620     p->pStmt = 0;
   74621     if( rc==SQLITE_OK ){
   74622       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
   74623       rc = SQLITE_ERROR;
   74624     }else{
   74625       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
   74626     }
   74627   }
   74628 
   74629   assert( rc!=SQLITE_OK || zErr==0 );
   74630   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
   74631 
   74632   *pzErr = zErr;
   74633   return rc;
   74634 }
   74635 
   74636 /*
   74637 ** Open a blob handle.
   74638 */
   74639 SQLITE_API int sqlite3_blob_open(
   74640   sqlite3* db,            /* The database connection */
   74641   const char *zDb,        /* The attached database containing the blob */
   74642   const char *zTable,     /* The table containing the blob */
   74643   const char *zColumn,    /* The column containing the blob */
   74644   sqlite_int64 iRow,      /* The row containing the glob */
   74645   int flags,              /* True -> read/write access, false -> read-only */
   74646   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
   74647 ){
   74648   int nAttempt = 0;
   74649   int iCol;               /* Index of zColumn in row-record */
   74650 
   74651   /* This VDBE program seeks a btree cursor to the identified
   74652   ** db/table/row entry. The reason for using a vdbe program instead
   74653   ** of writing code to use the b-tree layer directly is that the
   74654   ** vdbe program will take advantage of the various transaction,
   74655   ** locking and error handling infrastructure built into the vdbe.
   74656   **
   74657   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
   74658   ** Code external to the Vdbe then "borrows" the b-tree cursor and
   74659   ** uses it to implement the blob_read(), blob_write() and
   74660   ** blob_bytes() functions.
   74661   **
   74662   ** The sqlite3_blob_close() function finalizes the vdbe program,
   74663   ** which closes the b-tree cursor and (possibly) commits the
   74664   ** transaction.
   74665   */
   74666   static const int iLn = VDBE_OFFSET_LINENO(4);
   74667   static const VdbeOpList openBlob[] = {
   74668     /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
   74669     {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
   74670     /* One of the following two instructions is replaced by an OP_Noop. */
   74671     {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
   74672     {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
   74673     {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
   74674     {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
   74675     {OP_Column, 0, 0, 1},          /* 6  */
   74676     {OP_ResultRow, 1, 0, 0},       /* 7  */
   74677     {OP_Goto, 0, 4, 0},            /* 8  */
   74678     {OP_Close, 0, 0, 0},           /* 9  */
   74679     {OP_Halt, 0, 0, 0},            /* 10 */
   74680   };
   74681 
   74682   int rc = SQLITE_OK;
   74683   char *zErr = 0;
   74684   Table *pTab;
   74685   Parse *pParse = 0;
   74686   Incrblob *pBlob = 0;
   74687 
   74688   flags = !!flags;                /* flags = (flags ? 1 : 0); */
   74689   *ppBlob = 0;
   74690 
   74691   sqlite3_mutex_enter(db->mutex);
   74692 
   74693   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
   74694   if( !pBlob ) goto blob_open_out;
   74695   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
   74696   if( !pParse ) goto blob_open_out;
   74697 
   74698   do {
   74699     memset(pParse, 0, sizeof(Parse));
   74700     pParse->db = db;
   74701     sqlite3DbFree(db, zErr);
   74702     zErr = 0;
   74703 
   74704     sqlite3BtreeEnterAll(db);
   74705     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
   74706     if( pTab && IsVirtual(pTab) ){
   74707       pTab = 0;
   74708       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
   74709     }
   74710     if( pTab && !HasRowid(pTab) ){
   74711       pTab = 0;
   74712       sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
   74713     }
   74714 #ifndef SQLITE_OMIT_VIEW
   74715     if( pTab && pTab->pSelect ){
   74716       pTab = 0;
   74717       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
   74718     }
   74719 #endif
   74720     if( !pTab ){
   74721       if( pParse->zErrMsg ){
   74722         sqlite3DbFree(db, zErr);
   74723         zErr = pParse->zErrMsg;
   74724         pParse->zErrMsg = 0;
   74725       }
   74726       rc = SQLITE_ERROR;
   74727       sqlite3BtreeLeaveAll(db);
   74728       goto blob_open_out;
   74729     }
   74730 
   74731     /* Now search pTab for the exact column. */
   74732     for(iCol=0; iCol<pTab->nCol; iCol++) {
   74733       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
   74734         break;
   74735       }
   74736     }
   74737     if( iCol==pTab->nCol ){
   74738       sqlite3DbFree(db, zErr);
   74739       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
   74740       rc = SQLITE_ERROR;
   74741       sqlite3BtreeLeaveAll(db);
   74742       goto blob_open_out;
   74743     }
   74744 
   74745     /* If the value is being opened for writing, check that the
   74746     ** column is not indexed, and that it is not part of a foreign key.
   74747     ** It is against the rules to open a column to which either of these
   74748     ** descriptions applies for writing.  */
   74749     if( flags ){
   74750       const char *zFault = 0;
   74751       Index *pIdx;
   74752 #ifndef SQLITE_OMIT_FOREIGN_KEY
   74753       if( db->flags&SQLITE_ForeignKeys ){
   74754         /* Check that the column is not part of an FK child key definition. It
   74755         ** is not necessary to check if it is part of a parent key, as parent
   74756         ** key columns must be indexed. The check below will pick up this
   74757         ** case.  */
   74758         FKey *pFKey;
   74759         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   74760           int j;
   74761           for(j=0; j<pFKey->nCol; j++){
   74762             if( pFKey->aCol[j].iFrom==iCol ){
   74763               zFault = "foreign key";
   74764             }
   74765           }
   74766         }
   74767       }
   74768 #endif
   74769       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   74770         int j;
   74771         for(j=0; j<pIdx->nKeyCol; j++){
   74772           if( pIdx->aiColumn[j]==iCol ){
   74773             zFault = "indexed";
   74774           }
   74775         }
   74776       }
   74777       if( zFault ){
   74778         sqlite3DbFree(db, zErr);
   74779         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
   74780         rc = SQLITE_ERROR;
   74781         sqlite3BtreeLeaveAll(db);
   74782         goto blob_open_out;
   74783       }
   74784     }
   74785 
   74786     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
   74787     assert( pBlob->pStmt || db->mallocFailed );
   74788     if( pBlob->pStmt ){
   74789       Vdbe *v = (Vdbe *)pBlob->pStmt;
   74790       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   74791 
   74792 
   74793       sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
   74794                            pTab->pSchema->schema_cookie,
   74795                            pTab->pSchema->iGeneration);
   74796       sqlite3VdbeChangeP5(v, 1);
   74797       sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
   74798 
   74799       /* Make sure a mutex is held on the table to be accessed */
   74800       sqlite3VdbeUsesBtree(v, iDb);
   74801 
   74802       /* Configure the OP_TableLock instruction */
   74803 #ifdef SQLITE_OMIT_SHARED_CACHE
   74804       sqlite3VdbeChangeToNoop(v, 1);
   74805 #else
   74806       sqlite3VdbeChangeP1(v, 1, iDb);
   74807       sqlite3VdbeChangeP2(v, 1, pTab->tnum);
   74808       sqlite3VdbeChangeP3(v, 1, flags);
   74809       sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
   74810 #endif
   74811 
   74812       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
   74813       ** parameter of the other to pTab->tnum.  */
   74814       sqlite3VdbeChangeToNoop(v, 3 - flags);
   74815       sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
   74816       sqlite3VdbeChangeP3(v, 2 + flags, iDb);
   74817 
   74818       /* Configure the number of columns. Configure the cursor to
   74819       ** think that the table has one more column than it really
   74820       ** does. An OP_Column to retrieve this imaginary column will
   74821       ** always return an SQL NULL. This is useful because it means
   74822       ** we can invoke OP_Column to fill in the vdbe cursors type
   74823       ** and offset cache without causing any IO.
   74824       */
   74825       sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
   74826       sqlite3VdbeChangeP2(v, 6, pTab->nCol);
   74827       if( !db->mallocFailed ){
   74828         pParse->nVar = 1;
   74829         pParse->nMem = 1;
   74830         pParse->nTab = 1;
   74831         sqlite3VdbeMakeReady(v, pParse);
   74832       }
   74833     }
   74834 
   74835     pBlob->flags = flags;
   74836     pBlob->iCol = iCol;
   74837     pBlob->db = db;
   74838     sqlite3BtreeLeaveAll(db);
   74839     if( db->mallocFailed ){
   74840       goto blob_open_out;
   74841     }
   74842     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
   74843     rc = blobSeekToRow(pBlob, iRow, &zErr);
   74844   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
   74845 
   74846 blob_open_out:
   74847   if( rc==SQLITE_OK && db->mallocFailed==0 ){
   74848     *ppBlob = (sqlite3_blob *)pBlob;
   74849   }else{
   74850     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
   74851     sqlite3DbFree(db, pBlob);
   74852   }
   74853   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   74854   sqlite3DbFree(db, zErr);
   74855   sqlite3ParserReset(pParse);
   74856   sqlite3StackFree(db, pParse);
   74857   rc = sqlite3ApiExit(db, rc);
   74858   sqlite3_mutex_leave(db->mutex);
   74859   return rc;
   74860 }
   74861 
   74862 /*
   74863 ** Close a blob handle that was previously created using
   74864 ** sqlite3_blob_open().
   74865 */
   74866 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
   74867   Incrblob *p = (Incrblob *)pBlob;
   74868   int rc;
   74869   sqlite3 *db;
   74870 
   74871   if( p ){
   74872     db = p->db;
   74873     sqlite3_mutex_enter(db->mutex);
   74874     rc = sqlite3_finalize(p->pStmt);
   74875     sqlite3DbFree(db, p);
   74876     sqlite3_mutex_leave(db->mutex);
   74877   }else{
   74878     rc = SQLITE_OK;
   74879   }
   74880   return rc;
   74881 }
   74882 
   74883 /*
   74884 ** Perform a read or write operation on a blob
   74885 */
   74886 static int blobReadWrite(
   74887   sqlite3_blob *pBlob,
   74888   void *z,
   74889   int n,
   74890   int iOffset,
   74891   int (*xCall)(BtCursor*, u32, u32, void*)
   74892 ){
   74893   int rc;
   74894   Incrblob *p = (Incrblob *)pBlob;
   74895   Vdbe *v;
   74896   sqlite3 *db;
   74897 
   74898   if( p==0 ) return SQLITE_MISUSE_BKPT;
   74899   db = p->db;
   74900   sqlite3_mutex_enter(db->mutex);
   74901   v = (Vdbe*)p->pStmt;
   74902 
   74903   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
   74904     /* Request is out of range. Return a transient error. */
   74905     rc = SQLITE_ERROR;
   74906     sqlite3Error(db, SQLITE_ERROR, 0);
   74907   }else if( v==0 ){
   74908     /* If there is no statement handle, then the blob-handle has
   74909     ** already been invalidated. Return SQLITE_ABORT in this case.
   74910     */
   74911     rc = SQLITE_ABORT;
   74912   }else{
   74913     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
   74914     ** returned, clean-up the statement handle.
   74915     */
   74916     assert( db == v->db );
   74917     sqlite3BtreeEnterCursor(p->pCsr);
   74918     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
   74919     sqlite3BtreeLeaveCursor(p->pCsr);
   74920     if( rc==SQLITE_ABORT ){
   74921       sqlite3VdbeFinalize(v);
   74922       p->pStmt = 0;
   74923     }else{
   74924       db->errCode = rc;
   74925       v->rc = rc;
   74926     }
   74927   }
   74928   rc = sqlite3ApiExit(db, rc);
   74929   sqlite3_mutex_leave(db->mutex);
   74930   return rc;
   74931 }
   74932 
   74933 /*
   74934 ** Read data from a blob handle.
   74935 */
   74936 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
   74937   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
   74938 }
   74939 
   74940 /*
   74941 ** Write data to a blob handle.
   74942 */
   74943 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
   74944   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
   74945 }
   74946 
   74947 /*
   74948 ** Query a blob handle for the size of the data.
   74949 **
   74950 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
   74951 ** so no mutex is required for access.
   74952 */
   74953 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
   74954   Incrblob *p = (Incrblob *)pBlob;
   74955   return (p && p->pStmt) ? p->nByte : 0;
   74956 }
   74957 
   74958 /*
   74959 ** Move an existing blob handle to point to a different row of the same
   74960 ** database table.
   74961 **
   74962 ** If an error occurs, or if the specified row does not exist or does not
   74963 ** contain a blob or text value, then an error code is returned and the
   74964 ** database handle error code and message set. If this happens, then all
   74965 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
   74966 ** immediately return SQLITE_ABORT.
   74967 */
   74968 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
   74969   int rc;
   74970   Incrblob *p = (Incrblob *)pBlob;
   74971   sqlite3 *db;
   74972 
   74973   if( p==0 ) return SQLITE_MISUSE_BKPT;
   74974   db = p->db;
   74975   sqlite3_mutex_enter(db->mutex);
   74976 
   74977   if( p->pStmt==0 ){
   74978     /* If there is no statement handle, then the blob-handle has
   74979     ** already been invalidated. Return SQLITE_ABORT in this case.
   74980     */
   74981     rc = SQLITE_ABORT;
   74982   }else{
   74983     char *zErr;
   74984     rc = blobSeekToRow(p, iRow, &zErr);
   74985     if( rc!=SQLITE_OK ){
   74986       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   74987       sqlite3DbFree(db, zErr);
   74988     }
   74989     assert( rc!=SQLITE_SCHEMA );
   74990   }
   74991 
   74992   rc = sqlite3ApiExit(db, rc);
   74993   assert( rc==SQLITE_OK || p->pStmt==0 );
   74994   sqlite3_mutex_leave(db->mutex);
   74995   return rc;
   74996 }
   74997 
   74998 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
   74999 
   75000 /************** End of vdbeblob.c ********************************************/
   75001 /************** Begin file vdbesort.c ****************************************/
   75002 /*
   75003 ** 2011 July 9
   75004 **
   75005 ** The author disclaims copyright to this source code.  In place of
   75006 ** a legal notice, here is a blessing:
   75007 **
   75008 **    May you do good and not evil.
   75009 **    May you find forgiveness for yourself and forgive others.
   75010 **    May you share freely, never taking more than you give.
   75011 **
   75012 *************************************************************************
   75013 ** This file contains code for the VdbeSorter object, used in concert with
   75014 ** a VdbeCursor to sort large numbers of keys (as may be required, for
   75015 ** example, by CREATE INDEX statements on tables too large to fit in main
   75016 ** memory).
   75017 */
   75018 
   75019 
   75020 
   75021 typedef struct VdbeSorterIter VdbeSorterIter;
   75022 typedef struct SorterRecord SorterRecord;
   75023 typedef struct FileWriter FileWriter;
   75024 
   75025 /*
   75026 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
   75027 **
   75028 ** As keys are added to the sorter, they are written to disk in a series
   75029 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
   75030 ** the same as the cache-size allowed for temporary databases. In order
   75031 ** to allow the caller to extract keys from the sorter in sorted order,
   75032 ** all PMAs currently stored on disk must be merged together. This comment
   75033 ** describes the data structure used to do so. The structure supports
   75034 ** merging any number of arrays in a single pass with no redundant comparison
   75035 ** operations.
   75036 **
   75037 ** The aIter[] array contains an iterator for each of the PMAs being merged.
   75038 ** An aIter[] iterator either points to a valid key or else is at EOF. For
   75039 ** the purposes of the paragraphs below, we assume that the array is actually
   75040 ** N elements in size, where N is the smallest power of 2 greater to or equal
   75041 ** to the number of iterators being merged. The extra aIter[] elements are
   75042 ** treated as if they are empty (always at EOF).
   75043 **
   75044 ** The aTree[] array is also N elements in size. The value of N is stored in
   75045 ** the VdbeSorter.nTree variable.
   75046 **
   75047 ** The final (N/2) elements of aTree[] contain the results of comparing
   75048 ** pairs of iterator keys together. Element i contains the result of
   75049 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
   75050 ** aTree element is set to the index of it.
   75051 **
   75052 ** For the purposes of this comparison, EOF is considered greater than any
   75053 ** other key value. If the keys are equal (only possible with two EOF
   75054 ** values), it doesn't matter which index is stored.
   75055 **
   75056 ** The (N/4) elements of aTree[] that precede the final (N/2) described
   75057 ** above contains the index of the smallest of each block of 4 iterators.
   75058 ** And so on. So that aTree[1] contains the index of the iterator that
   75059 ** currently points to the smallest key value. aTree[0] is unused.
   75060 **
   75061 ** Example:
   75062 **
   75063 **     aIter[0] -> Banana
   75064 **     aIter[1] -> Feijoa
   75065 **     aIter[2] -> Elderberry
   75066 **     aIter[3] -> Currant
   75067 **     aIter[4] -> Grapefruit
   75068 **     aIter[5] -> Apple
   75069 **     aIter[6] -> Durian
   75070 **     aIter[7] -> EOF
   75071 **
   75072 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
   75073 **
   75074 ** The current element is "Apple" (the value of the key indicated by
   75075 ** iterator 5). When the Next() operation is invoked, iterator 5 will
   75076 ** be advanced to the next key in its segment. Say the next key is
   75077 ** "Eggplant":
   75078 **
   75079 **     aIter[5] -> Eggplant
   75080 **
   75081 ** The contents of aTree[] are updated first by comparing the new iterator
   75082 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
   75083 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
   75084 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
   75085 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
   75086 ** so the value written into element 1 of the array is 0. As follows:
   75087 **
   75088 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
   75089 **
   75090 ** In other words, each time we advance to the next sorter element, log2(N)
   75091 ** key comparison operations are required, where N is the number of segments
   75092 ** being merged (rounded up to the next power of 2).
   75093 */
   75094 struct VdbeSorter {
   75095   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
   75096   i64 iReadOff;                   /* Current read offset within file pTemp1 */
   75097   int nInMemory;                  /* Current size of pRecord list as PMA */
   75098   int nTree;                      /* Used size of aTree/aIter (power of 2) */
   75099   int nPMA;                       /* Number of PMAs stored in pTemp1 */
   75100   int mnPmaSize;                  /* Minimum PMA size, in bytes */
   75101   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
   75102   VdbeSorterIter *aIter;          /* Array of iterators to merge */
   75103   int *aTree;                     /* Current state of incremental merge */
   75104   sqlite3_file *pTemp1;           /* PMA file 1 */
   75105   SorterRecord *pRecord;          /* Head of in-memory record list */
   75106   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
   75107 };
   75108 
   75109 /*
   75110 ** The following type is an iterator for a PMA. It caches the current key in
   75111 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
   75112 */
   75113 struct VdbeSorterIter {
   75114   i64 iReadOff;                   /* Current read offset */
   75115   i64 iEof;                       /* 1 byte past EOF for this iterator */
   75116   int nAlloc;                     /* Bytes of space at aAlloc */
   75117   int nKey;                       /* Number of bytes in key */
   75118   sqlite3_file *pFile;            /* File iterator is reading from */
   75119   u8 *aAlloc;                     /* Allocated space */
   75120   u8 *aKey;                       /* Pointer to current key */
   75121   u8 *aBuffer;                    /* Current read buffer */
   75122   int nBuffer;                    /* Size of read buffer in bytes */
   75123 };
   75124 
   75125 /*
   75126 ** An instance of this structure is used to organize the stream of records
   75127 ** being written to files by the merge-sort code into aligned, page-sized
   75128 ** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
   75129 ** faster on many operating systems.
   75130 */
   75131 struct FileWriter {
   75132   int eFWErr;                     /* Non-zero if in an error state */
   75133   u8 *aBuffer;                    /* Pointer to write buffer */
   75134   int nBuffer;                    /* Size of write buffer in bytes */
   75135   int iBufStart;                  /* First byte of buffer to write */
   75136   int iBufEnd;                    /* Last byte of buffer to write */
   75137   i64 iWriteOff;                  /* Offset of start of buffer in file */
   75138   sqlite3_file *pFile;            /* File to write to */
   75139 };
   75140 
   75141 /*
   75142 ** A structure to store a single record. All in-memory records are connected
   75143 ** together into a linked list headed at VdbeSorter.pRecord using the
   75144 ** SorterRecord.pNext pointer.
   75145 */
   75146 struct SorterRecord {
   75147   void *pVal;
   75148   int nVal;
   75149   SorterRecord *pNext;
   75150 };
   75151 
   75152 /* Minimum allowable value for the VdbeSorter.nWorking variable */
   75153 #define SORTER_MIN_WORKING 10
   75154 
   75155 /* Maximum number of segments to merge in a single pass. */
   75156 #define SORTER_MAX_MERGE_COUNT 16
   75157 
   75158 /*
   75159 ** Free all memory belonging to the VdbeSorterIter object passed as the second
   75160 ** argument. All structure fields are set to zero before returning.
   75161 */
   75162 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
   75163   sqlite3DbFree(db, pIter->aAlloc);
   75164   sqlite3DbFree(db, pIter->aBuffer);
   75165   memset(pIter, 0, sizeof(VdbeSorterIter));
   75166 }
   75167 
   75168 /*
   75169 ** Read nByte bytes of data from the stream of data iterated by object p.
   75170 ** If successful, set *ppOut to point to a buffer containing the data
   75171 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
   75172 ** error code.
   75173 **
   75174 ** The buffer indicated by *ppOut may only be considered valid until the
   75175 ** next call to this function.
   75176 */
   75177 static int vdbeSorterIterRead(
   75178   sqlite3 *db,                    /* Database handle (for malloc) */
   75179   VdbeSorterIter *p,              /* Iterator */
   75180   int nByte,                      /* Bytes of data to read */
   75181   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
   75182 ){
   75183   int iBuf;                       /* Offset within buffer to read from */
   75184   int nAvail;                     /* Bytes of data available in buffer */
   75185   assert( p->aBuffer );
   75186 
   75187   /* If there is no more data to be read from the buffer, read the next
   75188   ** p->nBuffer bytes of data from the file into it. Or, if there are less
   75189   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
   75190   iBuf = p->iReadOff % p->nBuffer;
   75191   if( iBuf==0 ){
   75192     int nRead;                    /* Bytes to read from disk */
   75193     int rc;                       /* sqlite3OsRead() return code */
   75194 
   75195     /* Determine how many bytes of data to read. */
   75196     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
   75197       nRead = p->nBuffer;
   75198     }else{
   75199       nRead = (int)(p->iEof - p->iReadOff);
   75200     }
   75201     assert( nRead>0 );
   75202 
   75203     /* Read data from the file. Return early if an error occurs. */
   75204     rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
   75205     assert( rc!=SQLITE_IOERR_SHORT_READ );
   75206     if( rc!=SQLITE_OK ) return rc;
   75207   }
   75208   nAvail = p->nBuffer - iBuf;
   75209 
   75210   if( nByte<=nAvail ){
   75211     /* The requested data is available in the in-memory buffer. In this
   75212     ** case there is no need to make a copy of the data, just return a
   75213     ** pointer into the buffer to the caller.  */
   75214     *ppOut = &p->aBuffer[iBuf];
   75215     p->iReadOff += nByte;
   75216   }else{
   75217     /* The requested data is not all available in the in-memory buffer.
   75218     ** In this case, allocate space at p->aAlloc[] to copy the requested
   75219     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
   75220     int nRem;                     /* Bytes remaining to copy */
   75221 
   75222     /* Extend the p->aAlloc[] allocation if required. */
   75223     if( p->nAlloc<nByte ){
   75224       int nNew = p->nAlloc*2;
   75225       while( nByte>nNew ) nNew = nNew*2;
   75226       p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
   75227       if( !p->aAlloc ) return SQLITE_NOMEM;
   75228       p->nAlloc = nNew;
   75229     }
   75230 
   75231     /* Copy as much data as is available in the buffer into the start of
   75232     ** p->aAlloc[].  */
   75233     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
   75234     p->iReadOff += nAvail;
   75235     nRem = nByte - nAvail;
   75236 
   75237     /* The following loop copies up to p->nBuffer bytes per iteration into
   75238     ** the p->aAlloc[] buffer.  */
   75239     while( nRem>0 ){
   75240       int rc;                     /* vdbeSorterIterRead() return code */
   75241       int nCopy;                  /* Number of bytes to copy */
   75242       u8 *aNext;                  /* Pointer to buffer to copy data from */
   75243 
   75244       nCopy = nRem;
   75245       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
   75246       rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
   75247       if( rc!=SQLITE_OK ) return rc;
   75248       assert( aNext!=p->aAlloc );
   75249       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
   75250       nRem -= nCopy;
   75251     }
   75252 
   75253     *ppOut = p->aAlloc;
   75254   }
   75255 
   75256   return SQLITE_OK;
   75257 }
   75258 
   75259 /*
   75260 ** Read a varint from the stream of data accessed by p. Set *pnOut to
   75261 ** the value read.
   75262 */
   75263 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
   75264   int iBuf;
   75265 
   75266   iBuf = p->iReadOff % p->nBuffer;
   75267   if( iBuf && (p->nBuffer-iBuf)>=9 ){
   75268     p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
   75269   }else{
   75270     u8 aVarint[16], *a;
   75271     int i = 0, rc;
   75272     do{
   75273       rc = vdbeSorterIterRead(db, p, 1, &a);
   75274       if( rc ) return rc;
   75275       aVarint[(i++)&0xf] = a[0];
   75276     }while( (a[0]&0x80)!=0 );
   75277     sqlite3GetVarint(aVarint, pnOut);
   75278   }
   75279 
   75280   return SQLITE_OK;
   75281 }
   75282 
   75283 
   75284 /*
   75285 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
   75286 ** no error occurs, or an SQLite error code if one does.
   75287 */
   75288 static int vdbeSorterIterNext(
   75289   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
   75290   VdbeSorterIter *pIter           /* Iterator to advance */
   75291 ){
   75292   int rc;                         /* Return Code */
   75293   u64 nRec = 0;                   /* Size of record in bytes */
   75294 
   75295   if( pIter->iReadOff>=pIter->iEof ){
   75296     /* This is an EOF condition */
   75297     vdbeSorterIterZero(db, pIter);
   75298     return SQLITE_OK;
   75299   }
   75300 
   75301   rc = vdbeSorterIterVarint(db, pIter, &nRec);
   75302   if( rc==SQLITE_OK ){
   75303     pIter->nKey = (int)nRec;
   75304     rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
   75305   }
   75306 
   75307   return rc;
   75308 }
   75309 
   75310 /*
   75311 ** Initialize iterator pIter to scan through the PMA stored in file pFile
   75312 ** starting at offset iStart and ending at offset iEof-1. This function
   75313 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
   75314 ** PMA is empty).
   75315 */
   75316 static int vdbeSorterIterInit(
   75317   sqlite3 *db,                    /* Database handle */
   75318   const VdbeSorter *pSorter,      /* Sorter object */
   75319   i64 iStart,                     /* Start offset in pFile */
   75320   VdbeSorterIter *pIter,          /* Iterator to populate */
   75321   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
   75322 ){
   75323   int rc = SQLITE_OK;
   75324   int nBuf;
   75325 
   75326   nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   75327 
   75328   assert( pSorter->iWriteOff>iStart );
   75329   assert( pIter->aAlloc==0 );
   75330   assert( pIter->aBuffer==0 );
   75331   pIter->pFile = pSorter->pTemp1;
   75332   pIter->iReadOff = iStart;
   75333   pIter->nAlloc = 128;
   75334   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
   75335   pIter->nBuffer = nBuf;
   75336   pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
   75337 
   75338   if( !pIter->aBuffer ){
   75339     rc = SQLITE_NOMEM;
   75340   }else{
   75341     int iBuf;
   75342 
   75343     iBuf = iStart % nBuf;
   75344     if( iBuf ){
   75345       int nRead = nBuf - iBuf;
   75346       if( (iStart + nRead) > pSorter->iWriteOff ){
   75347         nRead = (int)(pSorter->iWriteOff - iStart);
   75348       }
   75349       rc = sqlite3OsRead(
   75350           pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
   75351       );
   75352     }
   75353 
   75354     if( rc==SQLITE_OK ){
   75355       u64 nByte;                       /* Size of PMA in bytes */
   75356       pIter->iEof = pSorter->iWriteOff;
   75357       rc = vdbeSorterIterVarint(db, pIter, &nByte);
   75358       pIter->iEof = pIter->iReadOff + nByte;
   75359       *pnByte += nByte;
   75360     }
   75361   }
   75362 
   75363   if( rc==SQLITE_OK ){
   75364     rc = vdbeSorterIterNext(db, pIter);
   75365   }
   75366   return rc;
   75367 }
   75368 
   75369 
   75370 /*
   75371 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
   75372 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
   75373 ** used by the comparison. If an error occurs, return an SQLite error code.
   75374 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
   75375 ** value, depending on whether key1 is smaller, equal to or larger than key2.
   75376 **
   75377 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
   75378 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
   75379 ** is true and key1 contains even a single NULL value, it is considered to
   75380 ** be less than key2. Even if key2 also contains NULL values.
   75381 **
   75382 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
   75383 ** has been allocated and contains an unpacked record that is used as key2.
   75384 */
   75385 static void vdbeSorterCompare(
   75386   const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
   75387   int nKeyCol,                    /* Num of columns. 0 means "all" */
   75388   const void *pKey1, int nKey1,   /* Left side of comparison */
   75389   const void *pKey2, int nKey2,   /* Right side of comparison */
   75390   int *pRes                       /* OUT: Result of comparison */
   75391 ){
   75392   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
   75393   VdbeSorter *pSorter = pCsr->pSorter;
   75394   UnpackedRecord *r2 = pSorter->pUnpacked;
   75395   int i;
   75396 
   75397   if( pKey2 ){
   75398     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
   75399   }
   75400 
   75401   if( nKeyCol ){
   75402     r2->nField = nKeyCol;
   75403     for(i=0; i<nKeyCol; i++){
   75404       if( r2->aMem[i].flags & MEM_Null ){
   75405         *pRes = -1;
   75406         return;
   75407       }
   75408     }
   75409     assert( r2->default_rc==0 );
   75410   }
   75411 
   75412   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2, 0);
   75413 }
   75414 
   75415 /*
   75416 ** This function is called to compare two iterator keys when merging
   75417 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
   75418 ** value to recalculate.
   75419 */
   75420 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
   75421   VdbeSorter *pSorter = pCsr->pSorter;
   75422   int i1;
   75423   int i2;
   75424   int iRes;
   75425   VdbeSorterIter *p1;
   75426   VdbeSorterIter *p2;
   75427 
   75428   assert( iOut<pSorter->nTree && iOut>0 );
   75429 
   75430   if( iOut>=(pSorter->nTree/2) ){
   75431     i1 = (iOut - pSorter->nTree/2) * 2;
   75432     i2 = i1 + 1;
   75433   }else{
   75434     i1 = pSorter->aTree[iOut*2];
   75435     i2 = pSorter->aTree[iOut*2+1];
   75436   }
   75437 
   75438   p1 = &pSorter->aIter[i1];
   75439   p2 = &pSorter->aIter[i2];
   75440 
   75441   if( p1->pFile==0 ){
   75442     iRes = i2;
   75443   }else if( p2->pFile==0 ){
   75444     iRes = i1;
   75445   }else{
   75446     int res;
   75447     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
   75448     vdbeSorterCompare(
   75449         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
   75450     );
   75451     if( res<=0 ){
   75452       iRes = i1;
   75453     }else{
   75454       iRes = i2;
   75455     }
   75456   }
   75457 
   75458   pSorter->aTree[iOut] = iRes;
   75459   return SQLITE_OK;
   75460 }
   75461 
   75462 /*
   75463 ** Initialize the temporary index cursor just opened as a sorter cursor.
   75464 */
   75465 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
   75466   int pgsz;                       /* Page size of main database */
   75467   int mxCache;                    /* Cache size */
   75468   VdbeSorter *pSorter;            /* The new sorter */
   75469   char *d;                        /* Dummy */
   75470 
   75471   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
   75472   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
   75473   if( pSorter==0 ){
   75474     return SQLITE_NOMEM;
   75475   }
   75476 
   75477   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
   75478   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
   75479   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
   75480 
   75481   if( !sqlite3TempInMemory(db) ){
   75482     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   75483     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
   75484     mxCache = db->aDb[0].pSchema->cache_size;
   75485     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
   75486     pSorter->mxPmaSize = mxCache * pgsz;
   75487   }
   75488 
   75489   return SQLITE_OK;
   75490 }
   75491 
   75492 /*
   75493 ** Free the list of sorted records starting at pRecord.
   75494 */
   75495 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
   75496   SorterRecord *p;
   75497   SorterRecord *pNext;
   75498   for(p=pRecord; p; p=pNext){
   75499     pNext = p->pNext;
   75500     sqlite3DbFree(db, p);
   75501   }
   75502 }
   75503 
   75504 /*
   75505 ** Reset a sorting cursor back to its original empty state.
   75506 */
   75507 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
   75508   if( pSorter->aIter ){
   75509     int i;
   75510     for(i=0; i<pSorter->nTree; i++){
   75511       vdbeSorterIterZero(db, &pSorter->aIter[i]);
   75512     }
   75513     sqlite3DbFree(db, pSorter->aIter);
   75514     pSorter->aIter = 0;
   75515   }
   75516   if( pSorter->pTemp1 ){
   75517     sqlite3OsCloseFree(pSorter->pTemp1);
   75518     pSorter->pTemp1 = 0;
   75519   }
   75520   vdbeSorterRecordFree(db, pSorter->pRecord);
   75521   pSorter->pRecord = 0;
   75522   pSorter->iWriteOff = 0;
   75523   pSorter->iReadOff = 0;
   75524   pSorter->nInMemory = 0;
   75525   pSorter->nTree = 0;
   75526   pSorter->nPMA = 0;
   75527   pSorter->aTree = 0;
   75528 }
   75529 
   75530 
   75531 /*
   75532 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
   75533 */
   75534 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
   75535   VdbeSorter *pSorter = pCsr->pSorter;
   75536   if( pSorter ){
   75537     sqlite3VdbeSorterReset(db, pSorter);
   75538     sqlite3DbFree(db, pSorter->pUnpacked);
   75539     sqlite3DbFree(db, pSorter);
   75540     pCsr->pSorter = 0;
   75541   }
   75542 }
   75543 
   75544 /*
   75545 ** Allocate space for a file-handle and open a temporary file. If successful,
   75546 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
   75547 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
   75548 */
   75549 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
   75550   int dummy;
   75551   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
   75552       SQLITE_OPEN_TEMP_JOURNAL |
   75553       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
   75554       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
   75555   );
   75556 }
   75557 
   75558 /*
   75559 ** Merge the two sorted lists p1 and p2 into a single list.
   75560 ** Set *ppOut to the head of the new list.
   75561 */
   75562 static void vdbeSorterMerge(
   75563   const VdbeCursor *pCsr,         /* For pKeyInfo */
   75564   SorterRecord *p1,               /* First list to merge */
   75565   SorterRecord *p2,               /* Second list to merge */
   75566   SorterRecord **ppOut            /* OUT: Head of merged list */
   75567 ){
   75568   SorterRecord *pFinal = 0;
   75569   SorterRecord **pp = &pFinal;
   75570   void *pVal2 = p2 ? p2->pVal : 0;
   75571 
   75572   while( p1 && p2 ){
   75573     int res;
   75574     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
   75575     if( res<=0 ){
   75576       *pp = p1;
   75577       pp = &p1->pNext;
   75578       p1 = p1->pNext;
   75579       pVal2 = 0;
   75580     }else{
   75581       *pp = p2;
   75582        pp = &p2->pNext;
   75583       p2 = p2->pNext;
   75584       if( p2==0 ) break;
   75585       pVal2 = p2->pVal;
   75586     }
   75587   }
   75588   *pp = p1 ? p1 : p2;
   75589   *ppOut = pFinal;
   75590 }
   75591 
   75592 /*
   75593 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
   75594 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
   75595 ** occurs.
   75596 */
   75597 static int vdbeSorterSort(const VdbeCursor *pCsr){
   75598   int i;
   75599   SorterRecord **aSlot;
   75600   SorterRecord *p;
   75601   VdbeSorter *pSorter = pCsr->pSorter;
   75602 
   75603   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
   75604   if( !aSlot ){
   75605     return SQLITE_NOMEM;
   75606   }
   75607 
   75608   p = pSorter->pRecord;
   75609   while( p ){
   75610     SorterRecord *pNext = p->pNext;
   75611     p->pNext = 0;
   75612     for(i=0; aSlot[i]; i++){
   75613       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
   75614       aSlot[i] = 0;
   75615     }
   75616     aSlot[i] = p;
   75617     p = pNext;
   75618   }
   75619 
   75620   p = 0;
   75621   for(i=0; i<64; i++){
   75622     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
   75623   }
   75624   pSorter->pRecord = p;
   75625 
   75626   sqlite3_free(aSlot);
   75627   return SQLITE_OK;
   75628 }
   75629 
   75630 /*
   75631 ** Initialize a file-writer object.
   75632 */
   75633 static void fileWriterInit(
   75634   sqlite3 *db,                    /* Database (for malloc) */
   75635   sqlite3_file *pFile,            /* File to write to */
   75636   FileWriter *p,                  /* Object to populate */
   75637   i64 iStart                      /* Offset of pFile to begin writing at */
   75638 ){
   75639   int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   75640 
   75641   memset(p, 0, sizeof(FileWriter));
   75642   p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
   75643   if( !p->aBuffer ){
   75644     p->eFWErr = SQLITE_NOMEM;
   75645   }else{
   75646     p->iBufEnd = p->iBufStart = (iStart % nBuf);
   75647     p->iWriteOff = iStart - p->iBufStart;
   75648     p->nBuffer = nBuf;
   75649     p->pFile = pFile;
   75650   }
   75651 }
   75652 
   75653 /*
   75654 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
   75655 ** if successful, or an SQLite error code if an error occurs.
   75656 */
   75657 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
   75658   int nRem = nData;
   75659   while( nRem>0 && p->eFWErr==0 ){
   75660     int nCopy = nRem;
   75661     if( nCopy>(p->nBuffer - p->iBufEnd) ){
   75662       nCopy = p->nBuffer - p->iBufEnd;
   75663     }
   75664 
   75665     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
   75666     p->iBufEnd += nCopy;
   75667     if( p->iBufEnd==p->nBuffer ){
   75668       p->eFWErr = sqlite3OsWrite(p->pFile,
   75669           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
   75670           p->iWriteOff + p->iBufStart
   75671       );
   75672       p->iBufStart = p->iBufEnd = 0;
   75673       p->iWriteOff += p->nBuffer;
   75674     }
   75675     assert( p->iBufEnd<p->nBuffer );
   75676 
   75677     nRem -= nCopy;
   75678   }
   75679 }
   75680 
   75681 /*
   75682 ** Flush any buffered data to disk and clean up the file-writer object.
   75683 ** The results of using the file-writer after this call are undefined.
   75684 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
   75685 ** required. Otherwise, return an SQLite error code.
   75686 **
   75687 ** Before returning, set *piEof to the offset immediately following the
   75688 ** last byte written to the file.
   75689 */
   75690 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
   75691   int rc;
   75692   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
   75693     p->eFWErr = sqlite3OsWrite(p->pFile,
   75694         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
   75695         p->iWriteOff + p->iBufStart
   75696     );
   75697   }
   75698   *piEof = (p->iWriteOff + p->iBufEnd);
   75699   sqlite3DbFree(db, p->aBuffer);
   75700   rc = p->eFWErr;
   75701   memset(p, 0, sizeof(FileWriter));
   75702   return rc;
   75703 }
   75704 
   75705 /*
   75706 ** Write value iVal encoded as a varint to the file-write object. Return
   75707 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
   75708 */
   75709 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
   75710   int nByte;
   75711   u8 aByte[10];
   75712   nByte = sqlite3PutVarint(aByte, iVal);
   75713   fileWriterWrite(p, aByte, nByte);
   75714 }
   75715 
   75716 /*
   75717 ** Write the current contents of the in-memory linked-list to a PMA. Return
   75718 ** SQLITE_OK if successful, or an SQLite error code otherwise.
   75719 **
   75720 ** The format of a PMA is:
   75721 **
   75722 **     * A varint. This varint contains the total number of bytes of content
   75723 **       in the PMA (not including the varint itself).
   75724 **
   75725 **     * One or more records packed end-to-end in order of ascending keys.
   75726 **       Each record consists of a varint followed by a blob of data (the
   75727 **       key). The varint is the number of bytes in the blob of data.
   75728 */
   75729 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
   75730   int rc = SQLITE_OK;             /* Return code */
   75731   VdbeSorter *pSorter = pCsr->pSorter;
   75732   FileWriter writer;
   75733 
   75734   memset(&writer, 0, sizeof(FileWriter));
   75735 
   75736   if( pSorter->nInMemory==0 ){
   75737     assert( pSorter->pRecord==0 );
   75738     return rc;
   75739   }
   75740 
   75741   rc = vdbeSorterSort(pCsr);
   75742 
   75743   /* If the first temporary PMA file has not been opened, open it now. */
   75744   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
   75745     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
   75746     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
   75747     assert( pSorter->iWriteOff==0 );
   75748     assert( pSorter->nPMA==0 );
   75749   }
   75750 
   75751   if( rc==SQLITE_OK ){
   75752     SorterRecord *p;
   75753     SorterRecord *pNext = 0;
   75754 
   75755     fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
   75756     pSorter->nPMA++;
   75757     fileWriterWriteVarint(&writer, pSorter->nInMemory);
   75758     for(p=pSorter->pRecord; p; p=pNext){
   75759       pNext = p->pNext;
   75760       fileWriterWriteVarint(&writer, p->nVal);
   75761       fileWriterWrite(&writer, p->pVal, p->nVal);
   75762       sqlite3DbFree(db, p);
   75763     }
   75764     pSorter->pRecord = p;
   75765     rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
   75766   }
   75767 
   75768   return rc;
   75769 }
   75770 
   75771 /*
   75772 ** Add a record to the sorter.
   75773 */
   75774 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
   75775   sqlite3 *db,                    /* Database handle */
   75776   const VdbeCursor *pCsr,               /* Sorter cursor */
   75777   Mem *pVal                       /* Memory cell containing record */
   75778 ){
   75779   VdbeSorter *pSorter = pCsr->pSorter;
   75780   int rc = SQLITE_OK;             /* Return Code */
   75781   SorterRecord *pNew;             /* New list element */
   75782 
   75783   assert( pSorter );
   75784   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
   75785 
   75786   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
   75787   if( pNew==0 ){
   75788     rc = SQLITE_NOMEM;
   75789   }else{
   75790     pNew->pVal = (void *)&pNew[1];
   75791     memcpy(pNew->pVal, pVal->z, pVal->n);
   75792     pNew->nVal = pVal->n;
   75793     pNew->pNext = pSorter->pRecord;
   75794     pSorter->pRecord = pNew;
   75795   }
   75796 
   75797   /* See if the contents of the sorter should now be written out. They
   75798   ** are written out when either of the following are true:
   75799   **
   75800   **   * The total memory allocated for the in-memory list is greater
   75801   **     than (page-size * cache-size), or
   75802   **
   75803   **   * The total memory allocated for the in-memory list is greater
   75804   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
   75805   */
   75806   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
   75807         (pSorter->nInMemory>pSorter->mxPmaSize)
   75808      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
   75809   )){
   75810 #ifdef SQLITE_DEBUG
   75811     i64 nExpect = pSorter->iWriteOff
   75812                 + sqlite3VarintLen(pSorter->nInMemory)
   75813                 + pSorter->nInMemory;
   75814 #endif
   75815     rc = vdbeSorterListToPMA(db, pCsr);
   75816     pSorter->nInMemory = 0;
   75817     assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
   75818   }
   75819 
   75820   return rc;
   75821 }
   75822 
   75823 /*
   75824 ** Helper function for sqlite3VdbeSorterRewind().
   75825 */
   75826 static int vdbeSorterInitMerge(
   75827   sqlite3 *db,                    /* Database handle */
   75828   const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
   75829   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
   75830 ){
   75831   VdbeSorter *pSorter = pCsr->pSorter;
   75832   int rc = SQLITE_OK;             /* Return code */
   75833   int i;                          /* Used to iterator through aIter[] */
   75834   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
   75835 
   75836   /* Initialize the iterators. */
   75837   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
   75838     VdbeSorterIter *pIter = &pSorter->aIter[i];
   75839     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
   75840     pSorter->iReadOff = pIter->iEof;
   75841     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
   75842     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
   75843   }
   75844 
   75845   /* Initialize the aTree[] array. */
   75846   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
   75847     rc = vdbeSorterDoCompare(pCsr, i);
   75848   }
   75849 
   75850   *pnByte = nByte;
   75851   return rc;
   75852 }
   75853 
   75854 /*
   75855 ** Once the sorter has been populated, this function is called to prepare
   75856 ** for iterating through its contents in sorted order.
   75857 */
   75858 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
   75859   VdbeSorter *pSorter = pCsr->pSorter;
   75860   int rc;                         /* Return code */
   75861   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
   75862   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
   75863   int nIter;                      /* Number of iterators used */
   75864   int nByte;                      /* Bytes of space required for aIter/aTree */
   75865   int N = 2;                      /* Power of 2 >= nIter */
   75866 
   75867   assert( pSorter );
   75868 
   75869   /* If no data has been written to disk, then do not do so now. Instead,
   75870   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
   75871   ** from the in-memory list.  */
   75872   if( pSorter->nPMA==0 ){
   75873     *pbEof = !pSorter->pRecord;
   75874     assert( pSorter->aTree==0 );
   75875     return vdbeSorterSort(pCsr);
   75876   }
   75877 
   75878   /* Write the current in-memory list to a PMA. */
   75879   rc = vdbeSorterListToPMA(db, pCsr);
   75880   if( rc!=SQLITE_OK ) return rc;
   75881 
   75882   /* Allocate space for aIter[] and aTree[]. */
   75883   nIter = pSorter->nPMA;
   75884   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
   75885   assert( nIter>0 );
   75886   while( N<nIter ) N += N;
   75887   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
   75888   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
   75889   if( !pSorter->aIter ) return SQLITE_NOMEM;
   75890   pSorter->aTree = (int *)&pSorter->aIter[N];
   75891   pSorter->nTree = N;
   75892 
   75893   do {
   75894     int iNew;                     /* Index of new, merged, PMA */
   75895 
   75896     for(iNew=0;
   75897         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
   75898         iNew++
   75899     ){
   75900       int rc2;                    /* Return code from fileWriterFinish() */
   75901       FileWriter writer;          /* Object used to write to disk */
   75902       i64 nWrite;                 /* Number of bytes in new PMA */
   75903 
   75904       memset(&writer, 0, sizeof(FileWriter));
   75905 
   75906       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
   75907       ** initialize an iterator for each of them and break out of the loop.
   75908       ** These iterators will be incrementally merged as the VDBE layer calls
   75909       ** sqlite3VdbeSorterNext().
   75910       **
   75911       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
   75912       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
   75913       ** are merged into a single PMA that is written to file pTemp2.
   75914       */
   75915       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
   75916       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
   75917       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
   75918         break;
   75919       }
   75920 
   75921       /* Open the second temp file, if it is not already open. */
   75922       if( pTemp2==0 ){
   75923         assert( iWrite2==0 );
   75924         rc = vdbeSorterOpenTempFile(db, &pTemp2);
   75925       }
   75926 
   75927       if( rc==SQLITE_OK ){
   75928         int bEof = 0;
   75929         fileWriterInit(db, pTemp2, &writer, iWrite2);
   75930         fileWriterWriteVarint(&writer, nWrite);
   75931         while( rc==SQLITE_OK && bEof==0 ){
   75932           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
   75933           assert( pIter->pFile );
   75934 
   75935           fileWriterWriteVarint(&writer, pIter->nKey);
   75936           fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
   75937           rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
   75938         }
   75939         rc2 = fileWriterFinish(db, &writer, &iWrite2);
   75940         if( rc==SQLITE_OK ) rc = rc2;
   75941       }
   75942     }
   75943 
   75944     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
   75945       break;
   75946     }else{
   75947       sqlite3_file *pTmp = pSorter->pTemp1;
   75948       pSorter->nPMA = iNew;
   75949       pSorter->pTemp1 = pTemp2;
   75950       pTemp2 = pTmp;
   75951       pSorter->iWriteOff = iWrite2;
   75952       pSorter->iReadOff = 0;
   75953       iWrite2 = 0;
   75954     }
   75955   }while( rc==SQLITE_OK );
   75956 
   75957   if( pTemp2 ){
   75958     sqlite3OsCloseFree(pTemp2);
   75959   }
   75960   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
   75961   return rc;
   75962 }
   75963 
   75964 /*
   75965 ** Advance to the next element in the sorter.
   75966 */
   75967 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
   75968   VdbeSorter *pSorter = pCsr->pSorter;
   75969   int rc;                         /* Return code */
   75970 
   75971   if( pSorter->aTree ){
   75972     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
   75973     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
   75974     if( rc==SQLITE_OK ){
   75975       int i;                      /* Index of aTree[] to recalculate */
   75976       VdbeSorterIter *pIter1;     /* First iterator to compare */
   75977       VdbeSorterIter *pIter2;     /* Second iterator to compare */
   75978       u8 *pKey2;                  /* To pIter2->aKey, or 0 if record cached */
   75979 
   75980       /* Find the first two iterators to compare. The one that was just
   75981       ** advanced (iPrev) and the one next to it in the array.  */
   75982       pIter1 = &pSorter->aIter[(iPrev & 0xFFFE)];
   75983       pIter2 = &pSorter->aIter[(iPrev | 0x0001)];
   75984       pKey2 = pIter2->aKey;
   75985 
   75986       for(i=(pSorter->nTree+iPrev)/2; i>0; i=i/2){
   75987         /* Compare pIter1 and pIter2. Store the result in variable iRes. */
   75988         int iRes;
   75989         if( pIter1->pFile==0 ){
   75990           iRes = +1;
   75991         }else if( pIter2->pFile==0 ){
   75992           iRes = -1;
   75993         }else{
   75994           vdbeSorterCompare(pCsr, 0,
   75995               pIter1->aKey, pIter1->nKey, pKey2, pIter2->nKey, &iRes
   75996           );
   75997         }
   75998 
   75999         /* If pIter1 contained the smaller value, set aTree[i] to its index.
   76000         ** Then set pIter2 to the next iterator to compare to pIter1. In this
   76001         ** case there is no cache of pIter2 in pSorter->pUnpacked, so set
   76002         ** pKey2 to point to the record belonging to pIter2.
   76003         **
   76004         ** Alternatively, if pIter2 contains the smaller of the two values,
   76005         ** set aTree[i] to its index and update pIter1. If vdbeSorterCompare()
   76006         ** was actually called above, then pSorter->pUnpacked now contains
   76007         ** a value equivalent to pIter2. So set pKey2 to NULL to prevent
   76008         ** vdbeSorterCompare() from decoding pIter2 again.  */
   76009         if( iRes<=0 ){
   76010           pSorter->aTree[i] = (int)(pIter1 - pSorter->aIter);
   76011           pIter2 = &pSorter->aIter[ pSorter->aTree[i ^ 0x0001] ];
   76012           pKey2 = pIter2->aKey;
   76013         }else{
   76014           if( pIter1->pFile ) pKey2 = 0;
   76015           pSorter->aTree[i] = (int)(pIter2 - pSorter->aIter);
   76016           pIter1 = &pSorter->aIter[ pSorter->aTree[i ^ 0x0001] ];
   76017         }
   76018 
   76019       }
   76020       *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
   76021     }
   76022   }else{
   76023     SorterRecord *pFree = pSorter->pRecord;
   76024     pSorter->pRecord = pFree->pNext;
   76025     pFree->pNext = 0;
   76026     vdbeSorterRecordFree(db, pFree);
   76027     *pbEof = !pSorter->pRecord;
   76028     rc = SQLITE_OK;
   76029   }
   76030   return rc;
   76031 }
   76032 
   76033 /*
   76034 ** Return a pointer to a buffer owned by the sorter that contains the
   76035 ** current key.
   76036 */
   76037 static void *vdbeSorterRowkey(
   76038   const VdbeSorter *pSorter,      /* Sorter object */
   76039   int *pnKey                      /* OUT: Size of current key in bytes */
   76040 ){
   76041   void *pKey;
   76042   if( pSorter->aTree ){
   76043     VdbeSorterIter *pIter;
   76044     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
   76045     *pnKey = pIter->nKey;
   76046     pKey = pIter->aKey;
   76047   }else{
   76048     *pnKey = pSorter->pRecord->nVal;
   76049     pKey = pSorter->pRecord->pVal;
   76050   }
   76051   return pKey;
   76052 }
   76053 
   76054 /*
   76055 ** Copy the current sorter key into the memory cell pOut.
   76056 */
   76057 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
   76058   VdbeSorter *pSorter = pCsr->pSorter;
   76059   void *pKey; int nKey;           /* Sorter key to copy into pOut */
   76060 
   76061   pKey = vdbeSorterRowkey(pSorter, &nKey);
   76062   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
   76063     return SQLITE_NOMEM;
   76064   }
   76065   pOut->n = nKey;
   76066   MemSetTypeFlag(pOut, MEM_Blob);
   76067   memcpy(pOut->z, pKey, nKey);
   76068 
   76069   return SQLITE_OK;
   76070 }
   76071 
   76072 /*
   76073 ** Compare the key in memory cell pVal with the key that the sorter cursor
   76074 ** passed as the first argument currently points to. For the purposes of
   76075 ** the comparison, ignore the rowid field at the end of each record.
   76076 **
   76077 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
   76078 ** Otherwise, set *pRes to a negative, zero or positive value if the
   76079 ** key in pVal is smaller than, equal to or larger than the current sorter
   76080 ** key.
   76081 */
   76082 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
   76083   const VdbeCursor *pCsr,         /* Sorter cursor */
   76084   Mem *pVal,                      /* Value to compare to current sorter key */
   76085   int nKeyCol,                    /* Only compare this many fields */
   76086   int *pRes                       /* OUT: Result of comparison */
   76087 ){
   76088   VdbeSorter *pSorter = pCsr->pSorter;
   76089   void *pKey; int nKey;           /* Sorter key to compare pVal with */
   76090 
   76091   pKey = vdbeSorterRowkey(pSorter, &nKey);
   76092   vdbeSorterCompare(pCsr, nKeyCol, pVal->z, pVal->n, pKey, nKey, pRes);
   76093   return SQLITE_OK;
   76094 }
   76095 
   76096 /************** End of vdbesort.c ********************************************/
   76097 /************** Begin file journal.c *****************************************/
   76098 /*
   76099 ** 2007 August 22
   76100 **
   76101 ** The author disclaims copyright to this source code.  In place of
   76102 ** a legal notice, here is a blessing:
   76103 **
   76104 **    May you do good and not evil.
   76105 **    May you find forgiveness for yourself and forgive others.
   76106 **    May you share freely, never taking more than you give.
   76107 **
   76108 *************************************************************************
   76109 **
   76110 ** This file implements a special kind of sqlite3_file object used
   76111 ** by SQLite to create journal files if the atomic-write optimization
   76112 ** is enabled.
   76113 **
   76114 ** The distinctive characteristic of this sqlite3_file is that the
   76115 ** actual on disk file is created lazily. When the file is created,
   76116 ** the caller specifies a buffer size for an in-memory buffer to
   76117 ** be used to service read() and write() requests. The actual file
   76118 ** on disk is not created or populated until either:
   76119 **
   76120 **   1) The in-memory representation grows too large for the allocated
   76121 **      buffer, or
   76122 **   2) The sqlite3JournalCreate() function is called.
   76123 */
   76124 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   76125 
   76126 
   76127 /*
   76128 ** A JournalFile object is a subclass of sqlite3_file used by
   76129 ** as an open file handle for journal files.
   76130 */
   76131 struct JournalFile {
   76132   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
   76133   int nBuf;                       /* Size of zBuf[] in bytes */
   76134   char *zBuf;                     /* Space to buffer journal writes */
   76135   int iSize;                      /* Amount of zBuf[] currently used */
   76136   int flags;                      /* xOpen flags */
   76137   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
   76138   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
   76139   const char *zJournal;           /* Name of the journal file */
   76140 };
   76141 typedef struct JournalFile JournalFile;
   76142 
   76143 /*
   76144 ** If it does not already exists, create and populate the on-disk file
   76145 ** for JournalFile p.
   76146 */
   76147 static int createFile(JournalFile *p){
   76148   int rc = SQLITE_OK;
   76149   if( !p->pReal ){
   76150     sqlite3_file *pReal = (sqlite3_file *)&p[1];
   76151     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
   76152     if( rc==SQLITE_OK ){
   76153       p->pReal = pReal;
   76154       if( p->iSize>0 ){
   76155         assert(p->iSize<=p->nBuf);
   76156         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
   76157       }
   76158       if( rc!=SQLITE_OK ){
   76159         /* If an error occurred while writing to the file, close it before
   76160         ** returning. This way, SQLite uses the in-memory journal data to
   76161         ** roll back changes made to the internal page-cache before this
   76162         ** function was called.  */
   76163         sqlite3OsClose(pReal);
   76164         p->pReal = 0;
   76165       }
   76166     }
   76167   }
   76168   return rc;
   76169 }
   76170 
   76171 /*
   76172 ** Close the file.
   76173 */
   76174 static int jrnlClose(sqlite3_file *pJfd){
   76175   JournalFile *p = (JournalFile *)pJfd;
   76176   if( p->pReal ){
   76177     sqlite3OsClose(p->pReal);
   76178   }
   76179   sqlite3_free(p->zBuf);
   76180   return SQLITE_OK;
   76181 }
   76182 
   76183 /*
   76184 ** Read data from the file.
   76185 */
   76186 static int jrnlRead(
   76187   sqlite3_file *pJfd,    /* The journal file from which to read */
   76188   void *zBuf,            /* Put the results here */
   76189   int iAmt,              /* Number of bytes to read */
   76190   sqlite_int64 iOfst     /* Begin reading at this offset */
   76191 ){
   76192   int rc = SQLITE_OK;
   76193   JournalFile *p = (JournalFile *)pJfd;
   76194   if( p->pReal ){
   76195     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
   76196   }else if( (iAmt+iOfst)>p->iSize ){
   76197     rc = SQLITE_IOERR_SHORT_READ;
   76198   }else{
   76199     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
   76200   }
   76201   return rc;
   76202 }
   76203 
   76204 /*
   76205 ** Write data to the file.
   76206 */
   76207 static int jrnlWrite(
   76208   sqlite3_file *pJfd,    /* The journal file into which to write */
   76209   const void *zBuf,      /* Take data to be written from here */
   76210   int iAmt,              /* Number of bytes to write */
   76211   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   76212 ){
   76213   int rc = SQLITE_OK;
   76214   JournalFile *p = (JournalFile *)pJfd;
   76215   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
   76216     rc = createFile(p);
   76217   }
   76218   if( rc==SQLITE_OK ){
   76219     if( p->pReal ){
   76220       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
   76221     }else{
   76222       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
   76223       if( p->iSize<(iOfst+iAmt) ){
   76224         p->iSize = (iOfst+iAmt);
   76225       }
   76226     }
   76227   }
   76228   return rc;
   76229 }
   76230 
   76231 /*
   76232 ** Truncate the file.
   76233 */
   76234 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   76235   int rc = SQLITE_OK;
   76236   JournalFile *p = (JournalFile *)pJfd;
   76237   if( p->pReal ){
   76238     rc = sqlite3OsTruncate(p->pReal, size);
   76239   }else if( size<p->iSize ){
   76240     p->iSize = size;
   76241   }
   76242   return rc;
   76243 }
   76244 
   76245 /*
   76246 ** Sync the file.
   76247 */
   76248 static int jrnlSync(sqlite3_file *pJfd, int flags){
   76249   int rc;
   76250   JournalFile *p = (JournalFile *)pJfd;
   76251   if( p->pReal ){
   76252     rc = sqlite3OsSync(p->pReal, flags);
   76253   }else{
   76254     rc = SQLITE_OK;
   76255   }
   76256   return rc;
   76257 }
   76258 
   76259 /*
   76260 ** Query the size of the file in bytes.
   76261 */
   76262 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   76263   int rc = SQLITE_OK;
   76264   JournalFile *p = (JournalFile *)pJfd;
   76265   if( p->pReal ){
   76266     rc = sqlite3OsFileSize(p->pReal, pSize);
   76267   }else{
   76268     *pSize = (sqlite_int64) p->iSize;
   76269   }
   76270   return rc;
   76271 }
   76272 
   76273 /*
   76274 ** Table of methods for JournalFile sqlite3_file object.
   76275 */
   76276 static struct sqlite3_io_methods JournalFileMethods = {
   76277   1,             /* iVersion */
   76278   jrnlClose,     /* xClose */
   76279   jrnlRead,      /* xRead */
   76280   jrnlWrite,     /* xWrite */
   76281   jrnlTruncate,  /* xTruncate */
   76282   jrnlSync,      /* xSync */
   76283   jrnlFileSize,  /* xFileSize */
   76284   0,             /* xLock */
   76285   0,             /* xUnlock */
   76286   0,             /* xCheckReservedLock */
   76287   0,             /* xFileControl */
   76288   0,             /* xSectorSize */
   76289   0,             /* xDeviceCharacteristics */
   76290   0,             /* xShmMap */
   76291   0,             /* xShmLock */
   76292   0,             /* xShmBarrier */
   76293   0              /* xShmUnmap */
   76294 };
   76295 
   76296 /*
   76297 ** Open a journal file.
   76298 */
   76299 SQLITE_PRIVATE int sqlite3JournalOpen(
   76300   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
   76301   const char *zName,         /* Name of the journal file */
   76302   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
   76303   int flags,                 /* Opening flags */
   76304   int nBuf                   /* Bytes buffered before opening the file */
   76305 ){
   76306   JournalFile *p = (JournalFile *)pJfd;
   76307   memset(p, 0, sqlite3JournalSize(pVfs));
   76308   if( nBuf>0 ){
   76309     p->zBuf = sqlite3MallocZero(nBuf);
   76310     if( !p->zBuf ){
   76311       return SQLITE_NOMEM;
   76312     }
   76313   }else{
   76314     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
   76315   }
   76316   p->pMethod = &JournalFileMethods;
   76317   p->nBuf = nBuf;
   76318   p->flags = flags;
   76319   p->zJournal = zName;
   76320   p->pVfs = pVfs;
   76321   return SQLITE_OK;
   76322 }
   76323 
   76324 /*
   76325 ** If the argument p points to a JournalFile structure, and the underlying
   76326 ** file has not yet been created, create it now.
   76327 */
   76328 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
   76329   if( p->pMethods!=&JournalFileMethods ){
   76330     return SQLITE_OK;
   76331   }
   76332   return createFile((JournalFile *)p);
   76333 }
   76334 
   76335 /*
   76336 ** The file-handle passed as the only argument is guaranteed to be an open
   76337 ** file. It may or may not be of class JournalFile. If the file is a
   76338 ** JournalFile, and the underlying file on disk has not yet been opened,
   76339 ** return 0. Otherwise, return 1.
   76340 */
   76341 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
   76342   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
   76343 }
   76344 
   76345 /*
   76346 ** Return the number of bytes required to store a JournalFile that uses vfs
   76347 ** pVfs to create the underlying on-disk files.
   76348 */
   76349 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
   76350   return (pVfs->szOsFile+sizeof(JournalFile));
   76351 }
   76352 #endif
   76353 
   76354 /************** End of journal.c *********************************************/
   76355 /************** Begin file memjournal.c **************************************/
   76356 /*
   76357 ** 2008 October 7
   76358 **
   76359 ** The author disclaims copyright to this source code.  In place of
   76360 ** a legal notice, here is a blessing:
   76361 **
   76362 **    May you do good and not evil.
   76363 **    May you find forgiveness for yourself and forgive others.
   76364 **    May you share freely, never taking more than you give.
   76365 **
   76366 *************************************************************************
   76367 **
   76368 ** This file contains code use to implement an in-memory rollback journal.
   76369 ** The in-memory rollback journal is used to journal transactions for
   76370 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
   76371 */
   76372 
   76373 /* Forward references to internal structures */
   76374 typedef struct MemJournal MemJournal;
   76375 typedef struct FilePoint FilePoint;
   76376 typedef struct FileChunk FileChunk;
   76377 
   76378 /* Space to hold the rollback journal is allocated in increments of
   76379 ** this many bytes.
   76380 **
   76381 ** The size chosen is a little less than a power of two.  That way,
   76382 ** the FileChunk object will have a size that almost exactly fills
   76383 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
   76384 ** memory allocators.
   76385 */
   76386 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
   76387 
   76388 /*
   76389 ** The rollback journal is composed of a linked list of these structures.
   76390 */
   76391 struct FileChunk {
   76392   FileChunk *pNext;               /* Next chunk in the journal */
   76393   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
   76394 };
   76395 
   76396 /*
   76397 ** An instance of this object serves as a cursor into the rollback journal.
   76398 ** The cursor can be either for reading or writing.
   76399 */
   76400 struct FilePoint {
   76401   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
   76402   FileChunk *pChunk;              /* Specific chunk into which cursor points */
   76403 };
   76404 
   76405 /*
   76406 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
   76407 ** is an instance of this class.
   76408 */
   76409 struct MemJournal {
   76410   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
   76411   FileChunk *pFirst;              /* Head of in-memory chunk-list */
   76412   FilePoint endpoint;             /* Pointer to the end of the file */
   76413   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
   76414 };
   76415 
   76416 /*
   76417 ** Read data from the in-memory journal file.  This is the implementation
   76418 ** of the sqlite3_vfs.xRead method.
   76419 */
   76420 static int memjrnlRead(
   76421   sqlite3_file *pJfd,    /* The journal file from which to read */
   76422   void *zBuf,            /* Put the results here */
   76423   int iAmt,              /* Number of bytes to read */
   76424   sqlite_int64 iOfst     /* Begin reading at this offset */
   76425 ){
   76426   MemJournal *p = (MemJournal *)pJfd;
   76427   u8 *zOut = zBuf;
   76428   int nRead = iAmt;
   76429   int iChunkOffset;
   76430   FileChunk *pChunk;
   76431 
   76432   /* SQLite never tries to read past the end of a rollback journal file */
   76433   assert( iOfst+iAmt<=p->endpoint.iOffset );
   76434 
   76435   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
   76436     sqlite3_int64 iOff = 0;
   76437     for(pChunk=p->pFirst;
   76438         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
   76439         pChunk=pChunk->pNext
   76440     ){
   76441       iOff += JOURNAL_CHUNKSIZE;
   76442     }
   76443   }else{
   76444     pChunk = p->readpoint.pChunk;
   76445   }
   76446 
   76447   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
   76448   do {
   76449     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
   76450     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
   76451     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
   76452     zOut += nCopy;
   76453     nRead -= iSpace;
   76454     iChunkOffset = 0;
   76455   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
   76456   p->readpoint.iOffset = iOfst+iAmt;
   76457   p->readpoint.pChunk = pChunk;
   76458 
   76459   return SQLITE_OK;
   76460 }
   76461 
   76462 /*
   76463 ** Write data to the file.
   76464 */
   76465 static int memjrnlWrite(
   76466   sqlite3_file *pJfd,    /* The journal file into which to write */
   76467   const void *zBuf,      /* Take data to be written from here */
   76468   int iAmt,              /* Number of bytes to write */
   76469   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   76470 ){
   76471   MemJournal *p = (MemJournal *)pJfd;
   76472   int nWrite = iAmt;
   76473   u8 *zWrite = (u8 *)zBuf;
   76474 
   76475   /* An in-memory journal file should only ever be appended to. Random
   76476   ** access writes are not required by sqlite.
   76477   */
   76478   assert( iOfst==p->endpoint.iOffset );
   76479   UNUSED_PARAMETER(iOfst);
   76480 
   76481   while( nWrite>0 ){
   76482     FileChunk *pChunk = p->endpoint.pChunk;
   76483     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
   76484     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
   76485 
   76486     if( iChunkOffset==0 ){
   76487       /* New chunk is required to extend the file. */
   76488       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
   76489       if( !pNew ){
   76490         return SQLITE_IOERR_NOMEM;
   76491       }
   76492       pNew->pNext = 0;
   76493       if( pChunk ){
   76494         assert( p->pFirst );
   76495         pChunk->pNext = pNew;
   76496       }else{
   76497         assert( !p->pFirst );
   76498         p->pFirst = pNew;
   76499       }
   76500       p->endpoint.pChunk = pNew;
   76501     }
   76502 
   76503     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
   76504     zWrite += iSpace;
   76505     nWrite -= iSpace;
   76506     p->endpoint.iOffset += iSpace;
   76507   }
   76508 
   76509   return SQLITE_OK;
   76510 }
   76511 
   76512 /*
   76513 ** Truncate the file.
   76514 */
   76515 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   76516   MemJournal *p = (MemJournal *)pJfd;
   76517   FileChunk *pChunk;
   76518   assert(size==0);
   76519   UNUSED_PARAMETER(size);
   76520   pChunk = p->pFirst;
   76521   while( pChunk ){
   76522     FileChunk *pTmp = pChunk;
   76523     pChunk = pChunk->pNext;
   76524     sqlite3_free(pTmp);
   76525   }
   76526   sqlite3MemJournalOpen(pJfd);
   76527   return SQLITE_OK;
   76528 }
   76529 
   76530 /*
   76531 ** Close the file.
   76532 */
   76533 static int memjrnlClose(sqlite3_file *pJfd){
   76534   memjrnlTruncate(pJfd, 0);
   76535   return SQLITE_OK;
   76536 }
   76537 
   76538 
   76539 /*
   76540 ** Sync the file.
   76541 **
   76542 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
   76543 ** is never called in a working implementation.  This implementation
   76544 ** exists purely as a contingency, in case some malfunction in some other
   76545 ** part of SQLite causes Sync to be called by mistake.
   76546 */
   76547 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
   76548   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   76549   return SQLITE_OK;
   76550 }
   76551 
   76552 /*
   76553 ** Query the size of the file in bytes.
   76554 */
   76555 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   76556   MemJournal *p = (MemJournal *)pJfd;
   76557   *pSize = (sqlite_int64) p->endpoint.iOffset;
   76558   return SQLITE_OK;
   76559 }
   76560 
   76561 /*
   76562 ** Table of methods for MemJournal sqlite3_file object.
   76563 */
   76564 static const struct sqlite3_io_methods MemJournalMethods = {
   76565   1,                /* iVersion */
   76566   memjrnlClose,     /* xClose */
   76567   memjrnlRead,      /* xRead */
   76568   memjrnlWrite,     /* xWrite */
   76569   memjrnlTruncate,  /* xTruncate */
   76570   memjrnlSync,      /* xSync */
   76571   memjrnlFileSize,  /* xFileSize */
   76572   0,                /* xLock */
   76573   0,                /* xUnlock */
   76574   0,                /* xCheckReservedLock */
   76575   0,                /* xFileControl */
   76576   0,                /* xSectorSize */
   76577   0,                /* xDeviceCharacteristics */
   76578   0,                /* xShmMap */
   76579   0,                /* xShmLock */
   76580   0,                /* xShmBarrier */
   76581   0,                /* xShmUnmap */
   76582   0,                /* xFetch */
   76583   0                 /* xUnfetch */
   76584 };
   76585 
   76586 /*
   76587 ** Open a journal file.
   76588 */
   76589 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
   76590   MemJournal *p = (MemJournal *)pJfd;
   76591   assert( EIGHT_BYTE_ALIGNMENT(p) );
   76592   memset(p, 0, sqlite3MemJournalSize());
   76593   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
   76594 }
   76595 
   76596 /*
   76597 ** Return true if the file-handle passed as an argument is
   76598 ** an in-memory journal
   76599 */
   76600 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
   76601   return pJfd->pMethods==&MemJournalMethods;
   76602 }
   76603 
   76604 /*
   76605 ** Return the number of bytes required to store a MemJournal file descriptor.
   76606 */
   76607 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
   76608   return sizeof(MemJournal);
   76609 }
   76610 
   76611 /************** End of memjournal.c ******************************************/
   76612 /************** Begin file walker.c ******************************************/
   76613 /*
   76614 ** 2008 August 16
   76615 **
   76616 ** The author disclaims copyright to this source code.  In place of
   76617 ** a legal notice, here is a blessing:
   76618 **
   76619 **    May you do good and not evil.
   76620 **    May you find forgiveness for yourself and forgive others.
   76621 **    May you share freely, never taking more than you give.
   76622 **
   76623 *************************************************************************
   76624 ** This file contains routines used for walking the parser tree for
   76625 ** an SQL statement.
   76626 */
   76627 /* #include <stdlib.h> */
   76628 /* #include <string.h> */
   76629 
   76630 
   76631 /*
   76632 ** Walk an expression tree.  Invoke the callback once for each node
   76633 ** of the expression, while decending.  (In other words, the callback
   76634 ** is invoked before visiting children.)
   76635 **
   76636 ** The return value from the callback should be one of the WRC_*
   76637 ** constants to specify how to proceed with the walk.
   76638 **
   76639 **    WRC_Continue      Continue descending down the tree.
   76640 **
   76641 **    WRC_Prune         Do not descend into child nodes.  But allow
   76642 **                      the walk to continue with sibling nodes.
   76643 **
   76644 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
   76645 **                      return the top-level walk call.
   76646 **
   76647 ** The return value from this routine is WRC_Abort to abandon the tree walk
   76648 ** and WRC_Continue to continue.
   76649 */
   76650 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
   76651   int rc;
   76652   if( pExpr==0 ) return WRC_Continue;
   76653   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
   76654   testcase( ExprHasProperty(pExpr, EP_Reduced) );
   76655   rc = pWalker->xExprCallback(pWalker, pExpr);
   76656   if( rc==WRC_Continue
   76657               && !ExprHasProperty(pExpr,EP_TokenOnly) ){
   76658     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
   76659     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
   76660     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   76661       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
   76662     }else{
   76663       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
   76664     }
   76665   }
   76666   return rc & WRC_Abort;
   76667 }
   76668 
   76669 /*
   76670 ** Call sqlite3WalkExpr() for every expression in list p or until
   76671 ** an abort request is seen.
   76672 */
   76673 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
   76674   int i;
   76675   struct ExprList_item *pItem;
   76676   if( p ){
   76677     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
   76678       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
   76679     }
   76680   }
   76681   return WRC_Continue;
   76682 }
   76683 
   76684 /*
   76685 ** Walk all expressions associated with SELECT statement p.  Do
   76686 ** not invoke the SELECT callback on p, but do (of course) invoke
   76687 ** any expr callbacks and SELECT callbacks that come from subqueries.
   76688 ** Return WRC_Abort or WRC_Continue.
   76689 */
   76690 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
   76691   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
   76692   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
   76693   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
   76694   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
   76695   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
   76696   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
   76697   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
   76698   return WRC_Continue;
   76699 }
   76700 
   76701 /*
   76702 ** Walk the parse trees associated with all subqueries in the
   76703 ** FROM clause of SELECT statement p.  Do not invoke the select
   76704 ** callback on p, but do invoke it on each FROM clause subquery
   76705 ** and on any subqueries further down in the tree.  Return
   76706 ** WRC_Abort or WRC_Continue;
   76707 */
   76708 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   76709   SrcList *pSrc;
   76710   int i;
   76711   struct SrcList_item *pItem;
   76712 
   76713   pSrc = p->pSrc;
   76714   if( ALWAYS(pSrc) ){
   76715     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   76716       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
   76717         return WRC_Abort;
   76718       }
   76719     }
   76720   }
   76721   return WRC_Continue;
   76722 }
   76723 
   76724 /*
   76725 ** Call sqlite3WalkExpr() for every expression in Select statement p.
   76726 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
   76727 ** on the compound select chain, p->pPrior.
   76728 **
   76729 ** If it is not NULL, the xSelectCallback() callback is invoked before
   76730 ** the walk of the expressions and FROM clause. The xSelectCallback2()
   76731 ** method, if it is not NULL, is invoked following the walk of the
   76732 ** expressions and FROM clause.
   76733 **
   76734 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
   76735 ** there is an abort request.
   76736 **
   76737 ** If the Walker does not have an xSelectCallback() then this routine
   76738 ** is a no-op returning WRC_Continue.
   76739 */
   76740 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
   76741   int rc;
   76742   if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
   76743     return WRC_Continue;
   76744   }
   76745   rc = WRC_Continue;
   76746   pWalker->walkerDepth++;
   76747   while( p ){
   76748     if( pWalker->xSelectCallback ){
   76749        rc = pWalker->xSelectCallback(pWalker, p);
   76750        if( rc ) break;
   76751     }
   76752     if( sqlite3WalkSelectExpr(pWalker, p)
   76753      || sqlite3WalkSelectFrom(pWalker, p)
   76754     ){
   76755       pWalker->walkerDepth--;
   76756       return WRC_Abort;
   76757     }
   76758     if( pWalker->xSelectCallback2 ){
   76759       pWalker->xSelectCallback2(pWalker, p);
   76760     }
   76761     p = p->pPrior;
   76762   }
   76763   pWalker->walkerDepth--;
   76764   return rc & WRC_Abort;
   76765 }
   76766 
   76767 /************** End of walker.c **********************************************/
   76768 /************** Begin file resolve.c *****************************************/
   76769 /*
   76770 ** 2008 August 18
   76771 **
   76772 ** The author disclaims copyright to this source code.  In place of
   76773 ** a legal notice, here is a blessing:
   76774 **
   76775 **    May you do good and not evil.
   76776 **    May you find forgiveness for yourself and forgive others.
   76777 **    May you share freely, never taking more than you give.
   76778 **
   76779 *************************************************************************
   76780 **
   76781 ** This file contains routines used for walking the parser tree and
   76782 ** resolve all identifiers by associating them with a particular
   76783 ** table and column.
   76784 */
   76785 /* #include <stdlib.h> */
   76786 /* #include <string.h> */
   76787 
   76788 /*
   76789 ** Walk the expression tree pExpr and increase the aggregate function
   76790 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
   76791 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
   76792 ** outer query into an inner subquery.
   76793 **
   76794 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
   76795 ** is a helper function - a callback for the tree walker.
   76796 */
   76797 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
   76798   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
   76799   return WRC_Continue;
   76800 }
   76801 static void incrAggFunctionDepth(Expr *pExpr, int N){
   76802   if( N>0 ){
   76803     Walker w;
   76804     memset(&w, 0, sizeof(w));
   76805     w.xExprCallback = incrAggDepth;
   76806     w.u.i = N;
   76807     sqlite3WalkExpr(&w, pExpr);
   76808   }
   76809 }
   76810 
   76811 /*
   76812 ** Turn the pExpr expression into an alias for the iCol-th column of the
   76813 ** result set in pEList.
   76814 **
   76815 ** If the result set column is a simple column reference, then this routine
   76816 ** makes an exact copy.  But for any other kind of expression, this
   76817 ** routine make a copy of the result set column as the argument to the
   76818 ** TK_AS operator.  The TK_AS operator causes the expression to be
   76819 ** evaluated just once and then reused for each alias.
   76820 **
   76821 ** The reason for suppressing the TK_AS term when the expression is a simple
   76822 ** column reference is so that the column reference will be recognized as
   76823 ** usable by indices within the WHERE clause processing logic.
   76824 **
   76825 ** The TK_AS operator is inhibited if zType[0]=='G'.  This means
   76826 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
   76827 **
   76828 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
   76829 **
   76830 ** Is equivalent to:
   76831 **
   76832 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
   76833 **
   76834 ** The result of random()%5 in the GROUP BY clause is probably different
   76835 ** from the result in the result-set.  On the other hand Standard SQL does
   76836 ** not allow the GROUP BY clause to contain references to result-set columns.
   76837 ** So this should never come up in well-formed queries.
   76838 **
   76839 ** If the reference is followed by a COLLATE operator, then make sure
   76840 ** the COLLATE operator is preserved.  For example:
   76841 **
   76842 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
   76843 **
   76844 ** Should be transformed into:
   76845 **
   76846 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
   76847 **
   76848 ** The nSubquery parameter specifies how many levels of subquery the
   76849 ** alias is removed from the original expression.  The usually value is
   76850 ** zero but it might be more if the alias is contained within a subquery
   76851 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
   76852 ** structures must be increased by the nSubquery amount.
   76853 */
   76854 static void resolveAlias(
   76855   Parse *pParse,         /* Parsing context */
   76856   ExprList *pEList,      /* A result set */
   76857   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
   76858   Expr *pExpr,           /* Transform this into an alias to the result set */
   76859   const char *zType,     /* "GROUP" or "ORDER" or "" */
   76860   int nSubquery          /* Number of subqueries that the label is moving */
   76861 ){
   76862   Expr *pOrig;           /* The iCol-th column of the result set */
   76863   Expr *pDup;            /* Copy of pOrig */
   76864   sqlite3 *db;           /* The database connection */
   76865 
   76866   assert( iCol>=0 && iCol<pEList->nExpr );
   76867   pOrig = pEList->a[iCol].pExpr;
   76868   assert( pOrig!=0 );
   76869   assert( pOrig->flags & EP_Resolved );
   76870   db = pParse->db;
   76871   pDup = sqlite3ExprDup(db, pOrig, 0);
   76872   if( pDup==0 ) return;
   76873   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
   76874     incrAggFunctionDepth(pDup, nSubquery);
   76875     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
   76876     if( pDup==0 ) return;
   76877     ExprSetProperty(pDup, EP_Skip);
   76878     if( pEList->a[iCol].u.x.iAlias==0 ){
   76879       pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
   76880     }
   76881     pDup->iTable = pEList->a[iCol].u.x.iAlias;
   76882   }
   76883   if( pExpr->op==TK_COLLATE ){
   76884     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
   76885   }
   76886 
   76887   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
   76888   ** prevents ExprDelete() from deleting the Expr structure itself,
   76889   ** allowing it to be repopulated by the memcpy() on the following line.
   76890   ** The pExpr->u.zToken might point into memory that will be freed by the
   76891   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
   76892   ** make a copy of the token before doing the sqlite3DbFree().
   76893   */
   76894   ExprSetProperty(pExpr, EP_Static);
   76895   sqlite3ExprDelete(db, pExpr);
   76896   memcpy(pExpr, pDup, sizeof(*pExpr));
   76897   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
   76898     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
   76899     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
   76900     pExpr->flags |= EP_MemToken;
   76901   }
   76902   sqlite3DbFree(db, pDup);
   76903 }
   76904 
   76905 
   76906 /*
   76907 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
   76908 **
   76909 ** Return FALSE if the USING clause is NULL or if it does not contain
   76910 ** zCol.
   76911 */
   76912 static int nameInUsingClause(IdList *pUsing, const char *zCol){
   76913   if( pUsing ){
   76914     int k;
   76915     for(k=0; k<pUsing->nId; k++){
   76916       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
   76917     }
   76918   }
   76919   return 0;
   76920 }
   76921 
   76922 /*
   76923 ** Subqueries stores the original database, table and column names for their
   76924 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
   76925 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
   76926 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
   76927 ** match anything.
   76928 */
   76929 SQLITE_PRIVATE int sqlite3MatchSpanName(
   76930   const char *zSpan,
   76931   const char *zCol,
   76932   const char *zTab,
   76933   const char *zDb
   76934 ){
   76935   int n;
   76936   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
   76937   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
   76938     return 0;
   76939   }
   76940   zSpan += n+1;
   76941   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
   76942   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
   76943     return 0;
   76944   }
   76945   zSpan += n+1;
   76946   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
   76947     return 0;
   76948   }
   76949   return 1;
   76950 }
   76951 
   76952 /*
   76953 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
   76954 ** that name in the set of source tables in pSrcList and make the pExpr
   76955 ** expression node refer back to that source column.  The following changes
   76956 ** are made to pExpr:
   76957 **
   76958 **    pExpr->iDb           Set the index in db->aDb[] of the database X
   76959 **                         (even if X is implied).
   76960 **    pExpr->iTable        Set to the cursor number for the table obtained
   76961 **                         from pSrcList.
   76962 **    pExpr->pTab          Points to the Table structure of X.Y (even if
   76963 **                         X and/or Y are implied.)
   76964 **    pExpr->iColumn       Set to the column number within the table.
   76965 **    pExpr->op            Set to TK_COLUMN.
   76966 **    pExpr->pLeft         Any expression this points to is deleted
   76967 **    pExpr->pRight        Any expression this points to is deleted.
   76968 **
   76969 ** The zDb variable is the name of the database (the "X").  This value may be
   76970 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
   76971 ** can be used.  The zTable variable is the name of the table (the "Y").  This
   76972 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
   76973 ** means that the form of the name is Z and that columns from any table
   76974 ** can be used.
   76975 **
   76976 ** If the name cannot be resolved unambiguously, leave an error message
   76977 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
   76978 */
   76979 static int lookupName(
   76980   Parse *pParse,       /* The parsing context */
   76981   const char *zDb,     /* Name of the database containing table, or NULL */
   76982   const char *zTab,    /* Name of table containing column, or NULL */
   76983   const char *zCol,    /* Name of the column. */
   76984   NameContext *pNC,    /* The name context used to resolve the name */
   76985   Expr *pExpr          /* Make this EXPR node point to the selected column */
   76986 ){
   76987   int i, j;                         /* Loop counters */
   76988   int cnt = 0;                      /* Number of matching column names */
   76989   int cntTab = 0;                   /* Number of matching table names */
   76990   int nSubquery = 0;                /* How many levels of subquery */
   76991   sqlite3 *db = pParse->db;         /* The database connection */
   76992   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
   76993   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   76994   NameContext *pTopNC = pNC;        /* First namecontext in the list */
   76995   Schema *pSchema = 0;              /* Schema of the expression */
   76996   int isTrigger = 0;                /* True if resolved to a trigger column */
   76997   Table *pTab = 0;                  /* Table hold the row */
   76998   Column *pCol;                     /* A column of pTab */
   76999 
   77000   assert( pNC );     /* the name context cannot be NULL. */
   77001   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
   77002   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   77003 
   77004   /* Initialize the node to no-match */
   77005   pExpr->iTable = -1;
   77006   pExpr->pTab = 0;
   77007   ExprSetVVAProperty(pExpr, EP_NoReduce);
   77008 
   77009   /* Translate the schema name in zDb into a pointer to the corresponding
   77010   ** schema.  If not found, pSchema will remain NULL and nothing will match
   77011   ** resulting in an appropriate error message toward the end of this routine
   77012   */
   77013   if( zDb ){
   77014     testcase( pNC->ncFlags & NC_PartIdx );
   77015     testcase( pNC->ncFlags & NC_IsCheck );
   77016     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
   77017       /* Silently ignore database qualifiers inside CHECK constraints and partial
   77018       ** indices.  Do not raise errors because that might break legacy and
   77019       ** because it does not hurt anything to just ignore the database name. */
   77020       zDb = 0;
   77021     }else{
   77022       for(i=0; i<db->nDb; i++){
   77023         assert( db->aDb[i].zName );
   77024         if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
   77025           pSchema = db->aDb[i].pSchema;
   77026           break;
   77027         }
   77028       }
   77029     }
   77030   }
   77031 
   77032   /* Start at the inner-most context and move outward until a match is found */
   77033   while( pNC && cnt==0 ){
   77034     ExprList *pEList;
   77035     SrcList *pSrcList = pNC->pSrcList;
   77036 
   77037     if( pSrcList ){
   77038       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   77039         pTab = pItem->pTab;
   77040         assert( pTab!=0 && pTab->zName!=0 );
   77041         assert( pTab->nCol>0 );
   77042         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
   77043           int hit = 0;
   77044           pEList = pItem->pSelect->pEList;
   77045           for(j=0; j<pEList->nExpr; j++){
   77046             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
   77047               cnt++;
   77048               cntTab = 2;
   77049               pMatch = pItem;
   77050               pExpr->iColumn = j;
   77051               hit = 1;
   77052             }
   77053           }
   77054           if( hit || zTab==0 ) continue;
   77055         }
   77056         if( zDb && pTab->pSchema!=pSchema ){
   77057           continue;
   77058         }
   77059         if( zTab ){
   77060           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
   77061           assert( zTabName!=0 );
   77062           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
   77063             continue;
   77064           }
   77065         }
   77066         if( 0==(cntTab++) ){
   77067           pMatch = pItem;
   77068         }
   77069         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   77070           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   77071             /* If there has been exactly one prior match and this match
   77072             ** is for the right-hand table of a NATURAL JOIN or is in a
   77073             ** USING clause, then skip this match.
   77074             */
   77075             if( cnt==1 ){
   77076               if( pItem->jointype & JT_NATURAL ) continue;
   77077               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
   77078             }
   77079             cnt++;
   77080             pMatch = pItem;
   77081             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   77082             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
   77083             break;
   77084           }
   77085         }
   77086       }
   77087       if( pMatch ){
   77088         pExpr->iTable = pMatch->iCursor;
   77089         pExpr->pTab = pMatch->pTab;
   77090         pSchema = pExpr->pTab->pSchema;
   77091       }
   77092     } /* if( pSrcList ) */
   77093 
   77094 #ifndef SQLITE_OMIT_TRIGGER
   77095     /* If we have not already resolved the name, then maybe
   77096     ** it is a new.* or old.* trigger argument reference
   77097     */
   77098     if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
   77099       int op = pParse->eTriggerOp;
   77100       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
   77101       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   77102         pExpr->iTable = 1;
   77103         pTab = pParse->pTriggerTab;
   77104       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   77105         pExpr->iTable = 0;
   77106         pTab = pParse->pTriggerTab;
   77107       }else{
   77108         pTab = 0;
   77109       }
   77110 
   77111       if( pTab ){
   77112         int iCol;
   77113         pSchema = pTab->pSchema;
   77114         cntTab++;
   77115         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
   77116           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   77117             if( iCol==pTab->iPKey ){
   77118               iCol = -1;
   77119             }
   77120             break;
   77121           }
   77122         }
   77123         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
   77124           /* IMP: R-51414-32910 */
   77125           /* IMP: R-44911-55124 */
   77126           iCol = -1;
   77127         }
   77128         if( iCol<pTab->nCol ){
   77129           cnt++;
   77130           if( iCol<0 ){
   77131             pExpr->affinity = SQLITE_AFF_INTEGER;
   77132           }else if( pExpr->iTable==0 ){
   77133             testcase( iCol==31 );
   77134             testcase( iCol==32 );
   77135             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   77136           }else{
   77137             testcase( iCol==31 );
   77138             testcase( iCol==32 );
   77139             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   77140           }
   77141           pExpr->iColumn = (i16)iCol;
   77142           pExpr->pTab = pTab;
   77143           isTrigger = 1;
   77144         }
   77145       }
   77146     }
   77147 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   77148 
   77149     /*
   77150     ** Perhaps the name is a reference to the ROWID
   77151     */
   77152     if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
   77153      && HasRowid(pMatch->pTab) ){
   77154       cnt = 1;
   77155       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
   77156       pExpr->affinity = SQLITE_AFF_INTEGER;
   77157     }
   77158 
   77159     /*
   77160     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
   77161     ** might refer to an result-set alias.  This happens, for example, when
   77162     ** we are resolving names in the WHERE clause of the following command:
   77163     **
   77164     **     SELECT a+b AS x FROM table WHERE x<10;
   77165     **
   77166     ** In cases like this, replace pExpr with a copy of the expression that
   77167     ** forms the result set entry ("a+b" in the example) and return immediately.
   77168     ** Note that the expression in the result set should have already been
   77169     ** resolved by the time the WHERE clause is resolved.
   77170     **
   77171     ** The ability to use an output result-set column in the WHERE, GROUP BY,
   77172     ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
   77173     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
   77174     ** is supported for backwards compatibility only.  TO DO: Issue a warning
   77175     ** on sqlite3_log() whenever the capability is used.
   77176     */
   77177     if( (pEList = pNC->pEList)!=0
   77178      && zTab==0
   77179      && cnt==0
   77180     ){
   77181       for(j=0; j<pEList->nExpr; j++){
   77182         char *zAs = pEList->a[j].zName;
   77183         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   77184           Expr *pOrig;
   77185           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   77186           assert( pExpr->x.pList==0 );
   77187           assert( pExpr->x.pSelect==0 );
   77188           pOrig = pEList->a[j].pExpr;
   77189           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
   77190             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
   77191             return WRC_Abort;
   77192           }
   77193           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
   77194           cnt = 1;
   77195           pMatch = 0;
   77196           assert( zTab==0 && zDb==0 );
   77197           goto lookupname_end;
   77198         }
   77199       }
   77200     }
   77201 
   77202     /* Advance to the next name context.  The loop will exit when either
   77203     ** we have a match (cnt>0) or when we run out of name contexts.
   77204     */
   77205     if( cnt==0 ){
   77206       pNC = pNC->pNext;
   77207       nSubquery++;
   77208     }
   77209   }
   77210 
   77211   /*
   77212   ** If X and Y are NULL (in other words if only the column name Z is
   77213   ** supplied) and the value of Z is enclosed in double-quotes, then
   77214   ** Z is a string literal if it doesn't match any column names.  In that
   77215   ** case, we need to return right away and not make any changes to
   77216   ** pExpr.
   77217   **
   77218   ** Because no reference was made to outer contexts, the pNC->nRef
   77219   ** fields are not changed in any context.
   77220   */
   77221   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
   77222     pExpr->op = TK_STRING;
   77223     pExpr->pTab = 0;
   77224     return WRC_Prune;
   77225   }
   77226 
   77227   /*
   77228   ** cnt==0 means there was not match.  cnt>1 means there were two or
   77229   ** more matches.  Either way, we have an error.
   77230   */
   77231   if( cnt!=1 ){
   77232     const char *zErr;
   77233     zErr = cnt==0 ? "no such column" : "ambiguous column name";
   77234     if( zDb ){
   77235       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
   77236     }else if( zTab ){
   77237       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
   77238     }else{
   77239       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
   77240     }
   77241     pParse->checkSchema = 1;
   77242     pTopNC->nErr++;
   77243   }
   77244 
   77245   /* If a column from a table in pSrcList is referenced, then record
   77246   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
   77247   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
   77248   ** column number is greater than the number of bits in the bitmask
   77249   ** then set the high-order bit of the bitmask.
   77250   */
   77251   if( pExpr->iColumn>=0 && pMatch!=0 ){
   77252     int n = pExpr->iColumn;
   77253     testcase( n==BMS-1 );
   77254     if( n>=BMS ){
   77255       n = BMS-1;
   77256     }
   77257     assert( pMatch->iCursor==pExpr->iTable );
   77258     pMatch->colUsed |= ((Bitmask)1)<<n;
   77259   }
   77260 
   77261   /* Clean up and return
   77262   */
   77263   sqlite3ExprDelete(db, pExpr->pLeft);
   77264   pExpr->pLeft = 0;
   77265   sqlite3ExprDelete(db, pExpr->pRight);
   77266   pExpr->pRight = 0;
   77267   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
   77268 lookupname_end:
   77269   if( cnt==1 ){
   77270     assert( pNC!=0 );
   77271     if( pExpr->op!=TK_AS ){
   77272       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
   77273     }
   77274     /* Increment the nRef value on all name contexts from TopNC up to
   77275     ** the point where the name matched. */
   77276     for(;;){
   77277       assert( pTopNC!=0 );
   77278       pTopNC->nRef++;
   77279       if( pTopNC==pNC ) break;
   77280       pTopNC = pTopNC->pNext;
   77281     }
   77282     return WRC_Prune;
   77283   } else {
   77284     return WRC_Abort;
   77285   }
   77286 }
   77287 
   77288 /*
   77289 ** Allocate and return a pointer to an expression to load the column iCol
   77290 ** from datasource iSrc in SrcList pSrc.
   77291 */
   77292 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
   77293   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   77294   if( p ){
   77295     struct SrcList_item *pItem = &pSrc->a[iSrc];
   77296     p->pTab = pItem->pTab;
   77297     p->iTable = pItem->iCursor;
   77298     if( p->pTab->iPKey==iCol ){
   77299       p->iColumn = -1;
   77300     }else{
   77301       p->iColumn = (ynVar)iCol;
   77302       testcase( iCol==BMS );
   77303       testcase( iCol==BMS-1 );
   77304       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
   77305     }
   77306     ExprSetProperty(p, EP_Resolved);
   77307   }
   77308   return p;
   77309 }
   77310 
   77311 /*
   77312 ** Report an error that an expression is not valid for a partial index WHERE
   77313 ** clause.
   77314 */
   77315 static void notValidPartIdxWhere(
   77316   Parse *pParse,       /* Leave error message here */
   77317   NameContext *pNC,    /* The name context */
   77318   const char *zMsg     /* Type of error */
   77319 ){
   77320   if( (pNC->ncFlags & NC_PartIdx)!=0 ){
   77321     sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
   77322                     zMsg);
   77323   }
   77324 }
   77325 
   77326 #ifndef SQLITE_OMIT_CHECK
   77327 /*
   77328 ** Report an error that an expression is not valid for a CHECK constraint.
   77329 */
   77330 static void notValidCheckConstraint(
   77331   Parse *pParse,       /* Leave error message here */
   77332   NameContext *pNC,    /* The name context */
   77333   const char *zMsg     /* Type of error */
   77334 ){
   77335   if( (pNC->ncFlags & NC_IsCheck)!=0 ){
   77336     sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
   77337   }
   77338 }
   77339 #else
   77340 # define notValidCheckConstraint(P,N,M)
   77341 #endif
   77342 
   77343 /*
   77344 ** Expression p should encode a floating point value between 1.0 and 0.0.
   77345 ** Return 1024 times this value.  Or return -1 if p is not a floating point
   77346 ** value between 1.0 and 0.0.
   77347 */
   77348 static int exprProbability(Expr *p){
   77349   double r = -1.0;
   77350   if( p->op!=TK_FLOAT ) return -1;
   77351   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
   77352   assert( r>=0.0 );
   77353   if( r>1.0 ) return -1;
   77354   return (int)(r*1000.0);
   77355 }
   77356 
   77357 /*
   77358 ** This routine is callback for sqlite3WalkExpr().
   77359 **
   77360 ** Resolve symbolic names into TK_COLUMN operators for the current
   77361 ** node in the expression tree.  Return 0 to continue the search down
   77362 ** the tree or 2 to abort the tree walk.
   77363 **
   77364 ** This routine also does error checking and name resolution for
   77365 ** function names.  The operator for aggregate functions is changed
   77366 ** to TK_AGG_FUNCTION.
   77367 */
   77368 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
   77369   NameContext *pNC;
   77370   Parse *pParse;
   77371 
   77372   pNC = pWalker->u.pNC;
   77373   assert( pNC!=0 );
   77374   pParse = pNC->pParse;
   77375   assert( pParse==pWalker->pParse );
   77376 
   77377   if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
   77378   ExprSetProperty(pExpr, EP_Resolved);
   77379 #ifndef NDEBUG
   77380   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
   77381     SrcList *pSrcList = pNC->pSrcList;
   77382     int i;
   77383     for(i=0; i<pNC->pSrcList->nSrc; i++){
   77384       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
   77385     }
   77386   }
   77387 #endif
   77388   switch( pExpr->op ){
   77389 
   77390 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   77391     /* The special operator TK_ROW means use the rowid for the first
   77392     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
   77393     ** clause processing on UPDATE and DELETE statements.
   77394     */
   77395     case TK_ROW: {
   77396       SrcList *pSrcList = pNC->pSrcList;
   77397       struct SrcList_item *pItem;
   77398       assert( pSrcList && pSrcList->nSrc==1 );
   77399       pItem = pSrcList->a;
   77400       pExpr->op = TK_COLUMN;
   77401       pExpr->pTab = pItem->pTab;
   77402       pExpr->iTable = pItem->iCursor;
   77403       pExpr->iColumn = -1;
   77404       pExpr->affinity = SQLITE_AFF_INTEGER;
   77405       break;
   77406     }
   77407 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   77408 
   77409     /* A lone identifier is the name of a column.
   77410     */
   77411     case TK_ID: {
   77412       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
   77413     }
   77414 
   77415     /* A table name and column name:     ID.ID
   77416     ** Or a database, table and column:  ID.ID.ID
   77417     */
   77418     case TK_DOT: {
   77419       const char *zColumn;
   77420       const char *zTable;
   77421       const char *zDb;
   77422       Expr *pRight;
   77423 
   77424       /* if( pSrcList==0 ) break; */
   77425       pRight = pExpr->pRight;
   77426       if( pRight->op==TK_ID ){
   77427         zDb = 0;
   77428         zTable = pExpr->pLeft->u.zToken;
   77429         zColumn = pRight->u.zToken;
   77430       }else{
   77431         assert( pRight->op==TK_DOT );
   77432         zDb = pExpr->pLeft->u.zToken;
   77433         zTable = pRight->pLeft->u.zToken;
   77434         zColumn = pRight->pRight->u.zToken;
   77435       }
   77436       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
   77437     }
   77438 
   77439     /* Resolve function names
   77440     */
   77441     case TK_FUNCTION: {
   77442       ExprList *pList = pExpr->x.pList;    /* The argument list */
   77443       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
   77444       int no_such_func = 0;       /* True if no such function exists */
   77445       int wrong_num_args = 0;     /* True if wrong number of arguments */
   77446       int is_agg = 0;             /* True if is an aggregate function */
   77447       int auth;                   /* Authorization to use the function */
   77448       int nId;                    /* Number of characters in function name */
   77449       const char *zId;            /* The function name. */
   77450       FuncDef *pDef;              /* Information about the function */
   77451       u8 enc = ENC(pParse->db);   /* The database encoding */
   77452 
   77453       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   77454       notValidPartIdxWhere(pParse, pNC, "functions");
   77455       zId = pExpr->u.zToken;
   77456       nId = sqlite3Strlen30(zId);
   77457       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
   77458       if( pDef==0 ){
   77459         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
   77460         if( pDef==0 ){
   77461           no_such_func = 1;
   77462         }else{
   77463           wrong_num_args = 1;
   77464         }
   77465       }else{
   77466         is_agg = pDef->xFunc==0;
   77467         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
   77468           ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
   77469           if( n==2 ){
   77470             pExpr->iTable = exprProbability(pList->a[1].pExpr);
   77471             if( pExpr->iTable<0 ){
   77472               sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
   77473                                       "constant between 0.0 and 1.0");
   77474               pNC->nErr++;
   77475             }
   77476           }else{
   77477             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
   77478             ** likelihood(X, 0.0625).
   77479             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
   77480             ** likelihood(X,0.0625).
   77481             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand for
   77482             ** likelihood(X,0.9375).
   77483             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent to
   77484             ** likelihood(X,0.9375). */
   77485             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
   77486             pExpr->iTable = pDef->zName[0]=='u' ? 62 : 938;
   77487           }
   77488         }
   77489       }
   77490 #ifndef SQLITE_OMIT_AUTHORIZATION
   77491       if( pDef ){
   77492         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
   77493         if( auth!=SQLITE_OK ){
   77494           if( auth==SQLITE_DENY ){
   77495             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
   77496                                     pDef->zName);
   77497             pNC->nErr++;
   77498           }
   77499           pExpr->op = TK_NULL;
   77500           return WRC_Prune;
   77501         }
   77502         if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
   77503       }
   77504 #endif
   77505       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
   77506         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
   77507         pNC->nErr++;
   77508         is_agg = 0;
   77509       }else if( no_such_func && pParse->db->init.busy==0 ){
   77510         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
   77511         pNC->nErr++;
   77512       }else if( wrong_num_args ){
   77513         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
   77514              nId, zId);
   77515         pNC->nErr++;
   77516       }
   77517       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
   77518       sqlite3WalkExprList(pWalker, pList);
   77519       if( is_agg ){
   77520         NameContext *pNC2 = pNC;
   77521         pExpr->op = TK_AGG_FUNCTION;
   77522         pExpr->op2 = 0;
   77523         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
   77524           pExpr->op2++;
   77525           pNC2 = pNC2->pNext;
   77526         }
   77527         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
   77528         pNC->ncFlags |= NC_AllowAgg;
   77529       }
   77530       /* FIX ME:  Compute pExpr->affinity based on the expected return
   77531       ** type of the function
   77532       */
   77533       return WRC_Prune;
   77534     }
   77535 #ifndef SQLITE_OMIT_SUBQUERY
   77536     case TK_SELECT:
   77537     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
   77538 #endif
   77539     case TK_IN: {
   77540       testcase( pExpr->op==TK_IN );
   77541       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   77542         int nRef = pNC->nRef;
   77543         notValidCheckConstraint(pParse, pNC, "subqueries");
   77544         notValidPartIdxWhere(pParse, pNC, "subqueries");
   77545         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
   77546         assert( pNC->nRef>=nRef );
   77547         if( nRef!=pNC->nRef ){
   77548           ExprSetProperty(pExpr, EP_VarSelect);
   77549         }
   77550       }
   77551       break;
   77552     }
   77553     case TK_VARIABLE: {
   77554       notValidCheckConstraint(pParse, pNC, "parameters");
   77555       notValidPartIdxWhere(pParse, pNC, "parameters");
   77556       break;
   77557     }
   77558   }
   77559   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
   77560 }
   77561 
   77562 /*
   77563 ** pEList is a list of expressions which are really the result set of the
   77564 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
   77565 ** This routine checks to see if pE is a simple identifier which corresponds
   77566 ** to the AS-name of one of the terms of the expression list.  If it is,
   77567 ** this routine return an integer between 1 and N where N is the number of
   77568 ** elements in pEList, corresponding to the matching entry.  If there is
   77569 ** no match, or if pE is not a simple identifier, then this routine
   77570 ** return 0.
   77571 **
   77572 ** pEList has been resolved.  pE has not.
   77573 */
   77574 static int resolveAsName(
   77575   Parse *pParse,     /* Parsing context for error messages */
   77576   ExprList *pEList,  /* List of expressions to scan */
   77577   Expr *pE           /* Expression we are trying to match */
   77578 ){
   77579   int i;             /* Loop counter */
   77580 
   77581   UNUSED_PARAMETER(pParse);
   77582 
   77583   if( pE->op==TK_ID ){
   77584     char *zCol = pE->u.zToken;
   77585     for(i=0; i<pEList->nExpr; i++){
   77586       char *zAs = pEList->a[i].zName;
   77587       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   77588         return i+1;
   77589       }
   77590     }
   77591   }
   77592   return 0;
   77593 }
   77594 
   77595 /*
   77596 ** pE is a pointer to an expression which is a single term in the
   77597 ** ORDER BY of a compound SELECT.  The expression has not been
   77598 ** name resolved.
   77599 **
   77600 ** At the point this routine is called, we already know that the
   77601 ** ORDER BY term is not an integer index into the result set.  That
   77602 ** case is handled by the calling routine.
   77603 **
   77604 ** Attempt to match pE against result set columns in the left-most
   77605 ** SELECT statement.  Return the index i of the matching column,
   77606 ** as an indication to the caller that it should sort by the i-th column.
   77607 ** The left-most column is 1.  In other words, the value returned is the
   77608 ** same integer value that would be used in the SQL statement to indicate
   77609 ** the column.
   77610 **
   77611 ** If there is no match, return 0.  Return -1 if an error occurs.
   77612 */
   77613 static int resolveOrderByTermToExprList(
   77614   Parse *pParse,     /* Parsing context for error messages */
   77615   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
   77616   Expr *pE           /* The specific ORDER BY term */
   77617 ){
   77618   int i;             /* Loop counter */
   77619   ExprList *pEList;  /* The columns of the result set */
   77620   NameContext nc;    /* Name context for resolving pE */
   77621   sqlite3 *db;       /* Database connection */
   77622   int rc;            /* Return code from subprocedures */
   77623   u8 savedSuppErr;   /* Saved value of db->suppressErr */
   77624 
   77625   assert( sqlite3ExprIsInteger(pE, &i)==0 );
   77626   pEList = pSelect->pEList;
   77627 
   77628   /* Resolve all names in the ORDER BY term expression
   77629   */
   77630   memset(&nc, 0, sizeof(nc));
   77631   nc.pParse = pParse;
   77632   nc.pSrcList = pSelect->pSrc;
   77633   nc.pEList = pEList;
   77634   nc.ncFlags = NC_AllowAgg;
   77635   nc.nErr = 0;
   77636   db = pParse->db;
   77637   savedSuppErr = db->suppressErr;
   77638   db->suppressErr = 1;
   77639   rc = sqlite3ResolveExprNames(&nc, pE);
   77640   db->suppressErr = savedSuppErr;
   77641   if( rc ) return 0;
   77642 
   77643   /* Try to match the ORDER BY expression against an expression
   77644   ** in the result set.  Return an 1-based index of the matching
   77645   ** result-set entry.
   77646   */
   77647   for(i=0; i<pEList->nExpr; i++){
   77648     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
   77649       return i+1;
   77650     }
   77651   }
   77652 
   77653   /* If no match, return 0. */
   77654   return 0;
   77655 }
   77656 
   77657 /*
   77658 ** Generate an ORDER BY or GROUP BY term out-of-range error.
   77659 */
   77660 static void resolveOutOfRangeError(
   77661   Parse *pParse,         /* The error context into which to write the error */
   77662   const char *zType,     /* "ORDER" or "GROUP" */
   77663   int i,                 /* The index (1-based) of the term out of range */
   77664   int mx                 /* Largest permissible value of i */
   77665 ){
   77666   sqlite3ErrorMsg(pParse,
   77667     "%r %s BY term out of range - should be "
   77668     "between 1 and %d", i, zType, mx);
   77669 }
   77670 
   77671 /*
   77672 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
   77673 ** each term of the ORDER BY clause is a constant integer between 1
   77674 ** and N where N is the number of columns in the compound SELECT.
   77675 **
   77676 ** ORDER BY terms that are already an integer between 1 and N are
   77677 ** unmodified.  ORDER BY terms that are integers outside the range of
   77678 ** 1 through N generate an error.  ORDER BY terms that are expressions
   77679 ** are matched against result set expressions of compound SELECT
   77680 ** beginning with the left-most SELECT and working toward the right.
   77681 ** At the first match, the ORDER BY expression is transformed into
   77682 ** the integer column number.
   77683 **
   77684 ** Return the number of errors seen.
   77685 */
   77686 static int resolveCompoundOrderBy(
   77687   Parse *pParse,        /* Parsing context.  Leave error messages here */
   77688   Select *pSelect       /* The SELECT statement containing the ORDER BY */
   77689 ){
   77690   int i;
   77691   ExprList *pOrderBy;
   77692   ExprList *pEList;
   77693   sqlite3 *db;
   77694   int moreToDo = 1;
   77695 
   77696   pOrderBy = pSelect->pOrderBy;
   77697   if( pOrderBy==0 ) return 0;
   77698   db = pParse->db;
   77699 #if SQLITE_MAX_COLUMN
   77700   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   77701     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
   77702     return 1;
   77703   }
   77704 #endif
   77705   for(i=0; i<pOrderBy->nExpr; i++){
   77706     pOrderBy->a[i].done = 0;
   77707   }
   77708   pSelect->pNext = 0;
   77709   while( pSelect->pPrior ){
   77710     pSelect->pPrior->pNext = pSelect;
   77711     pSelect = pSelect->pPrior;
   77712   }
   77713   while( pSelect && moreToDo ){
   77714     struct ExprList_item *pItem;
   77715     moreToDo = 0;
   77716     pEList = pSelect->pEList;
   77717     assert( pEList!=0 );
   77718     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   77719       int iCol = -1;
   77720       Expr *pE, *pDup;
   77721       if( pItem->done ) continue;
   77722       pE = sqlite3ExprSkipCollate(pItem->pExpr);
   77723       if( sqlite3ExprIsInteger(pE, &iCol) ){
   77724         if( iCol<=0 || iCol>pEList->nExpr ){
   77725           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
   77726           return 1;
   77727         }
   77728       }else{
   77729         iCol = resolveAsName(pParse, pEList, pE);
   77730         if( iCol==0 ){
   77731           pDup = sqlite3ExprDup(db, pE, 0);
   77732           if( !db->mallocFailed ){
   77733             assert(pDup);
   77734             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
   77735           }
   77736           sqlite3ExprDelete(db, pDup);
   77737         }
   77738       }
   77739       if( iCol>0 ){
   77740         /* Convert the ORDER BY term into an integer column number iCol,
   77741         ** taking care to preserve the COLLATE clause if it exists */
   77742         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   77743         if( pNew==0 ) return 1;
   77744         pNew->flags |= EP_IntValue;
   77745         pNew->u.iValue = iCol;
   77746         if( pItem->pExpr==pE ){
   77747           pItem->pExpr = pNew;
   77748         }else{
   77749           assert( pItem->pExpr->op==TK_COLLATE );
   77750           assert( pItem->pExpr->pLeft==pE );
   77751           pItem->pExpr->pLeft = pNew;
   77752         }
   77753         sqlite3ExprDelete(db, pE);
   77754         pItem->u.x.iOrderByCol = (u16)iCol;
   77755         pItem->done = 1;
   77756       }else{
   77757         moreToDo = 1;
   77758       }
   77759     }
   77760     pSelect = pSelect->pNext;
   77761   }
   77762   for(i=0; i<pOrderBy->nExpr; i++){
   77763     if( pOrderBy->a[i].done==0 ){
   77764       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
   77765             "column in the result set", i+1);
   77766       return 1;
   77767     }
   77768   }
   77769   return 0;
   77770 }
   77771 
   77772 /*
   77773 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
   77774 ** the SELECT statement pSelect.  If any term is reference to a
   77775 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
   77776 ** field) then convert that term into a copy of the corresponding result set
   77777 ** column.
   77778 **
   77779 ** If any errors are detected, add an error message to pParse and
   77780 ** return non-zero.  Return zero if no errors are seen.
   77781 */
   77782 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
   77783   Parse *pParse,        /* Parsing context.  Leave error messages here */
   77784   Select *pSelect,      /* The SELECT statement containing the clause */
   77785   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
   77786   const char *zType     /* "ORDER" or "GROUP" */
   77787 ){
   77788   int i;
   77789   sqlite3 *db = pParse->db;
   77790   ExprList *pEList;
   77791   struct ExprList_item *pItem;
   77792 
   77793   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
   77794 #if SQLITE_MAX_COLUMN
   77795   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   77796     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
   77797     return 1;
   77798   }
   77799 #endif
   77800   pEList = pSelect->pEList;
   77801   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
   77802   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   77803     if( pItem->u.x.iOrderByCol ){
   77804       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
   77805         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
   77806         return 1;
   77807       }
   77808       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
   77809     }
   77810   }
   77811   return 0;
   77812 }
   77813 
   77814 /*
   77815 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
   77816 ** The Name context of the SELECT statement is pNC.  zType is either
   77817 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
   77818 **
   77819 ** This routine resolves each term of the clause into an expression.
   77820 ** If the order-by term is an integer I between 1 and N (where N is the
   77821 ** number of columns in the result set of the SELECT) then the expression
   77822 ** in the resolution is a copy of the I-th result-set expression.  If
   77823 ** the order-by term is an identifier that corresponds to the AS-name of
   77824 ** a result-set expression, then the term resolves to a copy of the
   77825 ** result-set expression.  Otherwise, the expression is resolved in
   77826 ** the usual way - using sqlite3ResolveExprNames().
   77827 **
   77828 ** This routine returns the number of errors.  If errors occur, then
   77829 ** an appropriate error message might be left in pParse.  (OOM errors
   77830 ** excepted.)
   77831 */
   77832 static int resolveOrderGroupBy(
   77833   NameContext *pNC,     /* The name context of the SELECT statement */
   77834   Select *pSelect,      /* The SELECT statement holding pOrderBy */
   77835   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
   77836   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
   77837 ){
   77838   int i, j;                      /* Loop counters */
   77839   int iCol;                      /* Column number */
   77840   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
   77841   Parse *pParse;                 /* Parsing context */
   77842   int nResult;                   /* Number of terms in the result set */
   77843 
   77844   if( pOrderBy==0 ) return 0;
   77845   nResult = pSelect->pEList->nExpr;
   77846   pParse = pNC->pParse;
   77847   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   77848     Expr *pE = pItem->pExpr;
   77849     Expr *pE2 = sqlite3ExprSkipCollate(pE);
   77850     if( zType[0]!='G' ){
   77851       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
   77852       if( iCol>0 ){
   77853         /* If an AS-name match is found, mark this ORDER BY column as being
   77854         ** a copy of the iCol-th result-set column.  The subsequent call to
   77855         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
   77856         ** copy of the iCol-th result-set expression. */
   77857         pItem->u.x.iOrderByCol = (u16)iCol;
   77858         continue;
   77859       }
   77860     }
   77861     if( sqlite3ExprIsInteger(pE2, &iCol) ){
   77862       /* The ORDER BY term is an integer constant.  Again, set the column
   77863       ** number so that sqlite3ResolveOrderGroupBy() will convert the
   77864       ** order-by term to a copy of the result-set expression */
   77865       if( iCol<1 || iCol>0xffff ){
   77866         resolveOutOfRangeError(pParse, zType, i+1, nResult);
   77867         return 1;
   77868       }
   77869       pItem->u.x.iOrderByCol = (u16)iCol;
   77870       continue;
   77871     }
   77872 
   77873     /* Otherwise, treat the ORDER BY term as an ordinary expression */
   77874     pItem->u.x.iOrderByCol = 0;
   77875     if( sqlite3ResolveExprNames(pNC, pE) ){
   77876       return 1;
   77877     }
   77878     for(j=0; j<pSelect->pEList->nExpr; j++){
   77879       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
   77880         pItem->u.x.iOrderByCol = j+1;
   77881       }
   77882     }
   77883   }
   77884   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
   77885 }
   77886 
   77887 /*
   77888 ** Resolve names in the SELECT statement p and all of its descendents.
   77889 */
   77890 static int resolveSelectStep(Walker *pWalker, Select *p){
   77891   NameContext *pOuterNC;  /* Context that contains this SELECT */
   77892   NameContext sNC;        /* Name context of this SELECT */
   77893   int isCompound;         /* True if p is a compound select */
   77894   int nCompound;          /* Number of compound terms processed so far */
   77895   Parse *pParse;          /* Parsing context */
   77896   ExprList *pEList;       /* Result set expression list */
   77897   int i;                  /* Loop counter */
   77898   ExprList *pGroupBy;     /* The GROUP BY clause */
   77899   Select *pLeftmost;      /* Left-most of SELECT of a compound */
   77900   sqlite3 *db;            /* Database connection */
   77901 
   77902 
   77903   assert( p!=0 );
   77904   if( p->selFlags & SF_Resolved ){
   77905     return WRC_Prune;
   77906   }
   77907   pOuterNC = pWalker->u.pNC;
   77908   pParse = pWalker->pParse;
   77909   db = pParse->db;
   77910 
   77911   /* Normally sqlite3SelectExpand() will be called first and will have
   77912   ** already expanded this SELECT.  However, if this is a subquery within
   77913   ** an expression, sqlite3ResolveExprNames() will be called without a
   77914   ** prior call to sqlite3SelectExpand().  When that happens, let
   77915   ** sqlite3SelectPrep() do all of the processing for this SELECT.
   77916   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
   77917   ** this routine in the correct order.
   77918   */
   77919   if( (p->selFlags & SF_Expanded)==0 ){
   77920     sqlite3SelectPrep(pParse, p, pOuterNC);
   77921     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
   77922   }
   77923 
   77924   isCompound = p->pPrior!=0;
   77925   nCompound = 0;
   77926   pLeftmost = p;
   77927   while( p ){
   77928     assert( (p->selFlags & SF_Expanded)!=0 );
   77929     assert( (p->selFlags & SF_Resolved)==0 );
   77930     p->selFlags |= SF_Resolved;
   77931 
   77932     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
   77933     ** are not allowed to refer to any names, so pass an empty NameContext.
   77934     */
   77935     memset(&sNC, 0, sizeof(sNC));
   77936     sNC.pParse = pParse;
   77937     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
   77938         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
   77939       return WRC_Abort;
   77940     }
   77941 
   77942     /* Recursively resolve names in all subqueries
   77943     */
   77944     for(i=0; i<p->pSrc->nSrc; i++){
   77945       struct SrcList_item *pItem = &p->pSrc->a[i];
   77946       if( pItem->pSelect ){
   77947         NameContext *pNC;         /* Used to iterate name contexts */
   77948         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
   77949         const char *zSavedContext = pParse->zAuthContext;
   77950 
   77951         /* Count the total number of references to pOuterNC and all of its
   77952         ** parent contexts. After resolving references to expressions in
   77953         ** pItem->pSelect, check if this value has changed. If so, then
   77954         ** SELECT statement pItem->pSelect must be correlated. Set the
   77955         ** pItem->isCorrelated flag if this is the case. */
   77956         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
   77957 
   77958         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
   77959         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
   77960         pParse->zAuthContext = zSavedContext;
   77961         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
   77962 
   77963         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
   77964         assert( pItem->isCorrelated==0 && nRef<=0 );
   77965         pItem->isCorrelated = (nRef!=0);
   77966       }
   77967     }
   77968 
   77969     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
   77970     ** resolve the result-set expression list.
   77971     */
   77972     sNC.ncFlags = NC_AllowAgg;
   77973     sNC.pSrcList = p->pSrc;
   77974     sNC.pNext = pOuterNC;
   77975 
   77976     /* Resolve names in the result set. */
   77977     pEList = p->pEList;
   77978     assert( pEList!=0 );
   77979     for(i=0; i<pEList->nExpr; i++){
   77980       Expr *pX = pEList->a[i].pExpr;
   77981       if( sqlite3ResolveExprNames(&sNC, pX) ){
   77982         return WRC_Abort;
   77983       }
   77984     }
   77985 
   77986     /* If there are no aggregate functions in the result-set, and no GROUP BY
   77987     ** expression, do not allow aggregates in any of the other expressions.
   77988     */
   77989     assert( (p->selFlags & SF_Aggregate)==0 );
   77990     pGroupBy = p->pGroupBy;
   77991     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
   77992       p->selFlags |= SF_Aggregate;
   77993     }else{
   77994       sNC.ncFlags &= ~NC_AllowAgg;
   77995     }
   77996 
   77997     /* If a HAVING clause is present, then there must be a GROUP BY clause.
   77998     */
   77999     if( p->pHaving && !pGroupBy ){
   78000       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
   78001       return WRC_Abort;
   78002     }
   78003 
   78004     /* Add the output column list to the name-context before parsing the
   78005     ** other expressions in the SELECT statement. This is so that
   78006     ** expressions in the WHERE clause (etc.) can refer to expressions by
   78007     ** aliases in the result set.
   78008     **
   78009     ** Minor point: If this is the case, then the expression will be
   78010     ** re-evaluated for each reference to it.
   78011     */
   78012     sNC.pEList = p->pEList;
   78013     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
   78014     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
   78015 
   78016     /* The ORDER BY and GROUP BY clauses may not refer to terms in
   78017     ** outer queries
   78018     */
   78019     sNC.pNext = 0;
   78020     sNC.ncFlags |= NC_AllowAgg;
   78021 
   78022     /* Process the ORDER BY clause for singleton SELECT statements.
   78023     ** The ORDER BY clause for compounds SELECT statements is handled
   78024     ** below, after all of the result-sets for all of the elements of
   78025     ** the compound have been resolved.
   78026     */
   78027     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
   78028       return WRC_Abort;
   78029     }
   78030     if( db->mallocFailed ){
   78031       return WRC_Abort;
   78032     }
   78033 
   78034     /* Resolve the GROUP BY clause.  At the same time, make sure
   78035     ** the GROUP BY clause does not contain aggregate functions.
   78036     */
   78037     if( pGroupBy ){
   78038       struct ExprList_item *pItem;
   78039 
   78040       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
   78041         return WRC_Abort;
   78042       }
   78043       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
   78044         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
   78045           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
   78046               "the GROUP BY clause");
   78047           return WRC_Abort;
   78048         }
   78049       }
   78050     }
   78051 
   78052     /* Advance to the next term of the compound
   78053     */
   78054     p = p->pPrior;
   78055     nCompound++;
   78056   }
   78057 
   78058   /* Resolve the ORDER BY on a compound SELECT after all terms of
   78059   ** the compound have been resolved.
   78060   */
   78061   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
   78062     return WRC_Abort;
   78063   }
   78064 
   78065   return WRC_Prune;
   78066 }
   78067 
   78068 /*
   78069 ** This routine walks an expression tree and resolves references to
   78070 ** table columns and result-set columns.  At the same time, do error
   78071 ** checking on function usage and set a flag if any aggregate functions
   78072 ** are seen.
   78073 **
   78074 ** To resolve table columns references we look for nodes (or subtrees) of the
   78075 ** form X.Y.Z or Y.Z or just Z where
   78076 **
   78077 **      X:   The name of a database.  Ex:  "main" or "temp" or
   78078 **           the symbolic name assigned to an ATTACH-ed database.
   78079 **
   78080 **      Y:   The name of a table in a FROM clause.  Or in a trigger
   78081 **           one of the special names "old" or "new".
   78082 **
   78083 **      Z:   The name of a column in table Y.
   78084 **
   78085 ** The node at the root of the subtree is modified as follows:
   78086 **
   78087 **    Expr.op        Changed to TK_COLUMN
   78088 **    Expr.pTab      Points to the Table object for X.Y
   78089 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
   78090 **    Expr.iTable    The VDBE cursor number for X.Y
   78091 **
   78092 **
   78093 ** To resolve result-set references, look for expression nodes of the
   78094 ** form Z (with no X and Y prefix) where the Z matches the right-hand
   78095 ** size of an AS clause in the result-set of a SELECT.  The Z expression
   78096 ** is replaced by a copy of the left-hand side of the result-set expression.
   78097 ** Table-name and function resolution occurs on the substituted expression
   78098 ** tree.  For example, in:
   78099 **
   78100 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
   78101 **
   78102 ** The "x" term of the order by is replaced by "a+b" to render:
   78103 **
   78104 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
   78105 **
   78106 ** Function calls are checked to make sure that the function is
   78107 ** defined and that the correct number of arguments are specified.
   78108 ** If the function is an aggregate function, then the NC_HasAgg flag is
   78109 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
   78110 ** If an expression contains aggregate functions then the EP_Agg
   78111 ** property on the expression is set.
   78112 **
   78113 ** An error message is left in pParse if anything is amiss.  The number
   78114 ** if errors is returned.
   78115 */
   78116 SQLITE_PRIVATE int sqlite3ResolveExprNames(
   78117   NameContext *pNC,       /* Namespace to resolve expressions in. */
   78118   Expr *pExpr             /* The expression to be analyzed. */
   78119 ){
   78120   u8 savedHasAgg;
   78121   Walker w;
   78122 
   78123   if( pExpr==0 ) return 0;
   78124 #if SQLITE_MAX_EXPR_DEPTH>0
   78125   {
   78126     Parse *pParse = pNC->pParse;
   78127     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
   78128       return 1;
   78129     }
   78130     pParse->nHeight += pExpr->nHeight;
   78131   }
   78132 #endif
   78133   savedHasAgg = pNC->ncFlags & NC_HasAgg;
   78134   pNC->ncFlags &= ~NC_HasAgg;
   78135   memset(&w, 0, sizeof(w));
   78136   w.xExprCallback = resolveExprStep;
   78137   w.xSelectCallback = resolveSelectStep;
   78138   w.pParse = pNC->pParse;
   78139   w.u.pNC = pNC;
   78140   sqlite3WalkExpr(&w, pExpr);
   78141 #if SQLITE_MAX_EXPR_DEPTH>0
   78142   pNC->pParse->nHeight -= pExpr->nHeight;
   78143 #endif
   78144   if( pNC->nErr>0 || w.pParse->nErr>0 ){
   78145     ExprSetProperty(pExpr, EP_Error);
   78146   }
   78147   if( pNC->ncFlags & NC_HasAgg ){
   78148     ExprSetProperty(pExpr, EP_Agg);
   78149   }else if( savedHasAgg ){
   78150     pNC->ncFlags |= NC_HasAgg;
   78151   }
   78152   return ExprHasProperty(pExpr, EP_Error);
   78153 }
   78154 
   78155 
   78156 /*
   78157 ** Resolve all names in all expressions of a SELECT and in all
   78158 ** decendents of the SELECT, including compounds off of p->pPrior,
   78159 ** subqueries in expressions, and subqueries used as FROM clause
   78160 ** terms.
   78161 **
   78162 ** See sqlite3ResolveExprNames() for a description of the kinds of
   78163 ** transformations that occur.
   78164 **
   78165 ** All SELECT statements should have been expanded using
   78166 ** sqlite3SelectExpand() prior to invoking this routine.
   78167 */
   78168 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
   78169   Parse *pParse,         /* The parser context */
   78170   Select *p,             /* The SELECT statement being coded. */
   78171   NameContext *pOuterNC  /* Name context for parent SELECT statement */
   78172 ){
   78173   Walker w;
   78174 
   78175   assert( p!=0 );
   78176   memset(&w, 0, sizeof(w));
   78177   w.xExprCallback = resolveExprStep;
   78178   w.xSelectCallback = resolveSelectStep;
   78179   w.pParse = pParse;
   78180   w.u.pNC = pOuterNC;
   78181   sqlite3WalkSelect(&w, p);
   78182 }
   78183 
   78184 /*
   78185 ** Resolve names in expressions that can only reference a single table:
   78186 **
   78187 **    *   CHECK constraints
   78188 **    *   WHERE clauses on partial indices
   78189 **
   78190 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
   78191 ** is set to -1 and the Expr.iColumn value is set to the column number.
   78192 **
   78193 ** Any errors cause an error message to be set in pParse.
   78194 */
   78195 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
   78196   Parse *pParse,      /* Parsing context */
   78197   Table *pTab,        /* The table being referenced */
   78198   int type,           /* NC_IsCheck or NC_PartIdx */
   78199   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
   78200   ExprList *pList     /* Expression list to resolve.  May be NUL. */
   78201 ){
   78202   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
   78203   NameContext sNC;                /* Name context for pParse->pNewTable */
   78204   int i;                          /* Loop counter */
   78205 
   78206   assert( type==NC_IsCheck || type==NC_PartIdx );
   78207   memset(&sNC, 0, sizeof(sNC));
   78208   memset(&sSrc, 0, sizeof(sSrc));
   78209   sSrc.nSrc = 1;
   78210   sSrc.a[0].zName = pTab->zName;
   78211   sSrc.a[0].pTab = pTab;
   78212   sSrc.a[0].iCursor = -1;
   78213   sNC.pParse = pParse;
   78214   sNC.pSrcList = &sSrc;
   78215   sNC.ncFlags = type;
   78216   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
   78217   if( pList ){
   78218     for(i=0; i<pList->nExpr; i++){
   78219       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   78220         return;
   78221       }
   78222     }
   78223   }
   78224 }
   78225 
   78226 /************** End of resolve.c *********************************************/
   78227 /************** Begin file expr.c ********************************************/
   78228 /*
   78229 ** 2001 September 15
   78230 **
   78231 ** The author disclaims copyright to this source code.  In place of
   78232 ** a legal notice, here is a blessing:
   78233 **
   78234 **    May you do good and not evil.
   78235 **    May you find forgiveness for yourself and forgive others.
   78236 **    May you share freely, never taking more than you give.
   78237 **
   78238 *************************************************************************
   78239 ** This file contains routines used for analyzing expressions and
   78240 ** for generating VDBE code that evaluates expressions in SQLite.
   78241 */
   78242 
   78243 /*
   78244 ** Return the 'affinity' of the expression pExpr if any.
   78245 **
   78246 ** If pExpr is a column, a reference to a column via an 'AS' alias,
   78247 ** or a sub-select with a column as the return value, then the
   78248 ** affinity of that column is returned. Otherwise, 0x00 is returned,
   78249 ** indicating no affinity for the expression.
   78250 **
   78251 ** i.e. the WHERE clause expresssions in the following statements all
   78252 ** have an affinity:
   78253 **
   78254 ** CREATE TABLE t1(a);
   78255 ** SELECT * FROM t1 WHERE a;
   78256 ** SELECT a AS b FROM t1 WHERE b;
   78257 ** SELECT * FROM t1 WHERE (select a from t1);
   78258 */
   78259 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
   78260   int op;
   78261   pExpr = sqlite3ExprSkipCollate(pExpr);
   78262   if( pExpr->flags & EP_Generic ) return 0;
   78263   op = pExpr->op;
   78264   if( op==TK_SELECT ){
   78265     assert( pExpr->flags&EP_xIsSelect );
   78266     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   78267   }
   78268 #ifndef SQLITE_OMIT_CAST
   78269   if( op==TK_CAST ){
   78270     assert( !ExprHasProperty(pExpr, EP_IntValue) );
   78271     return sqlite3AffinityType(pExpr->u.zToken, 0);
   78272   }
   78273 #endif
   78274   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
   78275    && pExpr->pTab!=0
   78276   ){
   78277     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
   78278     ** a TK_COLUMN but was previously evaluated and cached in a register */
   78279     int j = pExpr->iColumn;
   78280     if( j<0 ) return SQLITE_AFF_INTEGER;
   78281     assert( pExpr->pTab && j<pExpr->pTab->nCol );
   78282     return pExpr->pTab->aCol[j].affinity;
   78283   }
   78284   return pExpr->affinity;
   78285 }
   78286 
   78287 /*
   78288 ** Set the collating sequence for expression pExpr to be the collating
   78289 ** sequence named by pToken.   Return a pointer to a new Expr node that
   78290 ** implements the COLLATE operator.
   78291 **
   78292 ** If a memory allocation error occurs, that fact is recorded in pParse->db
   78293 ** and the pExpr parameter is returned unchanged.
   78294 */
   78295 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
   78296   Parse *pParse,           /* Parsing context */
   78297   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
   78298   const Token *pCollName   /* Name of collating sequence */
   78299 ){
   78300   if( pCollName->n>0 ){
   78301     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
   78302     if( pNew ){
   78303       pNew->pLeft = pExpr;
   78304       pNew->flags |= EP_Collate|EP_Skip;
   78305       pExpr = pNew;
   78306     }
   78307   }
   78308   return pExpr;
   78309 }
   78310 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
   78311   Token s;
   78312   assert( zC!=0 );
   78313   s.z = zC;
   78314   s.n = sqlite3Strlen30(s.z);
   78315   return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
   78316 }
   78317 
   78318 /*
   78319 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
   78320 ** or likelihood() function at the root of an expression.
   78321 */
   78322 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
   78323   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
   78324     if( ExprHasProperty(pExpr, EP_Unlikely) ){
   78325       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   78326       assert( pExpr->x.pList->nExpr>0 );
   78327       assert( pExpr->op==TK_FUNCTION );
   78328       pExpr = pExpr->x.pList->a[0].pExpr;
   78329     }else{
   78330       assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
   78331       pExpr = pExpr->pLeft;
   78332     }
   78333   }
   78334   return pExpr;
   78335 }
   78336 
   78337 /*
   78338 ** Return the collation sequence for the expression pExpr. If
   78339 ** there is no defined collating sequence, return NULL.
   78340 **
   78341 ** The collating sequence might be determined by a COLLATE operator
   78342 ** or by the presence of a column with a defined collating sequence.
   78343 ** COLLATE operators take first precedence.  Left operands take
   78344 ** precedence over right operands.
   78345 */
   78346 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
   78347   sqlite3 *db = pParse->db;
   78348   CollSeq *pColl = 0;
   78349   Expr *p = pExpr;
   78350   while( p ){
   78351     int op = p->op;
   78352     if( p->flags & EP_Generic ) break;
   78353     if( op==TK_CAST || op==TK_UPLUS ){
   78354       p = p->pLeft;
   78355       continue;
   78356     }
   78357     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
   78358       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
   78359       break;
   78360     }
   78361     if( p->pTab!=0
   78362      && (op==TK_AGG_COLUMN || op==TK_COLUMN
   78363           || op==TK_REGISTER || op==TK_TRIGGER)
   78364     ){
   78365       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
   78366       ** a TK_COLUMN but was previously evaluated and cached in a register */
   78367       int j = p->iColumn;
   78368       if( j>=0 ){
   78369         const char *zColl = p->pTab->aCol[j].zColl;
   78370         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   78371       }
   78372       break;
   78373     }
   78374     if( p->flags & EP_Collate ){
   78375       if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
   78376         p = p->pLeft;
   78377       }else{
   78378         p = p->pRight;
   78379       }
   78380     }else{
   78381       break;
   78382     }
   78383   }
   78384   if( sqlite3CheckCollSeq(pParse, pColl) ){
   78385     pColl = 0;
   78386   }
   78387   return pColl;
   78388 }
   78389 
   78390 /*
   78391 ** pExpr is an operand of a comparison operator.  aff2 is the
   78392 ** type affinity of the other operand.  This routine returns the
   78393 ** type affinity that should be used for the comparison operator.
   78394 */
   78395 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
   78396   char aff1 = sqlite3ExprAffinity(pExpr);
   78397   if( aff1 && aff2 ){
   78398     /* Both sides of the comparison are columns. If one has numeric
   78399     ** affinity, use that. Otherwise use no affinity.
   78400     */
   78401     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
   78402       return SQLITE_AFF_NUMERIC;
   78403     }else{
   78404       return SQLITE_AFF_NONE;
   78405     }
   78406   }else if( !aff1 && !aff2 ){
   78407     /* Neither side of the comparison is a column.  Compare the
   78408     ** results directly.
   78409     */
   78410     return SQLITE_AFF_NONE;
   78411   }else{
   78412     /* One side is a column, the other is not. Use the columns affinity. */
   78413     assert( aff1==0 || aff2==0 );
   78414     return (aff1 + aff2);
   78415   }
   78416 }
   78417 
   78418 /*
   78419 ** pExpr is a comparison operator.  Return the type affinity that should
   78420 ** be applied to both operands prior to doing the comparison.
   78421 */
   78422 static char comparisonAffinity(Expr *pExpr){
   78423   char aff;
   78424   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
   78425           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
   78426           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
   78427   assert( pExpr->pLeft );
   78428   aff = sqlite3ExprAffinity(pExpr->pLeft);
   78429   if( pExpr->pRight ){
   78430     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
   78431   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   78432     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
   78433   }else if( !aff ){
   78434     aff = SQLITE_AFF_NONE;
   78435   }
   78436   return aff;
   78437 }
   78438 
   78439 /*
   78440 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
   78441 ** idx_affinity is the affinity of an indexed column. Return true
   78442 ** if the index with affinity idx_affinity may be used to implement
   78443 ** the comparison in pExpr.
   78444 */
   78445 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
   78446   char aff = comparisonAffinity(pExpr);
   78447   switch( aff ){
   78448     case SQLITE_AFF_NONE:
   78449       return 1;
   78450     case SQLITE_AFF_TEXT:
   78451       return idx_affinity==SQLITE_AFF_TEXT;
   78452     default:
   78453       return sqlite3IsNumericAffinity(idx_affinity);
   78454   }
   78455 }
   78456 
   78457 /*
   78458 ** Return the P5 value that should be used for a binary comparison
   78459 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
   78460 */
   78461 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
   78462   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
   78463   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
   78464   return aff;
   78465 }
   78466 
   78467 /*
   78468 ** Return a pointer to the collation sequence that should be used by
   78469 ** a binary comparison operator comparing pLeft and pRight.
   78470 **
   78471 ** If the left hand expression has a collating sequence type, then it is
   78472 ** used. Otherwise the collation sequence for the right hand expression
   78473 ** is used, or the default (BINARY) if neither expression has a collating
   78474 ** type.
   78475 **
   78476 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
   78477 ** it is not considered.
   78478 */
   78479 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
   78480   Parse *pParse,
   78481   Expr *pLeft,
   78482   Expr *pRight
   78483 ){
   78484   CollSeq *pColl;
   78485   assert( pLeft );
   78486   if( pLeft->flags & EP_Collate ){
   78487     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   78488   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
   78489     pColl = sqlite3ExprCollSeq(pParse, pRight);
   78490   }else{
   78491     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   78492     if( !pColl ){
   78493       pColl = sqlite3ExprCollSeq(pParse, pRight);
   78494     }
   78495   }
   78496   return pColl;
   78497 }
   78498 
   78499 /*
   78500 ** Generate code for a comparison operator.
   78501 */
   78502 static int codeCompare(
   78503   Parse *pParse,    /* The parsing (and code generating) context */
   78504   Expr *pLeft,      /* The left operand */
   78505   Expr *pRight,     /* The right operand */
   78506   int opcode,       /* The comparison opcode */
   78507   int in1, int in2, /* Register holding operands */
   78508   int dest,         /* Jump here if true.  */
   78509   int jumpIfNull    /* If true, jump if either operand is NULL */
   78510 ){
   78511   int p5;
   78512   int addr;
   78513   CollSeq *p4;
   78514 
   78515   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
   78516   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
   78517   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
   78518                            (void*)p4, P4_COLLSEQ);
   78519   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
   78520   return addr;
   78521 }
   78522 
   78523 #if SQLITE_MAX_EXPR_DEPTH>0
   78524 /*
   78525 ** Check that argument nHeight is less than or equal to the maximum
   78526 ** expression depth allowed. If it is not, leave an error message in
   78527 ** pParse.
   78528 */
   78529 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
   78530   int rc = SQLITE_OK;
   78531   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
   78532   if( nHeight>mxHeight ){
   78533     sqlite3ErrorMsg(pParse,
   78534        "Expression tree is too large (maximum depth %d)", mxHeight
   78535     );
   78536     rc = SQLITE_ERROR;
   78537   }
   78538   return rc;
   78539 }
   78540 
   78541 /* The following three functions, heightOfExpr(), heightOfExprList()
   78542 ** and heightOfSelect(), are used to determine the maximum height
   78543 ** of any expression tree referenced by the structure passed as the
   78544 ** first argument.
   78545 **
   78546 ** If this maximum height is greater than the current value pointed
   78547 ** to by pnHeight, the second parameter, then set *pnHeight to that
   78548 ** value.
   78549 */
   78550 static void heightOfExpr(Expr *p, int *pnHeight){
   78551   if( p ){
   78552     if( p->nHeight>*pnHeight ){
   78553       *pnHeight = p->nHeight;
   78554     }
   78555   }
   78556 }
   78557 static void heightOfExprList(ExprList *p, int *pnHeight){
   78558   if( p ){
   78559     int i;
   78560     for(i=0; i<p->nExpr; i++){
   78561       heightOfExpr(p->a[i].pExpr, pnHeight);
   78562     }
   78563   }
   78564 }
   78565 static void heightOfSelect(Select *p, int *pnHeight){
   78566   if( p ){
   78567     heightOfExpr(p->pWhere, pnHeight);
   78568     heightOfExpr(p->pHaving, pnHeight);
   78569     heightOfExpr(p->pLimit, pnHeight);
   78570     heightOfExpr(p->pOffset, pnHeight);
   78571     heightOfExprList(p->pEList, pnHeight);
   78572     heightOfExprList(p->pGroupBy, pnHeight);
   78573     heightOfExprList(p->pOrderBy, pnHeight);
   78574     heightOfSelect(p->pPrior, pnHeight);
   78575   }
   78576 }
   78577 
   78578 /*
   78579 ** Set the Expr.nHeight variable in the structure passed as an
   78580 ** argument. An expression with no children, Expr.pList or
   78581 ** Expr.pSelect member has a height of 1. Any other expression
   78582 ** has a height equal to the maximum height of any other
   78583 ** referenced Expr plus one.
   78584 */
   78585 static void exprSetHeight(Expr *p){
   78586   int nHeight = 0;
   78587   heightOfExpr(p->pLeft, &nHeight);
   78588   heightOfExpr(p->pRight, &nHeight);
   78589   if( ExprHasProperty(p, EP_xIsSelect) ){
   78590     heightOfSelect(p->x.pSelect, &nHeight);
   78591   }else{
   78592     heightOfExprList(p->x.pList, &nHeight);
   78593   }
   78594   p->nHeight = nHeight + 1;
   78595 }
   78596 
   78597 /*
   78598 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
   78599 ** the height is greater than the maximum allowed expression depth,
   78600 ** leave an error in pParse.
   78601 */
   78602 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
   78603   exprSetHeight(p);
   78604   sqlite3ExprCheckHeight(pParse, p->nHeight);
   78605 }
   78606 
   78607 /*
   78608 ** Return the maximum height of any expression tree referenced
   78609 ** by the select statement passed as an argument.
   78610 */
   78611 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
   78612   int nHeight = 0;
   78613   heightOfSelect(p, &nHeight);
   78614   return nHeight;
   78615 }
   78616 #else
   78617   #define exprSetHeight(y)
   78618 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
   78619 
   78620 /*
   78621 ** This routine is the core allocator for Expr nodes.
   78622 **
   78623 ** Construct a new expression node and return a pointer to it.  Memory
   78624 ** for this node and for the pToken argument is a single allocation
   78625 ** obtained from sqlite3DbMalloc().  The calling function
   78626 ** is responsible for making sure the node eventually gets freed.
   78627 **
   78628 ** If dequote is true, then the token (if it exists) is dequoted.
   78629 ** If dequote is false, no dequoting is performance.  The deQuote
   78630 ** parameter is ignored if pToken is NULL or if the token does not
   78631 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
   78632 ** then the EP_DblQuoted flag is set on the expression node.
   78633 **
   78634 ** Special case:  If op==TK_INTEGER and pToken points to a string that
   78635 ** can be translated into a 32-bit integer, then the token is not
   78636 ** stored in u.zToken.  Instead, the integer values is written
   78637 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
   78638 ** is allocated to hold the integer text and the dequote flag is ignored.
   78639 */
   78640 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
   78641   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   78642   int op,                 /* Expression opcode */
   78643   const Token *pToken,    /* Token argument.  Might be NULL */
   78644   int dequote             /* True to dequote */
   78645 ){
   78646   Expr *pNew;
   78647   int nExtra = 0;
   78648   int iValue = 0;
   78649 
   78650   if( pToken ){
   78651     if( op!=TK_INTEGER || pToken->z==0
   78652           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
   78653       nExtra = pToken->n+1;
   78654       assert( iValue>=0 );
   78655     }
   78656   }
   78657   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
   78658   if( pNew ){
   78659     pNew->op = (u8)op;
   78660     pNew->iAgg = -1;
   78661     if( pToken ){
   78662       if( nExtra==0 ){
   78663         pNew->flags |= EP_IntValue;
   78664         pNew->u.iValue = iValue;
   78665       }else{
   78666         int c;
   78667         pNew->u.zToken = (char*)&pNew[1];
   78668         assert( pToken->z!=0 || pToken->n==0 );
   78669         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
   78670         pNew->u.zToken[pToken->n] = 0;
   78671         if( dequote && nExtra>=3
   78672              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
   78673           sqlite3Dequote(pNew->u.zToken);
   78674           if( c=='"' ) pNew->flags |= EP_DblQuoted;
   78675         }
   78676       }
   78677     }
   78678 #if SQLITE_MAX_EXPR_DEPTH>0
   78679     pNew->nHeight = 1;
   78680 #endif
   78681   }
   78682   return pNew;
   78683 }
   78684 
   78685 /*
   78686 ** Allocate a new expression node from a zero-terminated token that has
   78687 ** already been dequoted.
   78688 */
   78689 SQLITE_PRIVATE Expr *sqlite3Expr(
   78690   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   78691   int op,                 /* Expression opcode */
   78692   const char *zToken      /* Token argument.  Might be NULL */
   78693 ){
   78694   Token x;
   78695   x.z = zToken;
   78696   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
   78697   return sqlite3ExprAlloc(db, op, &x, 0);
   78698 }
   78699 
   78700 /*
   78701 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
   78702 **
   78703 ** If pRoot==NULL that means that a memory allocation error has occurred.
   78704 ** In that case, delete the subtrees pLeft and pRight.
   78705 */
   78706 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
   78707   sqlite3 *db,
   78708   Expr *pRoot,
   78709   Expr *pLeft,
   78710   Expr *pRight
   78711 ){
   78712   if( pRoot==0 ){
   78713     assert( db->mallocFailed );
   78714     sqlite3ExprDelete(db, pLeft);
   78715     sqlite3ExprDelete(db, pRight);
   78716   }else{
   78717     if( pRight ){
   78718       pRoot->pRight = pRight;
   78719       pRoot->flags |= EP_Collate & pRight->flags;
   78720     }
   78721     if( pLeft ){
   78722       pRoot->pLeft = pLeft;
   78723       pRoot->flags |= EP_Collate & pLeft->flags;
   78724     }
   78725     exprSetHeight(pRoot);
   78726   }
   78727 }
   78728 
   78729 /*
   78730 ** Allocate a Expr node which joins as many as two subtrees.
   78731 **
   78732 ** One or both of the subtrees can be NULL.  Return a pointer to the new
   78733 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
   78734 ** free the subtrees and return NULL.
   78735 */
   78736 SQLITE_PRIVATE Expr *sqlite3PExpr(
   78737   Parse *pParse,          /* Parsing context */
   78738   int op,                 /* Expression opcode */
   78739   Expr *pLeft,            /* Left operand */
   78740   Expr *pRight,           /* Right operand */
   78741   const Token *pToken     /* Argument token */
   78742 ){
   78743   Expr *p;
   78744   if( op==TK_AND && pLeft && pRight ){
   78745     /* Take advantage of short-circuit false optimization for AND */
   78746     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
   78747   }else{
   78748     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
   78749     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
   78750   }
   78751   if( p ) {
   78752     sqlite3ExprCheckHeight(pParse, p->nHeight);
   78753   }
   78754   return p;
   78755 }
   78756 
   78757 /*
   78758 ** If the expression is always either TRUE or FALSE (respectively),
   78759 ** then return 1.  If one cannot determine the truth value of the
   78760 ** expression at compile-time return 0.
   78761 **
   78762 ** This is an optimization.  If is OK to return 0 here even if
   78763 ** the expression really is always false or false (a false negative).
   78764 ** But it is a bug to return 1 if the expression might have different
   78765 ** boolean values in different circumstances (a false positive.)
   78766 **
   78767 ** Note that if the expression is part of conditional for a
   78768 ** LEFT JOIN, then we cannot determine at compile-time whether or not
   78769 ** is it true or false, so always return 0.
   78770 */
   78771 static int exprAlwaysTrue(Expr *p){
   78772   int v = 0;
   78773   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
   78774   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
   78775   return v!=0;
   78776 }
   78777 static int exprAlwaysFalse(Expr *p){
   78778   int v = 0;
   78779   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
   78780   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
   78781   return v==0;
   78782 }
   78783 
   78784 /*
   78785 ** Join two expressions using an AND operator.  If either expression is
   78786 ** NULL, then just return the other expression.
   78787 **
   78788 ** If one side or the other of the AND is known to be false, then instead
   78789 ** of returning an AND expression, just return a constant expression with
   78790 ** a value of false.
   78791 */
   78792 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
   78793   if( pLeft==0 ){
   78794     return pRight;
   78795   }else if( pRight==0 ){
   78796     return pLeft;
   78797   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
   78798     sqlite3ExprDelete(db, pLeft);
   78799     sqlite3ExprDelete(db, pRight);
   78800     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
   78801   }else{
   78802     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
   78803     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
   78804     return pNew;
   78805   }
   78806 }
   78807 
   78808 /*
   78809 ** Construct a new expression node for a function with multiple
   78810 ** arguments.
   78811 */
   78812 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
   78813   Expr *pNew;
   78814   sqlite3 *db = pParse->db;
   78815   assert( pToken );
   78816   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
   78817   if( pNew==0 ){
   78818     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
   78819     return 0;
   78820   }
   78821   pNew->x.pList = pList;
   78822   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   78823   sqlite3ExprSetHeight(pParse, pNew);
   78824   return pNew;
   78825 }
   78826 
   78827 /*
   78828 ** Assign a variable number to an expression that encodes a wildcard
   78829 ** in the original SQL statement.
   78830 **
   78831 ** Wildcards consisting of a single "?" are assigned the next sequential
   78832 ** variable number.
   78833 **
   78834 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
   78835 ** sure "nnn" is not too be to avoid a denial of service attack when
   78836 ** the SQL statement comes from an external source.
   78837 **
   78838 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
   78839 ** as the previous instance of the same wildcard.  Or if this is the first
   78840 ** instance of the wildcard, the next sequenial variable number is
   78841 ** assigned.
   78842 */
   78843 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
   78844   sqlite3 *db = pParse->db;
   78845   const char *z;
   78846 
   78847   if( pExpr==0 ) return;
   78848   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
   78849   z = pExpr->u.zToken;
   78850   assert( z!=0 );
   78851   assert( z[0]!=0 );
   78852   if( z[1]==0 ){
   78853     /* Wildcard of the form "?".  Assign the next variable number */
   78854     assert( z[0]=='?' );
   78855     pExpr->iColumn = (ynVar)(++pParse->nVar);
   78856   }else{
   78857     ynVar x = 0;
   78858     u32 n = sqlite3Strlen30(z);
   78859     if( z[0]=='?' ){
   78860       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
   78861       ** use it as the variable number */
   78862       i64 i;
   78863       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
   78864       pExpr->iColumn = x = (ynVar)i;
   78865       testcase( i==0 );
   78866       testcase( i==1 );
   78867       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
   78868       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
   78869       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   78870         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
   78871             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
   78872         x = 0;
   78873       }
   78874       if( i>pParse->nVar ){
   78875         pParse->nVar = (int)i;
   78876       }
   78877     }else{
   78878       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
   78879       ** number as the prior appearance of the same name, or if the name
   78880       ** has never appeared before, reuse the same variable number
   78881       */
   78882       ynVar i;
   78883       for(i=0; i<pParse->nzVar; i++){
   78884         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
   78885           pExpr->iColumn = x = (ynVar)i+1;
   78886           break;
   78887         }
   78888       }
   78889       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
   78890     }
   78891     if( x>0 ){
   78892       if( x>pParse->nzVar ){
   78893         char **a;
   78894         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
   78895         if( a==0 ) return;  /* Error reported through db->mallocFailed */
   78896         pParse->azVar = a;
   78897         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
   78898         pParse->nzVar = x;
   78899       }
   78900       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
   78901         sqlite3DbFree(db, pParse->azVar[x-1]);
   78902         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
   78903       }
   78904     }
   78905   }
   78906   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   78907     sqlite3ErrorMsg(pParse, "too many SQL variables");
   78908   }
   78909 }
   78910 
   78911 /*
   78912 ** Recursively delete an expression tree.
   78913 */
   78914 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
   78915   if( p==0 ) return;
   78916   /* Sanity check: Assert that the IntValue is non-negative if it exists */
   78917   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
   78918   if( !ExprHasProperty(p, EP_TokenOnly) ){
   78919     /* The Expr.x union is never used at the same time as Expr.pRight */
   78920     assert( p->x.pList==0 || p->pRight==0 );
   78921     sqlite3ExprDelete(db, p->pLeft);
   78922     sqlite3ExprDelete(db, p->pRight);
   78923     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
   78924     if( ExprHasProperty(p, EP_xIsSelect) ){
   78925       sqlite3SelectDelete(db, p->x.pSelect);
   78926     }else{
   78927       sqlite3ExprListDelete(db, p->x.pList);
   78928     }
   78929   }
   78930   if( !ExprHasProperty(p, EP_Static) ){
   78931     sqlite3DbFree(db, p);
   78932   }
   78933 }
   78934 
   78935 /*
   78936 ** Return the number of bytes allocated for the expression structure
   78937 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
   78938 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
   78939 */
   78940 static int exprStructSize(Expr *p){
   78941   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
   78942   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
   78943   return EXPR_FULLSIZE;
   78944 }
   78945 
   78946 /*
   78947 ** The dupedExpr*Size() routines each return the number of bytes required
   78948 ** to store a copy of an expression or expression tree.  They differ in
   78949 ** how much of the tree is measured.
   78950 **
   78951 **     dupedExprStructSize()     Size of only the Expr structure
   78952 **     dupedExprNodeSize()       Size of Expr + space for token
   78953 **     dupedExprSize()           Expr + token + subtree components
   78954 **
   78955 ***************************************************************************
   78956 **
   78957 ** The dupedExprStructSize() function returns two values OR-ed together:
   78958 ** (1) the space required for a copy of the Expr structure only and
   78959 ** (2) the EP_xxx flags that indicate what the structure size should be.
   78960 ** The return values is always one of:
   78961 **
   78962 **      EXPR_FULLSIZE
   78963 **      EXPR_REDUCEDSIZE   | EP_Reduced
   78964 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
   78965 **
   78966 ** The size of the structure can be found by masking the return value
   78967 ** of this routine with 0xfff.  The flags can be found by masking the
   78968 ** return value with EP_Reduced|EP_TokenOnly.
   78969 **
   78970 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
   78971 ** (unreduced) Expr objects as they or originally constructed by the parser.
   78972 ** During expression analysis, extra information is computed and moved into
   78973 ** later parts of teh Expr object and that extra information might get chopped
   78974 ** off if the expression is reduced.  Note also that it does not work to
   78975 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
   78976 ** to reduce a pristine expression tree from the parser.  The implementation
   78977 ** of dupedExprStructSize() contain multiple assert() statements that attempt
   78978 ** to enforce this constraint.
   78979 */
   78980 static int dupedExprStructSize(Expr *p, int flags){
   78981   int nSize;
   78982   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   78983   assert( EXPR_FULLSIZE<=0xfff );
   78984   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
   78985   if( 0==(flags&EXPRDUP_REDUCE) ){
   78986     nSize = EXPR_FULLSIZE;
   78987   }else{
   78988     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
   78989     assert( !ExprHasProperty(p, EP_FromJoin) );
   78990     assert( !ExprHasProperty(p, EP_MemToken) );
   78991     assert( !ExprHasProperty(p, EP_NoReduce) );
   78992     if( p->pLeft || p->x.pList ){
   78993       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
   78994     }else{
   78995       assert( p->pRight==0 );
   78996       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
   78997     }
   78998   }
   78999   return nSize;
   79000 }
   79001 
   79002 /*
   79003 ** This function returns the space in bytes required to store the copy
   79004 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
   79005 ** string is defined.)
   79006 */
   79007 static int dupedExprNodeSize(Expr *p, int flags){
   79008   int nByte = dupedExprStructSize(p, flags) & 0xfff;
   79009   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   79010     nByte += sqlite3Strlen30(p->u.zToken)+1;
   79011   }
   79012   return ROUND8(nByte);
   79013 }
   79014 
   79015 /*
   79016 ** Return the number of bytes required to create a duplicate of the
   79017 ** expression passed as the first argument. The second argument is a
   79018 ** mask containing EXPRDUP_XXX flags.
   79019 **
   79020 ** The value returned includes space to create a copy of the Expr struct
   79021 ** itself and the buffer referred to by Expr.u.zToken, if any.
   79022 **
   79023 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
   79024 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
   79025 ** and Expr.pRight variables (but not for any structures pointed to or
   79026 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
   79027 */
   79028 static int dupedExprSize(Expr *p, int flags){
   79029   int nByte = 0;
   79030   if( p ){
   79031     nByte = dupedExprNodeSize(p, flags);
   79032     if( flags&EXPRDUP_REDUCE ){
   79033       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
   79034     }
   79035   }
   79036   return nByte;
   79037 }
   79038 
   79039 /*
   79040 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
   79041 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
   79042 ** to store the copy of expression p, the copies of p->u.zToken
   79043 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
   79044 ** if any. Before returning, *pzBuffer is set to the first byte passed the
   79045 ** portion of the buffer copied into by this function.
   79046 */
   79047 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
   79048   Expr *pNew = 0;                      /* Value to return */
   79049   if( p ){
   79050     const int isReduced = (flags&EXPRDUP_REDUCE);
   79051     u8 *zAlloc;
   79052     u32 staticFlag = 0;
   79053 
   79054     assert( pzBuffer==0 || isReduced );
   79055 
   79056     /* Figure out where to write the new Expr structure. */
   79057     if( pzBuffer ){
   79058       zAlloc = *pzBuffer;
   79059       staticFlag = EP_Static;
   79060     }else{
   79061       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
   79062     }
   79063     pNew = (Expr *)zAlloc;
   79064 
   79065     if( pNew ){
   79066       /* Set nNewSize to the size allocated for the structure pointed to
   79067       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
   79068       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
   79069       ** by the copy of the p->u.zToken string (if any).
   79070       */
   79071       const unsigned nStructSize = dupedExprStructSize(p, flags);
   79072       const int nNewSize = nStructSize & 0xfff;
   79073       int nToken;
   79074       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   79075         nToken = sqlite3Strlen30(p->u.zToken) + 1;
   79076       }else{
   79077         nToken = 0;
   79078       }
   79079       if( isReduced ){
   79080         assert( ExprHasProperty(p, EP_Reduced)==0 );
   79081         memcpy(zAlloc, p, nNewSize);
   79082       }else{
   79083         int nSize = exprStructSize(p);
   79084         memcpy(zAlloc, p, nSize);
   79085         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
   79086       }
   79087 
   79088       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
   79089       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
   79090       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
   79091       pNew->flags |= staticFlag;
   79092 
   79093       /* Copy the p->u.zToken string, if any. */
   79094       if( nToken ){
   79095         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
   79096         memcpy(zToken, p->u.zToken, nToken);
   79097       }
   79098 
   79099       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
   79100         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
   79101         if( ExprHasProperty(p, EP_xIsSelect) ){
   79102           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
   79103         }else{
   79104           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
   79105         }
   79106       }
   79107 
   79108       /* Fill in pNew->pLeft and pNew->pRight. */
   79109       if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
   79110         zAlloc += dupedExprNodeSize(p, flags);
   79111         if( ExprHasProperty(pNew, EP_Reduced) ){
   79112           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
   79113           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
   79114         }
   79115         if( pzBuffer ){
   79116           *pzBuffer = zAlloc;
   79117         }
   79118       }else{
   79119         if( !ExprHasProperty(p, EP_TokenOnly) ){
   79120           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
   79121           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
   79122         }
   79123       }
   79124 
   79125     }
   79126   }
   79127   return pNew;
   79128 }
   79129 
   79130 /*
   79131 ** Create and return a deep copy of the object passed as the second
   79132 ** argument. If an OOM condition is encountered, NULL is returned
   79133 ** and the db->mallocFailed flag set.
   79134 */
   79135 #ifndef SQLITE_OMIT_CTE
   79136 static With *withDup(sqlite3 *db, With *p){
   79137   With *pRet = 0;
   79138   if( p ){
   79139     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
   79140     pRet = sqlite3DbMallocZero(db, nByte);
   79141     if( pRet ){
   79142       int i;
   79143       pRet->nCte = p->nCte;
   79144       for(i=0; i<p->nCte; i++){
   79145         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
   79146         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
   79147         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
   79148       }
   79149     }
   79150   }
   79151   return pRet;
   79152 }
   79153 #else
   79154 # define withDup(x,y) 0
   79155 #endif
   79156 
   79157 /*
   79158 ** The following group of routines make deep copies of expressions,
   79159 ** expression lists, ID lists, and select statements.  The copies can
   79160 ** be deleted (by being passed to their respective ...Delete() routines)
   79161 ** without effecting the originals.
   79162 **
   79163 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
   79164 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
   79165 ** by subsequent calls to sqlite*ListAppend() routines.
   79166 **
   79167 ** Any tables that the SrcList might point to are not duplicated.
   79168 **
   79169 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
   79170 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
   79171 ** truncated version of the usual Expr structure that will be stored as
   79172 ** part of the in-memory representation of the database schema.
   79173 */
   79174 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
   79175   return exprDup(db, p, flags, 0);
   79176 }
   79177 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
   79178   ExprList *pNew;
   79179   struct ExprList_item *pItem, *pOldItem;
   79180   int i;
   79181   if( p==0 ) return 0;
   79182   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   79183   if( pNew==0 ) return 0;
   79184   pNew->nExpr = i = p->nExpr;
   79185   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
   79186   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
   79187   if( pItem==0 ){
   79188     sqlite3DbFree(db, pNew);
   79189     return 0;
   79190   }
   79191   pOldItem = p->a;
   79192   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
   79193     Expr *pOldExpr = pOldItem->pExpr;
   79194     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   79195     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   79196     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   79197     pItem->sortOrder = pOldItem->sortOrder;
   79198     pItem->done = 0;
   79199     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
   79200     pItem->u = pOldItem->u;
   79201   }
   79202   return pNew;
   79203 }
   79204 
   79205 /*
   79206 ** If cursors, triggers, views and subqueries are all omitted from
   79207 ** the build, then none of the following routines, except for
   79208 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
   79209 ** called with a NULL argument.
   79210 */
   79211 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
   79212  || !defined(SQLITE_OMIT_SUBQUERY)
   79213 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   79214   SrcList *pNew;
   79215   int i;
   79216   int nByte;
   79217   if( p==0 ) return 0;
   79218   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
   79219   pNew = sqlite3DbMallocRaw(db, nByte );
   79220   if( pNew==0 ) return 0;
   79221   pNew->nSrc = pNew->nAlloc = p->nSrc;
   79222   for(i=0; i<p->nSrc; i++){
   79223     struct SrcList_item *pNewItem = &pNew->a[i];
   79224     struct SrcList_item *pOldItem = &p->a[i];
   79225     Table *pTab;
   79226     pNewItem->pSchema = pOldItem->pSchema;
   79227     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
   79228     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   79229     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
   79230     pNewItem->jointype = pOldItem->jointype;
   79231     pNewItem->iCursor = pOldItem->iCursor;
   79232     pNewItem->addrFillSub = pOldItem->addrFillSub;
   79233     pNewItem->regReturn = pOldItem->regReturn;
   79234     pNewItem->isCorrelated = pOldItem->isCorrelated;
   79235     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
   79236     pNewItem->isRecursive = pOldItem->isRecursive;
   79237     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
   79238     pNewItem->notIndexed = pOldItem->notIndexed;
   79239     pNewItem->pIndex = pOldItem->pIndex;
   79240     pTab = pNewItem->pTab = pOldItem->pTab;
   79241     if( pTab ){
   79242       pTab->nRef++;
   79243     }
   79244     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
   79245     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
   79246     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
   79247     pNewItem->colUsed = pOldItem->colUsed;
   79248   }
   79249   return pNew;
   79250 }
   79251 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
   79252   IdList *pNew;
   79253   int i;
   79254   if( p==0 ) return 0;
   79255   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   79256   if( pNew==0 ) return 0;
   79257   pNew->nId = p->nId;
   79258   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
   79259   if( pNew->a==0 ){
   79260     sqlite3DbFree(db, pNew);
   79261     return 0;
   79262   }
   79263   /* Note that because the size of the allocation for p->a[] is not
   79264   ** necessarily a power of two, sqlite3IdListAppend() may not be called
   79265   ** on the duplicate created by this function. */
   79266   for(i=0; i<p->nId; i++){
   79267     struct IdList_item *pNewItem = &pNew->a[i];
   79268     struct IdList_item *pOldItem = &p->a[i];
   79269     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   79270     pNewItem->idx = pOldItem->idx;
   79271   }
   79272   return pNew;
   79273 }
   79274 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   79275   Select *pNew, *pPrior;
   79276   if( p==0 ) return 0;
   79277   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
   79278   if( pNew==0 ) return 0;
   79279   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
   79280   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
   79281   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
   79282   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
   79283   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
   79284   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
   79285   pNew->op = p->op;
   79286   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
   79287   if( pPrior ) pPrior->pNext = pNew;
   79288   pNew->pNext = 0;
   79289   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
   79290   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
   79291   pNew->iLimit = 0;
   79292   pNew->iOffset = 0;
   79293   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
   79294   pNew->addrOpenEphm[0] = -1;
   79295   pNew->addrOpenEphm[1] = -1;
   79296   pNew->nSelectRow = p->nSelectRow;
   79297   pNew->pWith = withDup(db, p->pWith);
   79298   return pNew;
   79299 }
   79300 #else
   79301 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   79302   assert( p==0 );
   79303   return 0;
   79304 }
   79305 #endif
   79306 
   79307 
   79308 /*
   79309 ** Add a new element to the end of an expression list.  If pList is
   79310 ** initially NULL, then create a new expression list.
   79311 **
   79312 ** If a memory allocation error occurs, the entire list is freed and
   79313 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
   79314 ** that the new entry was successfully appended.
   79315 */
   79316 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
   79317   Parse *pParse,          /* Parsing context */
   79318   ExprList *pList,        /* List to which to append. Might be NULL */
   79319   Expr *pExpr             /* Expression to be appended. Might be NULL */
   79320 ){
   79321   sqlite3 *db = pParse->db;
   79322   if( pList==0 ){
   79323     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
   79324     if( pList==0 ){
   79325       goto no_mem;
   79326     }
   79327     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
   79328     if( pList->a==0 ) goto no_mem;
   79329   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
   79330     struct ExprList_item *a;
   79331     assert( pList->nExpr>0 );
   79332     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
   79333     if( a==0 ){
   79334       goto no_mem;
   79335     }
   79336     pList->a = a;
   79337   }
   79338   assert( pList->a!=0 );
   79339   if( 1 ){
   79340     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
   79341     memset(pItem, 0, sizeof(*pItem));
   79342     pItem->pExpr = pExpr;
   79343   }
   79344   return pList;
   79345 
   79346 no_mem:
   79347   /* Avoid leaking memory if malloc has failed. */
   79348   sqlite3ExprDelete(db, pExpr);
   79349   sqlite3ExprListDelete(db, pList);
   79350   return 0;
   79351 }
   79352 
   79353 /*
   79354 ** Set the ExprList.a[].zName element of the most recently added item
   79355 ** on the expression list.
   79356 **
   79357 ** pList might be NULL following an OOM error.  But pName should never be
   79358 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   79359 ** is set.
   79360 */
   79361 SQLITE_PRIVATE void sqlite3ExprListSetName(
   79362   Parse *pParse,          /* Parsing context */
   79363   ExprList *pList,        /* List to which to add the span. */
   79364   Token *pName,           /* Name to be added */
   79365   int dequote             /* True to cause the name to be dequoted */
   79366 ){
   79367   assert( pList!=0 || pParse->db->mallocFailed!=0 );
   79368   if( pList ){
   79369     struct ExprList_item *pItem;
   79370     assert( pList->nExpr>0 );
   79371     pItem = &pList->a[pList->nExpr-1];
   79372     assert( pItem->zName==0 );
   79373     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
   79374     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
   79375   }
   79376 }
   79377 
   79378 /*
   79379 ** Set the ExprList.a[].zSpan element of the most recently added item
   79380 ** on the expression list.
   79381 **
   79382 ** pList might be NULL following an OOM error.  But pSpan should never be
   79383 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   79384 ** is set.
   79385 */
   79386 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
   79387   Parse *pParse,          /* Parsing context */
   79388   ExprList *pList,        /* List to which to add the span. */
   79389   ExprSpan *pSpan         /* The span to be added */
   79390 ){
   79391   sqlite3 *db = pParse->db;
   79392   assert( pList!=0 || db->mallocFailed!=0 );
   79393   if( pList ){
   79394     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
   79395     assert( pList->nExpr>0 );
   79396     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
   79397     sqlite3DbFree(db, pItem->zSpan);
   79398     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   79399                                     (int)(pSpan->zEnd - pSpan->zStart));
   79400   }
   79401 }
   79402 
   79403 /*
   79404 ** If the expression list pEList contains more than iLimit elements,
   79405 ** leave an error message in pParse.
   79406 */
   79407 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
   79408   Parse *pParse,
   79409   ExprList *pEList,
   79410   const char *zObject
   79411 ){
   79412   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
   79413   testcase( pEList && pEList->nExpr==mx );
   79414   testcase( pEList && pEList->nExpr==mx+1 );
   79415   if( pEList && pEList->nExpr>mx ){
   79416     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
   79417   }
   79418 }
   79419 
   79420 /*
   79421 ** Delete an entire expression list.
   79422 */
   79423 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
   79424   int i;
   79425   struct ExprList_item *pItem;
   79426   if( pList==0 ) return;
   79427   assert( pList->a!=0 || pList->nExpr==0 );
   79428   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   79429     sqlite3ExprDelete(db, pItem->pExpr);
   79430     sqlite3DbFree(db, pItem->zName);
   79431     sqlite3DbFree(db, pItem->zSpan);
   79432   }
   79433   sqlite3DbFree(db, pList->a);
   79434   sqlite3DbFree(db, pList);
   79435 }
   79436 
   79437 /*
   79438 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
   79439 ** to an integer.  These routines are checking an expression to see
   79440 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
   79441 ** not constant.
   79442 **
   79443 ** These callback routines are used to implement the following:
   79444 **
   79445 **     sqlite3ExprIsConstant()
   79446 **     sqlite3ExprIsConstantNotJoin()
   79447 **     sqlite3ExprIsConstantOrFunction()
   79448 **
   79449 */
   79450 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
   79451 
   79452   /* If pWalker->u.i is 3 then any term of the expression that comes from
   79453   ** the ON or USING clauses of a join disqualifies the expression
   79454   ** from being considered constant. */
   79455   if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
   79456     pWalker->u.i = 0;
   79457     return WRC_Abort;
   79458   }
   79459 
   79460   switch( pExpr->op ){
   79461     /* Consider functions to be constant if all their arguments are constant
   79462     ** and either pWalker->u.i==2 or the function as the SQLITE_FUNC_CONST
   79463     ** flag. */
   79464     case TK_FUNCTION:
   79465       if( pWalker->u.i==2 || ExprHasProperty(pExpr,EP_Constant) ){
   79466         return WRC_Continue;
   79467       }
   79468       /* Fall through */
   79469     case TK_ID:
   79470     case TK_COLUMN:
   79471     case TK_AGG_FUNCTION:
   79472     case TK_AGG_COLUMN:
   79473       testcase( pExpr->op==TK_ID );
   79474       testcase( pExpr->op==TK_COLUMN );
   79475       testcase( pExpr->op==TK_AGG_FUNCTION );
   79476       testcase( pExpr->op==TK_AGG_COLUMN );
   79477       pWalker->u.i = 0;
   79478       return WRC_Abort;
   79479     default:
   79480       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
   79481       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
   79482       return WRC_Continue;
   79483   }
   79484 }
   79485 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
   79486   UNUSED_PARAMETER(NotUsed);
   79487   pWalker->u.i = 0;
   79488   return WRC_Abort;
   79489 }
   79490 static int exprIsConst(Expr *p, int initFlag){
   79491   Walker w;
   79492   memset(&w, 0, sizeof(w));
   79493   w.u.i = initFlag;
   79494   w.xExprCallback = exprNodeIsConstant;
   79495   w.xSelectCallback = selectNodeIsConstant;
   79496   sqlite3WalkExpr(&w, p);
   79497   return w.u.i;
   79498 }
   79499 
   79500 /*
   79501 ** Walk an expression tree.  Return 1 if the expression is constant
   79502 ** and 0 if it involves variables or function calls.
   79503 **
   79504 ** For the purposes of this function, a double-quoted string (ex: "abc")
   79505 ** is considered a variable but a single-quoted string (ex: 'abc') is
   79506 ** a constant.
   79507 */
   79508 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
   79509   return exprIsConst(p, 1);
   79510 }
   79511 
   79512 /*
   79513 ** Walk an expression tree.  Return 1 if the expression is constant
   79514 ** that does no originate from the ON or USING clauses of a join.
   79515 ** Return 0 if it involves variables or function calls or terms from
   79516 ** an ON or USING clause.
   79517 */
   79518 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
   79519   return exprIsConst(p, 3);
   79520 }
   79521 
   79522 /*
   79523 ** Walk an expression tree.  Return 1 if the expression is constant
   79524 ** or a function call with constant arguments.  Return and 0 if there
   79525 ** are any variables.
   79526 **
   79527 ** For the purposes of this function, a double-quoted string (ex: "abc")
   79528 ** is considered a variable but a single-quoted string (ex: 'abc') is
   79529 ** a constant.
   79530 */
   79531 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
   79532   return exprIsConst(p, 2);
   79533 }
   79534 
   79535 /*
   79536 ** If the expression p codes a constant integer that is small enough
   79537 ** to fit in a 32-bit integer, return 1 and put the value of the integer
   79538 ** in *pValue.  If the expression is not an integer or if it is too big
   79539 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
   79540 */
   79541 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
   79542   int rc = 0;
   79543 
   79544   /* If an expression is an integer literal that fits in a signed 32-bit
   79545   ** integer, then the EP_IntValue flag will have already been set */
   79546   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
   79547            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
   79548 
   79549   if( p->flags & EP_IntValue ){
   79550     *pValue = p->u.iValue;
   79551     return 1;
   79552   }
   79553   switch( p->op ){
   79554     case TK_UPLUS: {
   79555       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
   79556       break;
   79557     }
   79558     case TK_UMINUS: {
   79559       int v;
   79560       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
   79561         assert( v!=(-2147483647-1) );
   79562         *pValue = -v;
   79563         rc = 1;
   79564       }
   79565       break;
   79566     }
   79567     default: break;
   79568   }
   79569   return rc;
   79570 }
   79571 
   79572 /*
   79573 ** Return FALSE if there is no chance that the expression can be NULL.
   79574 **
   79575 ** If the expression might be NULL or if the expression is too complex
   79576 ** to tell return TRUE.
   79577 **
   79578 ** This routine is used as an optimization, to skip OP_IsNull opcodes
   79579 ** when we know that a value cannot be NULL.  Hence, a false positive
   79580 ** (returning TRUE when in fact the expression can never be NULL) might
   79581 ** be a small performance hit but is otherwise harmless.  On the other
   79582 ** hand, a false negative (returning FALSE when the result could be NULL)
   79583 ** will likely result in an incorrect answer.  So when in doubt, return
   79584 ** TRUE.
   79585 */
   79586 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
   79587   u8 op;
   79588   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   79589   op = p->op;
   79590   if( op==TK_REGISTER ) op = p->op2;
   79591   switch( op ){
   79592     case TK_INTEGER:
   79593     case TK_STRING:
   79594     case TK_FLOAT:
   79595     case TK_BLOB:
   79596       return 0;
   79597     case TK_COLUMN:
   79598       assert( p->pTab!=0 );
   79599       return p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0;
   79600     default:
   79601       return 1;
   79602   }
   79603 }
   79604 
   79605 /*
   79606 ** Return TRUE if the given expression is a constant which would be
   79607 ** unchanged by OP_Affinity with the affinity given in the second
   79608 ** argument.
   79609 **
   79610 ** This routine is used to determine if the OP_Affinity operation
   79611 ** can be omitted.  When in doubt return FALSE.  A false negative
   79612 ** is harmless.  A false positive, however, can result in the wrong
   79613 ** answer.
   79614 */
   79615 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
   79616   u8 op;
   79617   if( aff==SQLITE_AFF_NONE ) return 1;
   79618   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   79619   op = p->op;
   79620   if( op==TK_REGISTER ) op = p->op2;
   79621   switch( op ){
   79622     case TK_INTEGER: {
   79623       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
   79624     }
   79625     case TK_FLOAT: {
   79626       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
   79627     }
   79628     case TK_STRING: {
   79629       return aff==SQLITE_AFF_TEXT;
   79630     }
   79631     case TK_BLOB: {
   79632       return 1;
   79633     }
   79634     case TK_COLUMN: {
   79635       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
   79636       return p->iColumn<0
   79637           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
   79638     }
   79639     default: {
   79640       return 0;
   79641     }
   79642   }
   79643 }
   79644 
   79645 /*
   79646 ** Return TRUE if the given string is a row-id column name.
   79647 */
   79648 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
   79649   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
   79650   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
   79651   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
   79652   return 0;
   79653 }
   79654 
   79655 /*
   79656 ** Return true if we are able to the IN operator optimization on a
   79657 ** query of the form
   79658 **
   79659 **       x IN (SELECT ...)
   79660 **
   79661 ** Where the SELECT... clause is as specified by the parameter to this
   79662 ** routine.
   79663 **
   79664 ** The Select object passed in has already been preprocessed and no
   79665 ** errors have been found.
   79666 */
   79667 #ifndef SQLITE_OMIT_SUBQUERY
   79668 static int isCandidateForInOpt(Select *p){
   79669   SrcList *pSrc;
   79670   ExprList *pEList;
   79671   Table *pTab;
   79672   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
   79673   if( p->pPrior ) return 0;              /* Not a compound SELECT */
   79674   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   79675     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   79676     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   79677     return 0; /* No DISTINCT keyword and no aggregate functions */
   79678   }
   79679   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
   79680   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
   79681   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
   79682   if( p->pWhere ) return 0;              /* Has no WHERE clause */
   79683   pSrc = p->pSrc;
   79684   assert( pSrc!=0 );
   79685   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
   79686   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
   79687   pTab = pSrc->a[0].pTab;
   79688   if( NEVER(pTab==0) ) return 0;
   79689   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
   79690   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
   79691   pEList = p->pEList;
   79692   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
   79693   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
   79694   return 1;
   79695 }
   79696 #endif /* SQLITE_OMIT_SUBQUERY */
   79697 
   79698 /*
   79699 ** Code an OP_Once instruction and allocate space for its flag. Return the
   79700 ** address of the new instruction.
   79701 */
   79702 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
   79703   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
   79704   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
   79705 }
   79706 
   79707 /*
   79708 ** Generate code that checks the left-most column of index table iCur to see if
   79709 ** it contains any NULL entries.  Cause the register at regHasNull to be set
   79710 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
   79711 ** to be set to NULL if iCur contains one or more NULL values.
   79712 */
   79713 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
   79714   int j1;
   79715   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
   79716   j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
   79717   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
   79718   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
   79719   VdbeComment((v, "first_entry_in(%d)", iCur));
   79720   sqlite3VdbeJumpHere(v, j1);
   79721 }
   79722 
   79723 
   79724 #ifndef SQLITE_OMIT_SUBQUERY
   79725 /*
   79726 ** The argument is an IN operator with a list (not a subquery) on the
   79727 ** right-hand side.  Return TRUE if that list is constant.
   79728 */
   79729 static int sqlite3InRhsIsConstant(Expr *pIn){
   79730   Expr *pLHS;
   79731   int res;
   79732   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
   79733   pLHS = pIn->pLeft;
   79734   pIn->pLeft = 0;
   79735   res = sqlite3ExprIsConstant(pIn);
   79736   pIn->pLeft = pLHS;
   79737   return res;
   79738 }
   79739 #endif
   79740 
   79741 /*
   79742 ** This function is used by the implementation of the IN (...) operator.
   79743 ** The pX parameter is the expression on the RHS of the IN operator, which
   79744 ** might be either a list of expressions or a subquery.
   79745 **
   79746 ** The job of this routine is to find or create a b-tree object that can
   79747 ** be used either to test for membership in the RHS set or to iterate through
   79748 ** all members of the RHS set, skipping duplicates.
   79749 **
   79750 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
   79751 ** and pX->iTable is set to the index of that cursor.
   79752 **
   79753 ** The returned value of this function indicates the b-tree type, as follows:
   79754 **
   79755 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
   79756 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
   79757 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
   79758 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
   79759 **                         populated epheremal table.
   79760 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
   79761 **                         implemented as a sequence of comparisons.
   79762 **
   79763 ** An existing b-tree might be used if the RHS expression pX is a simple
   79764 ** subquery such as:
   79765 **
   79766 **     SELECT <column> FROM <table>
   79767 **
   79768 ** If the RHS of the IN operator is a list or a more complex subquery, then
   79769 ** an ephemeral table might need to be generated from the RHS and then
   79770 ** pX->iTable made to point to the ephermeral table instead of an
   79771 ** existing table.
   79772 **
   79773 ** The inFlags parameter must contain exactly one of the bits
   79774 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
   79775 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
   79776 ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
   79777 ** IN index will be used to loop over all values of the RHS of the
   79778 ** IN operator.
   79779 **
   79780 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
   79781 ** through the set members) then the b-tree must not contain duplicates.
   79782 ** An epheremal table must be used unless the selected <column> is guaranteed
   79783 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
   79784 ** has a UNIQUE constraint or UNIQUE index.
   79785 **
   79786 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
   79787 ** for fast set membership tests) then an epheremal table must
   79788 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
   79789 ** be found with <column> as its left-most column.
   79790 **
   79791 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
   79792 ** if the RHS of the IN operator is a list (not a subquery) then this
   79793 ** routine might decide that creating an ephemeral b-tree for membership
   79794 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
   79795 ** calling routine should implement the IN operator using a sequence
   79796 ** of Eq or Ne comparison operations.
   79797 **
   79798 ** When the b-tree is being used for membership tests, the calling function
   79799 ** might need to know whether or not the RHS side of the IN operator
   79800 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
   79801 ** if there is any chance that the (...) might contain a NULL value at
   79802 ** runtime, then a register is allocated and the register number written
   79803 ** to *prRhsHasNull. If there is no chance that the (...) contains a
   79804 ** NULL value, then *prRhsHasNull is left unchanged.
   79805 **
   79806 ** If a register is allocated and its location stored in *prRhsHasNull, then
   79807 ** the value in that register will be NULL if the b-tree contains one or more
   79808 ** NULL values, and it will be some non-NULL value if the b-tree contains no
   79809 ** NULL values.
   79810 */
   79811 #ifndef SQLITE_OMIT_SUBQUERY
   79812 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
   79813   Select *p;                            /* SELECT to the right of IN operator */
   79814   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
   79815   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
   79816   int mustBeUnique;                     /* True if RHS must be unique */
   79817   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
   79818 
   79819   assert( pX->op==TK_IN );
   79820   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
   79821 
   79822   /* Check to see if an existing table or index can be used to
   79823   ** satisfy the query.  This is preferable to generating a new
   79824   ** ephemeral table.
   79825   */
   79826   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
   79827   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
   79828     sqlite3 *db = pParse->db;              /* Database connection */
   79829     Table *pTab;                           /* Table <table>. */
   79830     Expr *pExpr;                           /* Expression <column> */
   79831     i16 iCol;                              /* Index of column <column> */
   79832     i16 iDb;                               /* Database idx for pTab */
   79833 
   79834     assert( p );                        /* Because of isCandidateForInOpt(p) */
   79835     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
   79836     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
   79837     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
   79838     pTab = p->pSrc->a[0].pTab;
   79839     pExpr = p->pEList->a[0].pExpr;
   79840     iCol = (i16)pExpr->iColumn;
   79841 
   79842     /* Code an OP_Transaction and OP_TableLock for <table>. */
   79843     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   79844     sqlite3CodeVerifySchema(pParse, iDb);
   79845     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   79846 
   79847     /* This function is only called from two places. In both cases the vdbe
   79848     ** has already been allocated. So assume sqlite3GetVdbe() is always
   79849     ** successful here.
   79850     */
   79851     assert(v);
   79852     if( iCol<0 ){
   79853       int iAddr = sqlite3CodeOnce(pParse);
   79854       VdbeCoverage(v);
   79855 
   79856       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   79857       eType = IN_INDEX_ROWID;
   79858 
   79859       sqlite3VdbeJumpHere(v, iAddr);
   79860     }else{
   79861       Index *pIdx;                         /* Iterator variable */
   79862 
   79863       /* The collation sequence used by the comparison. If an index is to
   79864       ** be used in place of a temp-table, it must be ordered according
   79865       ** to this collation sequence.  */
   79866       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
   79867 
   79868       /* Check that the affinity that will be used to perform the
   79869       ** comparison is the same as the affinity of the column. If
   79870       ** it is not, it is not possible to use any index.
   79871       */
   79872       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
   79873 
   79874       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
   79875         if( (pIdx->aiColumn[0]==iCol)
   79876          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
   79877          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
   79878         ){
   79879           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   79880           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
   79881           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   79882           VdbeComment((v, "%s", pIdx->zName));
   79883           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
   79884           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
   79885 
   79886           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
   79887             *prRhsHasNull = ++pParse->nMem;
   79888             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
   79889           }
   79890           sqlite3VdbeJumpHere(v, iAddr);
   79891         }
   79892       }
   79893     }
   79894   }
   79895 
   79896   /* If no preexisting index is available for the IN clause
   79897   ** and IN_INDEX_NOOP is an allowed reply
   79898   ** and the RHS of the IN operator is a list, not a subquery
   79899   ** and the RHS is not contant or has two or fewer terms,
   79900   ** then it is not worth creating an ephermeral table to evaluate
   79901   ** the IN operator so return IN_INDEX_NOOP.
   79902   */
   79903   if( eType==0
   79904    && (inFlags & IN_INDEX_NOOP_OK)
   79905    && !ExprHasProperty(pX, EP_xIsSelect)
   79906    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
   79907   ){
   79908     eType = IN_INDEX_NOOP;
   79909   }
   79910 
   79911 
   79912   if( eType==0 ){
   79913     /* Could not find an existing table or index to use as the RHS b-tree.
   79914     ** We will have to generate an ephemeral table to do the job.
   79915     */
   79916     u32 savedNQueryLoop = pParse->nQueryLoop;
   79917     int rMayHaveNull = 0;
   79918     eType = IN_INDEX_EPH;
   79919     if( inFlags & IN_INDEX_LOOP ){
   79920       pParse->nQueryLoop = 0;
   79921       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
   79922         eType = IN_INDEX_ROWID;
   79923       }
   79924     }else if( prRhsHasNull ){
   79925       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
   79926     }
   79927     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
   79928     pParse->nQueryLoop = savedNQueryLoop;
   79929   }else{
   79930     pX->iTable = iTab;
   79931   }
   79932   return eType;
   79933 }
   79934 #endif
   79935 
   79936 /*
   79937 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
   79938 ** or IN operators.  Examples:
   79939 **
   79940 **     (SELECT a FROM b)          -- subquery
   79941 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
   79942 **     x IN (4,5,11)              -- IN operator with list on right-hand side
   79943 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
   79944 **
   79945 ** The pExpr parameter describes the expression that contains the IN
   79946 ** operator or subquery.
   79947 **
   79948 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
   79949 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
   79950 ** to some integer key column of a table B-Tree. In this case, use an
   79951 ** intkey B-Tree to store the set of IN(...) values instead of the usual
   79952 ** (slower) variable length keys B-Tree.
   79953 **
   79954 ** If rMayHaveNull is non-zero, that means that the operation is an IN
   79955 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
   79956 ** All this routine does is initialize the register given by rMayHaveNull
   79957 ** to NULL.  Calling routines will take care of changing this register
   79958 ** value to non-NULL if the RHS is NULL-free.
   79959 **
   79960 ** For a SELECT or EXISTS operator, return the register that holds the
   79961 ** result.  For IN operators or if an error occurs, the return value is 0.
   79962 */
   79963 #ifndef SQLITE_OMIT_SUBQUERY
   79964 SQLITE_PRIVATE int sqlite3CodeSubselect(
   79965   Parse *pParse,          /* Parsing context */
   79966   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
   79967   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
   79968   int isRowid             /* If true, LHS of IN operator is a rowid */
   79969 ){
   79970   int jmpIfDynamic = -1;                      /* One-time test address */
   79971   int rReg = 0;                           /* Register storing resulting */
   79972   Vdbe *v = sqlite3GetVdbe(pParse);
   79973   if( NEVER(v==0) ) return 0;
   79974   sqlite3ExprCachePush(pParse);
   79975 
   79976   /* This code must be run in its entirety every time it is encountered
   79977   ** if any of the following is true:
   79978   **
   79979   **    *  The right-hand side is a correlated subquery
   79980   **    *  The right-hand side is an expression list containing variables
   79981   **    *  We are inside a trigger
   79982   **
   79983   ** If all of the above are false, then we can run this code just once
   79984   ** save the results, and reuse the same result on subsequent invocations.
   79985   */
   79986   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
   79987     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   79988   }
   79989 
   79990 #ifndef SQLITE_OMIT_EXPLAIN
   79991   if( pParse->explain==2 ){
   79992     char *zMsg = sqlite3MPrintf(
   79993         pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
   79994         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
   79995     );
   79996     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   79997   }
   79998 #endif
   79999 
   80000   switch( pExpr->op ){
   80001     case TK_IN: {
   80002       char affinity;              /* Affinity of the LHS of the IN */
   80003       int addr;                   /* Address of OP_OpenEphemeral instruction */
   80004       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
   80005       KeyInfo *pKeyInfo = 0;      /* Key information */
   80006 
   80007       affinity = sqlite3ExprAffinity(pLeft);
   80008 
   80009       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
   80010       ** expression it is handled the same way.  An ephemeral table is
   80011       ** filled with single-field index keys representing the results
   80012       ** from the SELECT or the <exprlist>.
   80013       **
   80014       ** If the 'x' expression is a column value, or the SELECT...
   80015       ** statement returns a column value, then the affinity of that
   80016       ** column is used to build the index keys. If both 'x' and the
   80017       ** SELECT... statement are columns, then numeric affinity is used
   80018       ** if either column has NUMERIC or INTEGER affinity. If neither
   80019       ** 'x' nor the SELECT... statement are columns, then numeric affinity
   80020       ** is used.
   80021       */
   80022       pExpr->iTable = pParse->nTab++;
   80023       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
   80024       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
   80025 
   80026       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   80027         /* Case 1:     expr IN (SELECT ...)
   80028         **
   80029         ** Generate code to write the results of the select into the temporary
   80030         ** table allocated and opened above.
   80031         */
   80032         Select *pSelect = pExpr->x.pSelect;
   80033         SelectDest dest;
   80034         ExprList *pEList;
   80035 
   80036         assert( !isRowid );
   80037         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
   80038         dest.affSdst = (u8)affinity;
   80039         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
   80040         pSelect->iLimit = 0;
   80041         testcase( pSelect->selFlags & SF_Distinct );
   80042         pSelect->selFlags &= ~SF_Distinct;
   80043         testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
   80044         if( sqlite3Select(pParse, pSelect, &dest) ){
   80045           sqlite3KeyInfoUnref(pKeyInfo);
   80046           return 0;
   80047         }
   80048         pEList = pSelect->pEList;
   80049         assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
   80050         assert( pEList!=0 );
   80051         assert( pEList->nExpr>0 );
   80052         assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
   80053         pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
   80054                                                          pEList->a[0].pExpr);
   80055       }else if( ALWAYS(pExpr->x.pList!=0) ){
   80056         /* Case 2:     expr IN (exprlist)
   80057         **
   80058         ** For each expression, build an index key from the evaluation and
   80059         ** store it in the temporary table. If <expr> is a column, then use
   80060         ** that columns affinity when building index keys. If <expr> is not
   80061         ** a column, use numeric affinity.
   80062         */
   80063         int i;
   80064         ExprList *pList = pExpr->x.pList;
   80065         struct ExprList_item *pItem;
   80066         int r1, r2, r3;
   80067 
   80068         if( !affinity ){
   80069           affinity = SQLITE_AFF_NONE;
   80070         }
   80071         if( pKeyInfo ){
   80072           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
   80073           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   80074         }
   80075 
   80076         /* Loop through each expression in <exprlist>. */
   80077         r1 = sqlite3GetTempReg(pParse);
   80078         r2 = sqlite3GetTempReg(pParse);
   80079         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
   80080         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
   80081           Expr *pE2 = pItem->pExpr;
   80082           int iValToIns;
   80083 
   80084           /* If the expression is not constant then we will need to
   80085           ** disable the test that was generated above that makes sure
   80086           ** this code only executes once.  Because for a non-constant
   80087           ** expression we need to rerun this code each time.
   80088           */
   80089           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
   80090             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
   80091             jmpIfDynamic = -1;
   80092           }
   80093 
   80094           /* Evaluate the expression and insert it into the temp table */
   80095           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
   80096             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
   80097           }else{
   80098             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
   80099             if( isRowid ){
   80100               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
   80101                                 sqlite3VdbeCurrentAddr(v)+2);
   80102               VdbeCoverage(v);
   80103               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
   80104             }else{
   80105               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
   80106               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
   80107               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
   80108             }
   80109           }
   80110         }
   80111         sqlite3ReleaseTempReg(pParse, r1);
   80112         sqlite3ReleaseTempReg(pParse, r2);
   80113       }
   80114       if( pKeyInfo ){
   80115         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
   80116       }
   80117       break;
   80118     }
   80119 
   80120     case TK_EXISTS:
   80121     case TK_SELECT:
   80122     default: {
   80123       /* If this has to be a scalar SELECT.  Generate code to put the
   80124       ** value of this select in a memory cell and record the number
   80125       ** of the memory cell in iColumn.  If this is an EXISTS, write
   80126       ** an integer 0 (not exists) or 1 (exists) into a memory cell
   80127       ** and record that memory cell in iColumn.
   80128       */
   80129       Select *pSel;                         /* SELECT statement to encode */
   80130       SelectDest dest;                      /* How to deal with SELECt result */
   80131 
   80132       testcase( pExpr->op==TK_EXISTS );
   80133       testcase( pExpr->op==TK_SELECT );
   80134       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
   80135 
   80136       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   80137       pSel = pExpr->x.pSelect;
   80138       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
   80139       if( pExpr->op==TK_SELECT ){
   80140         dest.eDest = SRT_Mem;
   80141         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
   80142         VdbeComment((v, "Init subquery result"));
   80143       }else{
   80144         dest.eDest = SRT_Exists;
   80145         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
   80146         VdbeComment((v, "Init EXISTS result"));
   80147       }
   80148       sqlite3ExprDelete(pParse->db, pSel->pLimit);
   80149       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
   80150                                   &sqlite3IntTokens[1]);
   80151       pSel->iLimit = 0;
   80152       if( sqlite3Select(pParse, pSel, &dest) ){
   80153         return 0;
   80154       }
   80155       rReg = dest.iSDParm;
   80156       ExprSetVVAProperty(pExpr, EP_NoReduce);
   80157       break;
   80158     }
   80159   }
   80160 
   80161   if( rHasNullFlag ){
   80162     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
   80163   }
   80164 
   80165   if( jmpIfDynamic>=0 ){
   80166     sqlite3VdbeJumpHere(v, jmpIfDynamic);
   80167   }
   80168   sqlite3ExprCachePop(pParse);
   80169 
   80170   return rReg;
   80171 }
   80172 #endif /* SQLITE_OMIT_SUBQUERY */
   80173 
   80174 #ifndef SQLITE_OMIT_SUBQUERY
   80175 /*
   80176 ** Generate code for an IN expression.
   80177 **
   80178 **      x IN (SELECT ...)
   80179 **      x IN (value, value, ...)
   80180 **
   80181 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
   80182 ** is an array of zero or more values.  The expression is true if the LHS is
   80183 ** contained within the RHS.  The value of the expression is unknown (NULL)
   80184 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
   80185 ** RHS contains one or more NULL values.
   80186 **
   80187 ** This routine generates code that jumps to destIfFalse if the LHS is not
   80188 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
   80189 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
   80190 ** within the RHS then fall through.
   80191 */
   80192 static void sqlite3ExprCodeIN(
   80193   Parse *pParse,        /* Parsing and code generating context */
   80194   Expr *pExpr,          /* The IN expression */
   80195   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
   80196   int destIfNull        /* Jump here if the results are unknown due to NULLs */
   80197 ){
   80198   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
   80199   char affinity;        /* Comparison affinity to use */
   80200   int eType;            /* Type of the RHS */
   80201   int r1;               /* Temporary use register */
   80202   Vdbe *v;              /* Statement under construction */
   80203 
   80204   /* Compute the RHS.   After this step, the table with cursor
   80205   ** pExpr->iTable will contains the values that make up the RHS.
   80206   */
   80207   v = pParse->pVdbe;
   80208   assert( v!=0 );       /* OOM detected prior to this routine */
   80209   VdbeNoopComment((v, "begin IN expr"));
   80210   eType = sqlite3FindInIndex(pParse, pExpr,
   80211                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
   80212                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
   80213 
   80214   /* Figure out the affinity to use to create a key from the results
   80215   ** of the expression. affinityStr stores a static string suitable for
   80216   ** P4 of OP_MakeRecord.
   80217   */
   80218   affinity = comparisonAffinity(pExpr);
   80219 
   80220   /* Code the LHS, the <expr> from "<expr> IN (...)".
   80221   */
   80222   sqlite3ExprCachePush(pParse);
   80223   r1 = sqlite3GetTempReg(pParse);
   80224   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
   80225 
   80226   /* If sqlite3FindInIndex() did not find or create an index that is
   80227   ** suitable for evaluating the IN operator, then evaluate using a
   80228   ** sequence of comparisons.
   80229   */
   80230   if( eType==IN_INDEX_NOOP ){
   80231     ExprList *pList = pExpr->x.pList;
   80232     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   80233     int labelOk = sqlite3VdbeMakeLabel(v);
   80234     int r2, regToFree;
   80235     int regCkNull = 0;
   80236     int ii;
   80237     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   80238     if( destIfNull!=destIfFalse ){
   80239       regCkNull = sqlite3GetTempReg(pParse);
   80240       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
   80241     }
   80242     for(ii=0; ii<pList->nExpr; ii++){
   80243       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
   80244       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
   80245         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
   80246       }
   80247       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
   80248         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
   80249                           (void*)pColl, P4_COLLSEQ);
   80250         VdbeCoverageIf(v, ii<pList->nExpr-1);
   80251         VdbeCoverageIf(v, ii==pList->nExpr-1);
   80252         sqlite3VdbeChangeP5(v, affinity);
   80253       }else{
   80254         assert( destIfNull==destIfFalse );
   80255         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
   80256                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
   80257         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
   80258       }
   80259       sqlite3ReleaseTempReg(pParse, regToFree);
   80260     }
   80261     if( regCkNull ){
   80262       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
   80263       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   80264     }
   80265     sqlite3VdbeResolveLabel(v, labelOk);
   80266     sqlite3ReleaseTempReg(pParse, regCkNull);
   80267   }else{
   80268 
   80269     /* If the LHS is NULL, then the result is either false or NULL depending
   80270     ** on whether the RHS is empty or not, respectively.
   80271     */
   80272     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
   80273       if( destIfNull==destIfFalse ){
   80274         /* Shortcut for the common case where the false and NULL outcomes are
   80275         ** the same. */
   80276         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
   80277       }else{
   80278         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
   80279         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
   80280         VdbeCoverage(v);
   80281         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
   80282         sqlite3VdbeJumpHere(v, addr1);
   80283       }
   80284     }
   80285 
   80286     if( eType==IN_INDEX_ROWID ){
   80287       /* In this case, the RHS is the ROWID of table b-tree
   80288       */
   80289       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
   80290       sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
   80291       VdbeCoverage(v);
   80292     }else{
   80293       /* In this case, the RHS is an index b-tree.
   80294       */
   80295       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
   80296 
   80297       /* If the set membership test fails, then the result of the
   80298       ** "x IN (...)" expression must be either 0 or NULL. If the set
   80299       ** contains no NULL values, then the result is 0. If the set
   80300       ** contains one or more NULL values, then the result of the
   80301       ** expression is also NULL.
   80302       */
   80303       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
   80304       if( rRhsHasNull==0 ){
   80305         /* This branch runs if it is known at compile time that the RHS
   80306         ** cannot contain NULL values. This happens as the result
   80307         ** of a "NOT NULL" constraint in the database schema.
   80308         **
   80309         ** Also run this branch if NULL is equivalent to FALSE
   80310         ** for this particular IN operator.
   80311         */
   80312         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
   80313         VdbeCoverage(v);
   80314       }else{
   80315         /* In this branch, the RHS of the IN might contain a NULL and
   80316         ** the presence of a NULL on the RHS makes a difference in the
   80317         ** outcome.
   80318         */
   80319         int j1;
   80320 
   80321         /* First check to see if the LHS is contained in the RHS.  If so,
   80322         ** then the answer is TRUE the presence of NULLs in the RHS does
   80323         ** not matter.  If the LHS is not contained in the RHS, then the
   80324         ** answer is NULL if the RHS contains NULLs and the answer is
   80325         ** FALSE if the RHS is NULL-free.
   80326         */
   80327         j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
   80328         VdbeCoverage(v);
   80329         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
   80330         VdbeCoverage(v);
   80331         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   80332         sqlite3VdbeJumpHere(v, j1);
   80333       }
   80334     }
   80335   }
   80336   sqlite3ReleaseTempReg(pParse, r1);
   80337   sqlite3ExprCachePop(pParse);
   80338   VdbeComment((v, "end IN expr"));
   80339 }
   80340 #endif /* SQLITE_OMIT_SUBQUERY */
   80341 
   80342 /*
   80343 ** Duplicate an 8-byte value
   80344 */
   80345 static char *dup8bytes(Vdbe *v, const char *in){
   80346   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
   80347   if( out ){
   80348     memcpy(out, in, 8);
   80349   }
   80350   return out;
   80351 }
   80352 
   80353 #ifndef SQLITE_OMIT_FLOATING_POINT
   80354 /*
   80355 ** Generate an instruction that will put the floating point
   80356 ** value described by z[0..n-1] into register iMem.
   80357 **
   80358 ** The z[] string will probably not be zero-terminated.  But the
   80359 ** z[n] character is guaranteed to be something that does not look
   80360 ** like the continuation of the number.
   80361 */
   80362 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
   80363   if( ALWAYS(z!=0) ){
   80364     double value;
   80365     char *zV;
   80366     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   80367     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
   80368     if( negateFlag ) value = -value;
   80369     zV = dup8bytes(v, (char*)&value);
   80370     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
   80371   }
   80372 }
   80373 #endif
   80374 
   80375 
   80376 /*
   80377 ** Generate an instruction that will put the integer describe by
   80378 ** text z[0..n-1] into register iMem.
   80379 **
   80380 ** Expr.u.zToken is always UTF8 and zero-terminated.
   80381 */
   80382 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
   80383   Vdbe *v = pParse->pVdbe;
   80384   if( pExpr->flags & EP_IntValue ){
   80385     int i = pExpr->u.iValue;
   80386     assert( i>=0 );
   80387     if( negFlag ) i = -i;
   80388     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
   80389   }else{
   80390     int c;
   80391     i64 value;
   80392     const char *z = pExpr->u.zToken;
   80393     assert( z!=0 );
   80394     c = sqlite3DecOrHexToI64(z, &value);
   80395     if( c==0 || (c==2 && negFlag) ){
   80396       char *zV;
   80397       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
   80398       zV = dup8bytes(v, (char*)&value);
   80399       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
   80400     }else{
   80401 #ifdef SQLITE_OMIT_FLOATING_POINT
   80402       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
   80403 #else
   80404 #ifndef SQLITE_OMIT_HEX_INTEGER
   80405       if( sqlite3_strnicmp(z,"0x",2)==0 ){
   80406         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
   80407       }else
   80408 #endif
   80409       {
   80410         codeReal(v, z, negFlag, iMem);
   80411       }
   80412 #endif
   80413     }
   80414   }
   80415 }
   80416 
   80417 /*
   80418 ** Clear a cache entry.
   80419 */
   80420 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
   80421   if( p->tempReg ){
   80422     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   80423       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
   80424     }
   80425     p->tempReg = 0;
   80426   }
   80427 }
   80428 
   80429 
   80430 /*
   80431 ** Record in the column cache that a particular column from a
   80432 ** particular table is stored in a particular register.
   80433 */
   80434 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
   80435   int i;
   80436   int minLru;
   80437   int idxLru;
   80438   struct yColCache *p;
   80439 
   80440   assert( iReg>0 );  /* Register numbers are always positive */
   80441   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
   80442 
   80443   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
   80444   ** for testing only - to verify that SQLite always gets the same answer
   80445   ** with and without the column cache.
   80446   */
   80447   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
   80448 
   80449   /* First replace any existing entry.
   80450   **
   80451   ** Actually, the way the column cache is currently used, we are guaranteed
   80452   ** that the object will never already be in cache.  Verify this guarantee.
   80453   */
   80454 #ifndef NDEBUG
   80455   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80456     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
   80457   }
   80458 #endif
   80459 
   80460   /* Find an empty slot and replace it */
   80461   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80462     if( p->iReg==0 ){
   80463       p->iLevel = pParse->iCacheLevel;
   80464       p->iTable = iTab;
   80465       p->iColumn = iCol;
   80466       p->iReg = iReg;
   80467       p->tempReg = 0;
   80468       p->lru = pParse->iCacheCnt++;
   80469       return;
   80470     }
   80471   }
   80472 
   80473   /* Replace the last recently used */
   80474   minLru = 0x7fffffff;
   80475   idxLru = -1;
   80476   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80477     if( p->lru<minLru ){
   80478       idxLru = i;
   80479       minLru = p->lru;
   80480     }
   80481   }
   80482   if( ALWAYS(idxLru>=0) ){
   80483     p = &pParse->aColCache[idxLru];
   80484     p->iLevel = pParse->iCacheLevel;
   80485     p->iTable = iTab;
   80486     p->iColumn = iCol;
   80487     p->iReg = iReg;
   80488     p->tempReg = 0;
   80489     p->lru = pParse->iCacheCnt++;
   80490     return;
   80491   }
   80492 }
   80493 
   80494 /*
   80495 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
   80496 ** Purge the range of registers from the column cache.
   80497 */
   80498 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
   80499   int i;
   80500   int iLast = iReg + nReg - 1;
   80501   struct yColCache *p;
   80502   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80503     int r = p->iReg;
   80504     if( r>=iReg && r<=iLast ){
   80505       cacheEntryClear(pParse, p);
   80506       p->iReg = 0;
   80507     }
   80508   }
   80509 }
   80510 
   80511 /*
   80512 ** Remember the current column cache context.  Any new entries added
   80513 ** added to the column cache after this call are removed when the
   80514 ** corresponding pop occurs.
   80515 */
   80516 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
   80517   pParse->iCacheLevel++;
   80518 #ifdef SQLITE_DEBUG
   80519   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   80520     printf("PUSH to %d\n", pParse->iCacheLevel);
   80521   }
   80522 #endif
   80523 }
   80524 
   80525 /*
   80526 ** Remove from the column cache any entries that were added since the
   80527 ** the previous sqlite3ExprCachePush operation.  In other words, restore
   80528 ** the cache to the state it was in prior the most recent Push.
   80529 */
   80530 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
   80531   int i;
   80532   struct yColCache *p;
   80533   assert( pParse->iCacheLevel>=1 );
   80534   pParse->iCacheLevel--;
   80535 #ifdef SQLITE_DEBUG
   80536   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   80537     printf("POP  to %d\n", pParse->iCacheLevel);
   80538   }
   80539 #endif
   80540   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80541     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
   80542       cacheEntryClear(pParse, p);
   80543       p->iReg = 0;
   80544     }
   80545   }
   80546 }
   80547 
   80548 /*
   80549 ** When a cached column is reused, make sure that its register is
   80550 ** no longer available as a temp register.  ticket #3879:  that same
   80551 ** register might be in the cache in multiple places, so be sure to
   80552 ** get them all.
   80553 */
   80554 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
   80555   int i;
   80556   struct yColCache *p;
   80557   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80558     if( p->iReg==iReg ){
   80559       p->tempReg = 0;
   80560     }
   80561   }
   80562 }
   80563 
   80564 /*
   80565 ** Generate code to extract the value of the iCol-th column of a table.
   80566 */
   80567 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
   80568   Vdbe *v,        /* The VDBE under construction */
   80569   Table *pTab,    /* The table containing the value */
   80570   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
   80571   int iCol,       /* Index of the column to extract */
   80572   int regOut      /* Extract the value into this register */
   80573 ){
   80574   if( iCol<0 || iCol==pTab->iPKey ){
   80575     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
   80576   }else{
   80577     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
   80578     int x = iCol;
   80579     if( !HasRowid(pTab) ){
   80580       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
   80581     }
   80582     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
   80583   }
   80584   if( iCol>=0 ){
   80585     sqlite3ColumnDefault(v, pTab, iCol, regOut);
   80586   }
   80587 }
   80588 
   80589 /*
   80590 ** Generate code that will extract the iColumn-th column from
   80591 ** table pTab and store the column value in a register.  An effort
   80592 ** is made to store the column value in register iReg, but this is
   80593 ** not guaranteed.  The location of the column value is returned.
   80594 **
   80595 ** There must be an open cursor to pTab in iTable when this routine
   80596 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
   80597 */
   80598 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
   80599   Parse *pParse,   /* Parsing and code generating context */
   80600   Table *pTab,     /* Description of the table we are reading from */
   80601   int iColumn,     /* Index of the table column */
   80602   int iTable,      /* The cursor pointing to the table */
   80603   int iReg,        /* Store results here */
   80604   u8 p5            /* P5 value for OP_Column */
   80605 ){
   80606   Vdbe *v = pParse->pVdbe;
   80607   int i;
   80608   struct yColCache *p;
   80609 
   80610   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80611     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
   80612       p->lru = pParse->iCacheCnt++;
   80613       sqlite3ExprCachePinRegister(pParse, p->iReg);
   80614       return p->iReg;
   80615     }
   80616   }
   80617   assert( v!=0 );
   80618   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
   80619   if( p5 ){
   80620     sqlite3VdbeChangeP5(v, p5);
   80621   }else{
   80622     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
   80623   }
   80624   return iReg;
   80625 }
   80626 
   80627 /*
   80628 ** Clear all column cache entries.
   80629 */
   80630 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
   80631   int i;
   80632   struct yColCache *p;
   80633 
   80634 #if SQLITE_DEBUG
   80635   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   80636     printf("CLEAR\n");
   80637   }
   80638 #endif
   80639   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80640     if( p->iReg ){
   80641       cacheEntryClear(pParse, p);
   80642       p->iReg = 0;
   80643     }
   80644   }
   80645 }
   80646 
   80647 /*
   80648 ** Record the fact that an affinity change has occurred on iCount
   80649 ** registers starting with iStart.
   80650 */
   80651 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
   80652   sqlite3ExprCacheRemove(pParse, iStart, iCount);
   80653 }
   80654 
   80655 /*
   80656 ** Generate code to move content from registers iFrom...iFrom+nReg-1
   80657 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
   80658 */
   80659 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
   80660   int i;
   80661   struct yColCache *p;
   80662   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
   80663   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
   80664   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80665     int x = p->iReg;
   80666     if( x>=iFrom && x<iFrom+nReg ){
   80667       p->iReg += iTo-iFrom;
   80668     }
   80669   }
   80670 }
   80671 
   80672 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   80673 /*
   80674 ** Return true if any register in the range iFrom..iTo (inclusive)
   80675 ** is used as part of the column cache.
   80676 **
   80677 ** This routine is used within assert() and testcase() macros only
   80678 ** and does not appear in a normal build.
   80679 */
   80680 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
   80681   int i;
   80682   struct yColCache *p;
   80683   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   80684     int r = p->iReg;
   80685     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
   80686   }
   80687   return 0;
   80688 }
   80689 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
   80690 
   80691 /*
   80692 ** Convert an expression node to a TK_REGISTER
   80693 */
   80694 static void exprToRegister(Expr *p, int iReg){
   80695   p->op2 = p->op;
   80696   p->op = TK_REGISTER;
   80697   p->iTable = iReg;
   80698   ExprClearProperty(p, EP_Skip);
   80699 }
   80700 
   80701 /*
   80702 ** Generate code into the current Vdbe to evaluate the given
   80703 ** expression.  Attempt to store the results in register "target".
   80704 ** Return the register where results are stored.
   80705 **
   80706 ** With this routine, there is no guarantee that results will
   80707 ** be stored in target.  The result might be stored in some other
   80708 ** register if it is convenient to do so.  The calling function
   80709 ** must check the return code and move the results to the desired
   80710 ** register.
   80711 */
   80712 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
   80713   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
   80714   int op;                   /* The opcode being coded */
   80715   int inReg = target;       /* Results stored in register inReg */
   80716   int regFree1 = 0;         /* If non-zero free this temporary register */
   80717   int regFree2 = 0;         /* If non-zero free this temporary register */
   80718   int r1, r2, r3, r4;       /* Various register numbers */
   80719   sqlite3 *db = pParse->db; /* The database connection */
   80720   Expr tempX;               /* Temporary expression node */
   80721 
   80722   assert( target>0 && target<=pParse->nMem );
   80723   if( v==0 ){
   80724     assert( pParse->db->mallocFailed );
   80725     return 0;
   80726   }
   80727 
   80728   if( pExpr==0 ){
   80729     op = TK_NULL;
   80730   }else{
   80731     op = pExpr->op;
   80732   }
   80733   switch( op ){
   80734     case TK_AGG_COLUMN: {
   80735       AggInfo *pAggInfo = pExpr->pAggInfo;
   80736       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
   80737       if( !pAggInfo->directMode ){
   80738         assert( pCol->iMem>0 );
   80739         inReg = pCol->iMem;
   80740         break;
   80741       }else if( pAggInfo->useSortingIdx ){
   80742         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
   80743                               pCol->iSorterColumn, target);
   80744         break;
   80745       }
   80746       /* Otherwise, fall thru into the TK_COLUMN case */
   80747     }
   80748     case TK_COLUMN: {
   80749       int iTab = pExpr->iTable;
   80750       if( iTab<0 ){
   80751         if( pParse->ckBase>0 ){
   80752           /* Generating CHECK constraints or inserting into partial index */
   80753           inReg = pExpr->iColumn + pParse->ckBase;
   80754           break;
   80755         }else{
   80756           /* Deleting from a partial index */
   80757           iTab = pParse->iPartIdxTab;
   80758         }
   80759       }
   80760       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
   80761                                pExpr->iColumn, iTab, target,
   80762                                pExpr->op2);
   80763       break;
   80764     }
   80765     case TK_INTEGER: {
   80766       codeInteger(pParse, pExpr, 0, target);
   80767       break;
   80768     }
   80769 #ifndef SQLITE_OMIT_FLOATING_POINT
   80770     case TK_FLOAT: {
   80771       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80772       codeReal(v, pExpr->u.zToken, 0, target);
   80773       break;
   80774     }
   80775 #endif
   80776     case TK_STRING: {
   80777       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80778       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
   80779       break;
   80780     }
   80781     case TK_NULL: {
   80782       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   80783       break;
   80784     }
   80785 #ifndef SQLITE_OMIT_BLOB_LITERAL
   80786     case TK_BLOB: {
   80787       int n;
   80788       const char *z;
   80789       char *zBlob;
   80790       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80791       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   80792       assert( pExpr->u.zToken[1]=='\'' );
   80793       z = &pExpr->u.zToken[2];
   80794       n = sqlite3Strlen30(z) - 1;
   80795       assert( z[n]=='\'' );
   80796       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
   80797       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
   80798       break;
   80799     }
   80800 #endif
   80801     case TK_VARIABLE: {
   80802       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80803       assert( pExpr->u.zToken!=0 );
   80804       assert( pExpr->u.zToken[0]!=0 );
   80805       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
   80806       if( pExpr->u.zToken[1]!=0 ){
   80807         assert( pExpr->u.zToken[0]=='?'
   80808              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
   80809         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
   80810       }
   80811       break;
   80812     }
   80813     case TK_REGISTER: {
   80814       inReg = pExpr->iTable;
   80815       break;
   80816     }
   80817     case TK_AS: {
   80818       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   80819       break;
   80820     }
   80821 #ifndef SQLITE_OMIT_CAST
   80822     case TK_CAST: {
   80823       /* Expressions of the form:   CAST(pLeft AS token) */
   80824       int aff, to_op;
   80825       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   80826       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80827       aff = sqlite3AffinityType(pExpr->u.zToken, 0);
   80828       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
   80829       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
   80830       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
   80831       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
   80832       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
   80833       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
   80834       testcase( to_op==OP_ToText );
   80835       testcase( to_op==OP_ToBlob );
   80836       testcase( to_op==OP_ToNumeric );
   80837       testcase( to_op==OP_ToInt );
   80838       testcase( to_op==OP_ToReal );
   80839       if( inReg!=target ){
   80840         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
   80841         inReg = target;
   80842       }
   80843       sqlite3VdbeAddOp1(v, to_op, inReg);
   80844       testcase( usedAsColumnCache(pParse, inReg, inReg) );
   80845       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
   80846       break;
   80847     }
   80848 #endif /* SQLITE_OMIT_CAST */
   80849     case TK_LT:
   80850     case TK_LE:
   80851     case TK_GT:
   80852     case TK_GE:
   80853     case TK_NE:
   80854     case TK_EQ: {
   80855       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80856       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   80857       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   80858                   r1, r2, inReg, SQLITE_STOREP2);
   80859       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   80860       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   80861       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   80862       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   80863       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
   80864       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
   80865       testcase( regFree1==0 );
   80866       testcase( regFree2==0 );
   80867       break;
   80868     }
   80869     case TK_IS:
   80870     case TK_ISNOT: {
   80871       testcase( op==TK_IS );
   80872       testcase( op==TK_ISNOT );
   80873       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80874       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   80875       op = (op==TK_IS) ? TK_EQ : TK_NE;
   80876       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   80877                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
   80878       VdbeCoverageIf(v, op==TK_EQ);
   80879       VdbeCoverageIf(v, op==TK_NE);
   80880       testcase( regFree1==0 );
   80881       testcase( regFree2==0 );
   80882       break;
   80883     }
   80884     case TK_AND:
   80885     case TK_OR:
   80886     case TK_PLUS:
   80887     case TK_STAR:
   80888     case TK_MINUS:
   80889     case TK_REM:
   80890     case TK_BITAND:
   80891     case TK_BITOR:
   80892     case TK_SLASH:
   80893     case TK_LSHIFT:
   80894     case TK_RSHIFT:
   80895     case TK_CONCAT: {
   80896       assert( TK_AND==OP_And );            testcase( op==TK_AND );
   80897       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
   80898       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
   80899       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
   80900       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
   80901       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
   80902       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
   80903       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
   80904       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
   80905       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
   80906       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
   80907       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80908       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   80909       sqlite3VdbeAddOp3(v, op, r2, r1, target);
   80910       testcase( regFree1==0 );
   80911       testcase( regFree2==0 );
   80912       break;
   80913     }
   80914     case TK_UMINUS: {
   80915       Expr *pLeft = pExpr->pLeft;
   80916       assert( pLeft );
   80917       if( pLeft->op==TK_INTEGER ){
   80918         codeInteger(pParse, pLeft, 1, target);
   80919 #ifndef SQLITE_OMIT_FLOATING_POINT
   80920       }else if( pLeft->op==TK_FLOAT ){
   80921         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80922         codeReal(v, pLeft->u.zToken, 1, target);
   80923 #endif
   80924       }else{
   80925         tempX.op = TK_INTEGER;
   80926         tempX.flags = EP_IntValue|EP_TokenOnly;
   80927         tempX.u.iValue = 0;
   80928         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
   80929         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
   80930         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
   80931         testcase( regFree2==0 );
   80932       }
   80933       inReg = target;
   80934       break;
   80935     }
   80936     case TK_BITNOT:
   80937     case TK_NOT: {
   80938       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
   80939       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
   80940       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80941       testcase( regFree1==0 );
   80942       inReg = target;
   80943       sqlite3VdbeAddOp2(v, op, r1, inReg);
   80944       break;
   80945     }
   80946     case TK_ISNULL:
   80947     case TK_NOTNULL: {
   80948       int addr;
   80949       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
   80950       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
   80951       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   80952       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   80953       testcase( regFree1==0 );
   80954       addr = sqlite3VdbeAddOp1(v, op, r1);
   80955       VdbeCoverageIf(v, op==TK_ISNULL);
   80956       VdbeCoverageIf(v, op==TK_NOTNULL);
   80957       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
   80958       sqlite3VdbeJumpHere(v, addr);
   80959       break;
   80960     }
   80961     case TK_AGG_FUNCTION: {
   80962       AggInfo *pInfo = pExpr->pAggInfo;
   80963       if( pInfo==0 ){
   80964         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80965         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
   80966       }else{
   80967         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
   80968       }
   80969       break;
   80970     }
   80971     case TK_FUNCTION: {
   80972       ExprList *pFarg;       /* List of function arguments */
   80973       int nFarg;             /* Number of function arguments */
   80974       FuncDef *pDef;         /* The function definition object */
   80975       int nId;               /* Length of the function name in bytes */
   80976       const char *zId;       /* The function name */
   80977       u32 constMask = 0;     /* Mask of function arguments that are constant */
   80978       int i;                 /* Loop counter */
   80979       u8 enc = ENC(db);      /* The text encoding used by this database */
   80980       CollSeq *pColl = 0;    /* A collating sequence */
   80981 
   80982       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   80983       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
   80984         pFarg = 0;
   80985       }else{
   80986         pFarg = pExpr->x.pList;
   80987       }
   80988       nFarg = pFarg ? pFarg->nExpr : 0;
   80989       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   80990       zId = pExpr->u.zToken;
   80991       nId = sqlite3Strlen30(zId);
   80992       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
   80993       if( pDef==0 || pDef->xFunc==0 ){
   80994         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
   80995         break;
   80996       }
   80997 
   80998       /* Attempt a direct implementation of the built-in COALESCE() and
   80999       ** IFNULL() functions.  This avoids unnecessary evalation of
   81000       ** arguments past the first non-NULL argument.
   81001       */
   81002       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
   81003         int endCoalesce = sqlite3VdbeMakeLabel(v);
   81004         assert( nFarg>=2 );
   81005         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   81006         for(i=1; i<nFarg; i++){
   81007           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
   81008           VdbeCoverage(v);
   81009           sqlite3ExprCacheRemove(pParse, target, 1);
   81010           sqlite3ExprCachePush(pParse);
   81011           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
   81012           sqlite3ExprCachePop(pParse);
   81013         }
   81014         sqlite3VdbeResolveLabel(v, endCoalesce);
   81015         break;
   81016       }
   81017 
   81018       /* The UNLIKELY() function is a no-op.  The result is the value
   81019       ** of the first argument.
   81020       */
   81021       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
   81022         assert( nFarg>=1 );
   81023         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   81024         break;
   81025       }
   81026 
   81027       for(i=0; i<nFarg; i++){
   81028         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
   81029           testcase( i==31 );
   81030           constMask |= MASKBIT32(i);
   81031         }
   81032         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
   81033           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
   81034         }
   81035       }
   81036       if( pFarg ){
   81037         if( constMask ){
   81038           r1 = pParse->nMem+1;
   81039           pParse->nMem += nFarg;
   81040         }else{
   81041           r1 = sqlite3GetTempRange(pParse, nFarg);
   81042         }
   81043 
   81044         /* For length() and typeof() functions with a column argument,
   81045         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
   81046         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
   81047         ** loading.
   81048         */
   81049         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
   81050           u8 exprOp;
   81051           assert( nFarg==1 );
   81052           assert( pFarg->a[0].pExpr!=0 );
   81053           exprOp = pFarg->a[0].pExpr->op;
   81054           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
   81055             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
   81056             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
   81057             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
   81058             pFarg->a[0].pExpr->op2 =
   81059                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
   81060           }
   81061         }
   81062 
   81063         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
   81064         sqlite3ExprCodeExprList(pParse, pFarg, r1,
   81065                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
   81066         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
   81067       }else{
   81068         r1 = 0;
   81069       }
   81070 #ifndef SQLITE_OMIT_VIRTUALTABLE
   81071       /* Possibly overload the function if the first argument is
   81072       ** a virtual table column.
   81073       **
   81074       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
   81075       ** second argument, not the first, as the argument to test to
   81076       ** see if it is a column in a virtual table.  This is done because
   81077       ** the left operand of infix functions (the operand we want to
   81078       ** control overloading) ends up as the second argument to the
   81079       ** function.  The expression "A glob B" is equivalent to
   81080       ** "glob(B,A).  We want to use the A in "A glob B" to test
   81081       ** for function overloading.  But we use the B term in "glob(B,A)".
   81082       */
   81083       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
   81084         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
   81085       }else if( nFarg>0 ){
   81086         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
   81087       }
   81088 #endif
   81089       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   81090         if( !pColl ) pColl = db->pDfltColl;
   81091         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   81092       }
   81093       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
   81094                         (char*)pDef, P4_FUNCDEF);
   81095       sqlite3VdbeChangeP5(v, (u8)nFarg);
   81096       if( nFarg && constMask==0 ){
   81097         sqlite3ReleaseTempRange(pParse, r1, nFarg);
   81098       }
   81099       break;
   81100     }
   81101 #ifndef SQLITE_OMIT_SUBQUERY
   81102     case TK_EXISTS:
   81103     case TK_SELECT: {
   81104       testcase( op==TK_EXISTS );
   81105       testcase( op==TK_SELECT );
   81106       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
   81107       break;
   81108     }
   81109     case TK_IN: {
   81110       int destIfFalse = sqlite3VdbeMakeLabel(v);
   81111       int destIfNull = sqlite3VdbeMakeLabel(v);
   81112       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   81113       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   81114       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   81115       sqlite3VdbeResolveLabel(v, destIfFalse);
   81116       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
   81117       sqlite3VdbeResolveLabel(v, destIfNull);
   81118       break;
   81119     }
   81120 #endif /* SQLITE_OMIT_SUBQUERY */
   81121 
   81122 
   81123     /*
   81124     **    x BETWEEN y AND z
   81125     **
   81126     ** This is equivalent to
   81127     **
   81128     **    x>=y AND x<=z
   81129     **
   81130     ** X is stored in pExpr->pLeft.
   81131     ** Y is stored in pExpr->pList->a[0].pExpr.
   81132     ** Z is stored in pExpr->pList->a[1].pExpr.
   81133     */
   81134     case TK_BETWEEN: {
   81135       Expr *pLeft = pExpr->pLeft;
   81136       struct ExprList_item *pLItem = pExpr->x.pList->a;
   81137       Expr *pRight = pLItem->pExpr;
   81138 
   81139       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
   81140       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   81141       testcase( regFree1==0 );
   81142       testcase( regFree2==0 );
   81143       r3 = sqlite3GetTempReg(pParse);
   81144       r4 = sqlite3GetTempReg(pParse);
   81145       codeCompare(pParse, pLeft, pRight, OP_Ge,
   81146                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
   81147       pLItem++;
   81148       pRight = pLItem->pExpr;
   81149       sqlite3ReleaseTempReg(pParse, regFree2);
   81150       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   81151       testcase( regFree2==0 );
   81152       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
   81153       VdbeCoverage(v);
   81154       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
   81155       sqlite3ReleaseTempReg(pParse, r3);
   81156       sqlite3ReleaseTempReg(pParse, r4);
   81157       break;
   81158     }
   81159     case TK_COLLATE:
   81160     case TK_UPLUS: {
   81161       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   81162       break;
   81163     }
   81164 
   81165     case TK_TRIGGER: {
   81166       /* If the opcode is TK_TRIGGER, then the expression is a reference
   81167       ** to a column in the new.* or old.* pseudo-tables available to
   81168       ** trigger programs. In this case Expr.iTable is set to 1 for the
   81169       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   81170       ** is set to the column of the pseudo-table to read, or to -1 to
   81171       ** read the rowid field.
   81172       **
   81173       ** The expression is implemented using an OP_Param opcode. The p1
   81174       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
   81175       ** to reference another column of the old.* pseudo-table, where
   81176       ** i is the index of the column. For a new.rowid reference, p1 is
   81177       ** set to (n+1), where n is the number of columns in each pseudo-table.
   81178       ** For a reference to any other column in the new.* pseudo-table, p1
   81179       ** is set to (n+2+i), where n and i are as defined previously. For
   81180       ** example, if the table on which triggers are being fired is
   81181       ** declared as:
   81182       **
   81183       **   CREATE TABLE t1(a, b);
   81184       **
   81185       ** Then p1 is interpreted as follows:
   81186       **
   81187       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
   81188       **   p1==1   ->    old.a         p1==4   ->    new.a
   81189       **   p1==2   ->    old.b         p1==5   ->    new.b
   81190       */
   81191       Table *pTab = pExpr->pTab;
   81192       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
   81193 
   81194       assert( pExpr->iTable==0 || pExpr->iTable==1 );
   81195       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
   81196       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
   81197       assert( p1>=0 && p1<(pTab->nCol*2+2) );
   81198 
   81199       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
   81200       VdbeComment((v, "%s.%s -> $%d",
   81201         (pExpr->iTable ? "new" : "old"),
   81202         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
   81203         target
   81204       ));
   81205 
   81206 #ifndef SQLITE_OMIT_FLOATING_POINT
   81207       /* If the column has REAL affinity, it may currently be stored as an
   81208       ** integer. Use OP_RealAffinity to make sure it is really real.  */
   81209       if( pExpr->iColumn>=0
   81210        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
   81211       ){
   81212         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
   81213       }
   81214 #endif
   81215       break;
   81216     }
   81217 
   81218 
   81219     /*
   81220     ** Form A:
   81221     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   81222     **
   81223     ** Form B:
   81224     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   81225     **
   81226     ** Form A is can be transformed into the equivalent form B as follows:
   81227     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
   81228     **        WHEN x=eN THEN rN ELSE y END
   81229     **
   81230     ** X (if it exists) is in pExpr->pLeft.
   81231     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
   81232     ** odd.  The Y is also optional.  If the number of elements in x.pList
   81233     ** is even, then Y is omitted and the "otherwise" result is NULL.
   81234     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
   81235     **
   81236     ** The result of the expression is the Ri for the first matching Ei,
   81237     ** or if there is no matching Ei, the ELSE term Y, or if there is
   81238     ** no ELSE term, NULL.
   81239     */
   81240     default: assert( op==TK_CASE ); {
   81241       int endLabel;                     /* GOTO label for end of CASE stmt */
   81242       int nextCase;                     /* GOTO label for next WHEN clause */
   81243       int nExpr;                        /* 2x number of WHEN terms */
   81244       int i;                            /* Loop counter */
   81245       ExprList *pEList;                 /* List of WHEN terms */
   81246       struct ExprList_item *aListelem;  /* Array of WHEN terms */
   81247       Expr opCompare;                   /* The X==Ei expression */
   81248       Expr *pX;                         /* The X expression */
   81249       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
   81250       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
   81251 
   81252       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
   81253       assert(pExpr->x.pList->nExpr > 0);
   81254       pEList = pExpr->x.pList;
   81255       aListelem = pEList->a;
   81256       nExpr = pEList->nExpr;
   81257       endLabel = sqlite3VdbeMakeLabel(v);
   81258       if( (pX = pExpr->pLeft)!=0 ){
   81259         tempX = *pX;
   81260         testcase( pX->op==TK_COLUMN );
   81261         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
   81262         testcase( regFree1==0 );
   81263         opCompare.op = TK_EQ;
   81264         opCompare.pLeft = &tempX;
   81265         pTest = &opCompare;
   81266         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
   81267         ** The value in regFree1 might get SCopy-ed into the file result.
   81268         ** So make sure that the regFree1 register is not reused for other
   81269         ** purposes and possibly overwritten.  */
   81270         regFree1 = 0;
   81271       }
   81272       for(i=0; i<nExpr-1; i=i+2){
   81273         sqlite3ExprCachePush(pParse);
   81274         if( pX ){
   81275           assert( pTest!=0 );
   81276           opCompare.pRight = aListelem[i].pExpr;
   81277         }else{
   81278           pTest = aListelem[i].pExpr;
   81279         }
   81280         nextCase = sqlite3VdbeMakeLabel(v);
   81281         testcase( pTest->op==TK_COLUMN );
   81282         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
   81283         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
   81284         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
   81285         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
   81286         sqlite3ExprCachePop(pParse);
   81287         sqlite3VdbeResolveLabel(v, nextCase);
   81288       }
   81289       if( (nExpr&1)!=0 ){
   81290         sqlite3ExprCachePush(pParse);
   81291         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
   81292         sqlite3ExprCachePop(pParse);
   81293       }else{
   81294         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   81295       }
   81296       assert( db->mallocFailed || pParse->nErr>0
   81297            || pParse->iCacheLevel==iCacheLevel );
   81298       sqlite3VdbeResolveLabel(v, endLabel);
   81299       break;
   81300     }
   81301 #ifndef SQLITE_OMIT_TRIGGER
   81302     case TK_RAISE: {
   81303       assert( pExpr->affinity==OE_Rollback
   81304            || pExpr->affinity==OE_Abort
   81305            || pExpr->affinity==OE_Fail
   81306            || pExpr->affinity==OE_Ignore
   81307       );
   81308       if( !pParse->pTriggerTab ){
   81309         sqlite3ErrorMsg(pParse,
   81310                        "RAISE() may only be used within a trigger-program");
   81311         return 0;
   81312       }
   81313       if( pExpr->affinity==OE_Abort ){
   81314         sqlite3MayAbort(pParse);
   81315       }
   81316       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   81317       if( pExpr->affinity==OE_Ignore ){
   81318         sqlite3VdbeAddOp4(
   81319             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
   81320         VdbeCoverage(v);
   81321       }else{
   81322         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
   81323                               pExpr->affinity, pExpr->u.zToken, 0, 0);
   81324       }
   81325 
   81326       break;
   81327     }
   81328 #endif
   81329   }
   81330   sqlite3ReleaseTempReg(pParse, regFree1);
   81331   sqlite3ReleaseTempReg(pParse, regFree2);
   81332   return inReg;
   81333 }
   81334 
   81335 /*
   81336 ** Factor out the code of the given expression to initialization time.
   81337 */
   81338 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
   81339   Parse *pParse,    /* Parsing context */
   81340   Expr *pExpr,      /* The expression to code when the VDBE initializes */
   81341   int regDest,      /* Store the value in this register */
   81342   u8 reusable       /* True if this expression is reusable */
   81343 ){
   81344   ExprList *p;
   81345   assert( ConstFactorOk(pParse) );
   81346   p = pParse->pConstExpr;
   81347   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
   81348   p = sqlite3ExprListAppend(pParse, p, pExpr);
   81349   if( p ){
   81350      struct ExprList_item *pItem = &p->a[p->nExpr-1];
   81351      pItem->u.iConstExprReg = regDest;
   81352      pItem->reusable = reusable;
   81353   }
   81354   pParse->pConstExpr = p;
   81355 }
   81356 
   81357 /*
   81358 ** Generate code to evaluate an expression and store the results
   81359 ** into a register.  Return the register number where the results
   81360 ** are stored.
   81361 **
   81362 ** If the register is a temporary register that can be deallocated,
   81363 ** then write its number into *pReg.  If the result register is not
   81364 ** a temporary, then set *pReg to zero.
   81365 **
   81366 ** If pExpr is a constant, then this routine might generate this
   81367 ** code to fill the register in the initialization section of the
   81368 ** VDBE program, in order to factor it out of the evaluation loop.
   81369 */
   81370 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
   81371   int r2;
   81372   pExpr = sqlite3ExprSkipCollate(pExpr);
   81373   if( ConstFactorOk(pParse)
   81374    && pExpr->op!=TK_REGISTER
   81375    && sqlite3ExprIsConstantNotJoin(pExpr)
   81376   ){
   81377     ExprList *p = pParse->pConstExpr;
   81378     int i;
   81379     *pReg  = 0;
   81380     if( p ){
   81381       struct ExprList_item *pItem;
   81382       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
   81383         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
   81384           return pItem->u.iConstExprReg;
   81385         }
   81386       }
   81387     }
   81388     r2 = ++pParse->nMem;
   81389     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
   81390   }else{
   81391     int r1 = sqlite3GetTempReg(pParse);
   81392     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   81393     if( r2==r1 ){
   81394       *pReg = r1;
   81395     }else{
   81396       sqlite3ReleaseTempReg(pParse, r1);
   81397       *pReg = 0;
   81398     }
   81399   }
   81400   return r2;
   81401 }
   81402 
   81403 /*
   81404 ** Generate code that will evaluate expression pExpr and store the
   81405 ** results in register target.  The results are guaranteed to appear
   81406 ** in register target.
   81407 */
   81408 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   81409   int inReg;
   81410 
   81411   assert( target>0 && target<=pParse->nMem );
   81412   if( pExpr && pExpr->op==TK_REGISTER ){
   81413     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
   81414   }else{
   81415     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   81416     assert( pParse->pVdbe || pParse->db->mallocFailed );
   81417     if( inReg!=target && pParse->pVdbe ){
   81418       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
   81419     }
   81420   }
   81421 }
   81422 
   81423 /*
   81424 ** Generate code that will evaluate expression pExpr and store the
   81425 ** results in register target.  The results are guaranteed to appear
   81426 ** in register target.  If the expression is constant, then this routine
   81427 ** might choose to code the expression at initialization time.
   81428 */
   81429 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
   81430   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
   81431     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
   81432   }else{
   81433     sqlite3ExprCode(pParse, pExpr, target);
   81434   }
   81435 }
   81436 
   81437 /*
   81438 ** Generate code that evalutes the given expression and puts the result
   81439 ** in register target.
   81440 **
   81441 ** Also make a copy of the expression results into another "cache" register
   81442 ** and modify the expression so that the next time it is evaluated,
   81443 ** the result is a copy of the cache register.
   81444 **
   81445 ** This routine is used for expressions that are used multiple
   81446 ** times.  They are evaluated once and the results of the expression
   81447 ** are reused.
   81448 */
   81449 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
   81450   Vdbe *v = pParse->pVdbe;
   81451   int iMem;
   81452 
   81453   assert( target>0 );
   81454   assert( pExpr->op!=TK_REGISTER );
   81455   sqlite3ExprCode(pParse, pExpr, target);
   81456   iMem = ++pParse->nMem;
   81457   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
   81458   exprToRegister(pExpr, iMem);
   81459 }
   81460 
   81461 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   81462 /*
   81463 ** Generate a human-readable explanation of an expression tree.
   81464 */
   81465 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
   81466   int op;                   /* The opcode being coded */
   81467   const char *zBinOp = 0;   /* Binary operator */
   81468   const char *zUniOp = 0;   /* Unary operator */
   81469   if( pExpr==0 ){
   81470     op = TK_NULL;
   81471   }else{
   81472     op = pExpr->op;
   81473   }
   81474   switch( op ){
   81475     case TK_AGG_COLUMN: {
   81476       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
   81477             pExpr->iTable, pExpr->iColumn);
   81478       break;
   81479     }
   81480     case TK_COLUMN: {
   81481       if( pExpr->iTable<0 ){
   81482         /* This only happens when coding check constraints */
   81483         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
   81484       }else{
   81485         sqlite3ExplainPrintf(pOut, "{%d:%d}",
   81486                              pExpr->iTable, pExpr->iColumn);
   81487       }
   81488       break;
   81489     }
   81490     case TK_INTEGER: {
   81491       if( pExpr->flags & EP_IntValue ){
   81492         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
   81493       }else{
   81494         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
   81495       }
   81496       break;
   81497     }
   81498 #ifndef SQLITE_OMIT_FLOATING_POINT
   81499     case TK_FLOAT: {
   81500       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
   81501       break;
   81502     }
   81503 #endif
   81504     case TK_STRING: {
   81505       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
   81506       break;
   81507     }
   81508     case TK_NULL: {
   81509       sqlite3ExplainPrintf(pOut,"NULL");
   81510       break;
   81511     }
   81512 #ifndef SQLITE_OMIT_BLOB_LITERAL
   81513     case TK_BLOB: {
   81514       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
   81515       break;
   81516     }
   81517 #endif
   81518     case TK_VARIABLE: {
   81519       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
   81520                            pExpr->u.zToken, pExpr->iColumn);
   81521       break;
   81522     }
   81523     case TK_REGISTER: {
   81524       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
   81525       break;
   81526     }
   81527     case TK_AS: {
   81528       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81529       break;
   81530     }
   81531 #ifndef SQLITE_OMIT_CAST
   81532     case TK_CAST: {
   81533       /* Expressions of the form:   CAST(pLeft AS token) */
   81534       const char *zAff = "unk";
   81535       switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
   81536         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
   81537         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
   81538         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
   81539         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
   81540         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
   81541       }
   81542       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
   81543       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81544       sqlite3ExplainPrintf(pOut, ")");
   81545       break;
   81546     }
   81547 #endif /* SQLITE_OMIT_CAST */
   81548     case TK_LT:      zBinOp = "LT";     break;
   81549     case TK_LE:      zBinOp = "LE";     break;
   81550     case TK_GT:      zBinOp = "GT";     break;
   81551     case TK_GE:      zBinOp = "GE";     break;
   81552     case TK_NE:      zBinOp = "NE";     break;
   81553     case TK_EQ:      zBinOp = "EQ";     break;
   81554     case TK_IS:      zBinOp = "IS";     break;
   81555     case TK_ISNOT:   zBinOp = "ISNOT";  break;
   81556     case TK_AND:     zBinOp = "AND";    break;
   81557     case TK_OR:      zBinOp = "OR";     break;
   81558     case TK_PLUS:    zBinOp = "ADD";    break;
   81559     case TK_STAR:    zBinOp = "MUL";    break;
   81560     case TK_MINUS:   zBinOp = "SUB";    break;
   81561     case TK_REM:     zBinOp = "REM";    break;
   81562     case TK_BITAND:  zBinOp = "BITAND"; break;
   81563     case TK_BITOR:   zBinOp = "BITOR";  break;
   81564     case TK_SLASH:   zBinOp = "DIV";    break;
   81565     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
   81566     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
   81567     case TK_CONCAT:  zBinOp = "CONCAT"; break;
   81568 
   81569     case TK_UMINUS:  zUniOp = "UMINUS"; break;
   81570     case TK_UPLUS:   zUniOp = "UPLUS";  break;
   81571     case TK_BITNOT:  zUniOp = "BITNOT"; break;
   81572     case TK_NOT:     zUniOp = "NOT";    break;
   81573     case TK_ISNULL:  zUniOp = "ISNULL"; break;
   81574     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
   81575 
   81576     case TK_COLLATE: {
   81577       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81578       sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
   81579       break;
   81580     }
   81581 
   81582     case TK_AGG_FUNCTION:
   81583     case TK_FUNCTION: {
   81584       ExprList *pFarg;       /* List of function arguments */
   81585       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
   81586         pFarg = 0;
   81587       }else{
   81588         pFarg = pExpr->x.pList;
   81589       }
   81590       if( op==TK_AGG_FUNCTION ){
   81591         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
   81592                              pExpr->op2, pExpr->u.zToken);
   81593       }else{
   81594         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
   81595       }
   81596       if( pFarg ){
   81597         sqlite3ExplainExprList(pOut, pFarg);
   81598       }
   81599       sqlite3ExplainPrintf(pOut, ")");
   81600       break;
   81601     }
   81602 #ifndef SQLITE_OMIT_SUBQUERY
   81603     case TK_EXISTS: {
   81604       sqlite3ExplainPrintf(pOut, "EXISTS(");
   81605       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   81606       sqlite3ExplainPrintf(pOut,")");
   81607       break;
   81608     }
   81609     case TK_SELECT: {
   81610       sqlite3ExplainPrintf(pOut, "(");
   81611       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   81612       sqlite3ExplainPrintf(pOut, ")");
   81613       break;
   81614     }
   81615     case TK_IN: {
   81616       sqlite3ExplainPrintf(pOut, "IN(");
   81617       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81618       sqlite3ExplainPrintf(pOut, ",");
   81619       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   81620         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   81621       }else{
   81622         sqlite3ExplainExprList(pOut, pExpr->x.pList);
   81623       }
   81624       sqlite3ExplainPrintf(pOut, ")");
   81625       break;
   81626     }
   81627 #endif /* SQLITE_OMIT_SUBQUERY */
   81628 
   81629     /*
   81630     **    x BETWEEN y AND z
   81631     **
   81632     ** This is equivalent to
   81633     **
   81634     **    x>=y AND x<=z
   81635     **
   81636     ** X is stored in pExpr->pLeft.
   81637     ** Y is stored in pExpr->pList->a[0].pExpr.
   81638     ** Z is stored in pExpr->pList->a[1].pExpr.
   81639     */
   81640     case TK_BETWEEN: {
   81641       Expr *pX = pExpr->pLeft;
   81642       Expr *pY = pExpr->x.pList->a[0].pExpr;
   81643       Expr *pZ = pExpr->x.pList->a[1].pExpr;
   81644       sqlite3ExplainPrintf(pOut, "BETWEEN(");
   81645       sqlite3ExplainExpr(pOut, pX);
   81646       sqlite3ExplainPrintf(pOut, ",");
   81647       sqlite3ExplainExpr(pOut, pY);
   81648       sqlite3ExplainPrintf(pOut, ",");
   81649       sqlite3ExplainExpr(pOut, pZ);
   81650       sqlite3ExplainPrintf(pOut, ")");
   81651       break;
   81652     }
   81653     case TK_TRIGGER: {
   81654       /* If the opcode is TK_TRIGGER, then the expression is a reference
   81655       ** to a column in the new.* or old.* pseudo-tables available to
   81656       ** trigger programs. In this case Expr.iTable is set to 1 for the
   81657       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   81658       ** is set to the column of the pseudo-table to read, or to -1 to
   81659       ** read the rowid field.
   81660       */
   81661       sqlite3ExplainPrintf(pOut, "%s(%d)",
   81662           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
   81663       break;
   81664     }
   81665     case TK_CASE: {
   81666       sqlite3ExplainPrintf(pOut, "CASE(");
   81667       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81668       sqlite3ExplainPrintf(pOut, ",");
   81669       sqlite3ExplainExprList(pOut, pExpr->x.pList);
   81670       break;
   81671     }
   81672 #ifndef SQLITE_OMIT_TRIGGER
   81673     case TK_RAISE: {
   81674       const char *zType = "unk";
   81675       switch( pExpr->affinity ){
   81676         case OE_Rollback:   zType = "rollback";  break;
   81677         case OE_Abort:      zType = "abort";     break;
   81678         case OE_Fail:       zType = "fail";      break;
   81679         case OE_Ignore:     zType = "ignore";    break;
   81680       }
   81681       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
   81682       break;
   81683     }
   81684 #endif
   81685   }
   81686   if( zBinOp ){
   81687     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
   81688     sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81689     sqlite3ExplainPrintf(pOut,",");
   81690     sqlite3ExplainExpr(pOut, pExpr->pRight);
   81691     sqlite3ExplainPrintf(pOut,")");
   81692   }else if( zUniOp ){
   81693     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
   81694     sqlite3ExplainExpr(pOut, pExpr->pLeft);
   81695     sqlite3ExplainPrintf(pOut,")");
   81696   }
   81697 }
   81698 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
   81699 
   81700 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   81701 /*
   81702 ** Generate a human-readable explanation of an expression list.
   81703 */
   81704 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
   81705   int i;
   81706   if( pList==0 || pList->nExpr==0 ){
   81707     sqlite3ExplainPrintf(pOut, "(empty-list)");
   81708     return;
   81709   }else if( pList->nExpr==1 ){
   81710     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
   81711   }else{
   81712     sqlite3ExplainPush(pOut);
   81713     for(i=0; i<pList->nExpr; i++){
   81714       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
   81715       sqlite3ExplainPush(pOut);
   81716       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
   81717       sqlite3ExplainPop(pOut);
   81718       if( pList->a[i].zName ){
   81719         sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
   81720       }
   81721       if( pList->a[i].bSpanIsTab ){
   81722         sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
   81723       }
   81724       if( i<pList->nExpr-1 ){
   81725         sqlite3ExplainNL(pOut);
   81726       }
   81727     }
   81728     sqlite3ExplainPop(pOut);
   81729   }
   81730 }
   81731 #endif /* SQLITE_DEBUG */
   81732 
   81733 /*
   81734 ** Generate code that pushes the value of every element of the given
   81735 ** expression list into a sequence of registers beginning at target.
   81736 **
   81737 ** Return the number of elements evaluated.
   81738 **
   81739 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
   81740 ** filled using OP_SCopy.  OP_Copy must be used instead.
   81741 **
   81742 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
   81743 ** factored out into initialization code.
   81744 */
   81745 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
   81746   Parse *pParse,     /* Parsing context */
   81747   ExprList *pList,   /* The expression list to be coded */
   81748   int target,        /* Where to write results */
   81749   u8 flags           /* SQLITE_ECEL_* flags */
   81750 ){
   81751   struct ExprList_item *pItem;
   81752   int i, n;
   81753   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
   81754   assert( pList!=0 );
   81755   assert( target>0 );
   81756   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
   81757   n = pList->nExpr;
   81758   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
   81759   for(pItem=pList->a, i=0; i<n; i++, pItem++){
   81760     Expr *pExpr = pItem->pExpr;
   81761     if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
   81762       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
   81763     }else{
   81764       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
   81765       if( inReg!=target+i ){
   81766         VdbeOp *pOp;
   81767         Vdbe *v = pParse->pVdbe;
   81768         if( copyOp==OP_Copy
   81769          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
   81770          && pOp->p1+pOp->p3+1==inReg
   81771          && pOp->p2+pOp->p3+1==target+i
   81772         ){
   81773           pOp->p3++;
   81774         }else{
   81775           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
   81776         }
   81777       }
   81778     }
   81779   }
   81780   return n;
   81781 }
   81782 
   81783 /*
   81784 ** Generate code for a BETWEEN operator.
   81785 **
   81786 **    x BETWEEN y AND z
   81787 **
   81788 ** The above is equivalent to
   81789 **
   81790 **    x>=y AND x<=z
   81791 **
   81792 ** Code it as such, taking care to do the common subexpression
   81793 ** elementation of x.
   81794 */
   81795 static void exprCodeBetween(
   81796   Parse *pParse,    /* Parsing and code generating context */
   81797   Expr *pExpr,      /* The BETWEEN expression */
   81798   int dest,         /* Jump here if the jump is taken */
   81799   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
   81800   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
   81801 ){
   81802   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
   81803   Expr compLeft;    /* The  x>=y  term */
   81804   Expr compRight;   /* The  x<=z  term */
   81805   Expr exprX;       /* The  x  subexpression */
   81806   int regFree1 = 0; /* Temporary use register */
   81807 
   81808   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   81809   exprX = *pExpr->pLeft;
   81810   exprAnd.op = TK_AND;
   81811   exprAnd.pLeft = &compLeft;
   81812   exprAnd.pRight = &compRight;
   81813   compLeft.op = TK_GE;
   81814   compLeft.pLeft = &exprX;
   81815   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
   81816   compRight.op = TK_LE;
   81817   compRight.pLeft = &exprX;
   81818   compRight.pRight = pExpr->x.pList->a[1].pExpr;
   81819   exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
   81820   if( jumpIfTrue ){
   81821     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
   81822   }else{
   81823     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
   81824   }
   81825   sqlite3ReleaseTempReg(pParse, regFree1);
   81826 
   81827   /* Ensure adequate test coverage */
   81828   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
   81829   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
   81830   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
   81831   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
   81832   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
   81833   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
   81834   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
   81835   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
   81836 }
   81837 
   81838 /*
   81839 ** Generate code for a boolean expression such that a jump is made
   81840 ** to the label "dest" if the expression is true but execution
   81841 ** continues straight thru if the expression is false.
   81842 **
   81843 ** If the expression evaluates to NULL (neither true nor false), then
   81844 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
   81845 **
   81846 ** This code depends on the fact that certain token values (ex: TK_EQ)
   81847 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
   81848 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
   81849 ** the make process cause these values to align.  Assert()s in the code
   81850 ** below verify that the numbers are aligned correctly.
   81851 */
   81852 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   81853   Vdbe *v = pParse->pVdbe;
   81854   int op = 0;
   81855   int regFree1 = 0;
   81856   int regFree2 = 0;
   81857   int r1, r2;
   81858 
   81859   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   81860   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
   81861   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
   81862   op = pExpr->op;
   81863   switch( op ){
   81864     case TK_AND: {
   81865       int d2 = sqlite3VdbeMakeLabel(v);
   81866       testcase( jumpIfNull==0 );
   81867       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
   81868       sqlite3ExprCachePush(pParse);
   81869       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   81870       sqlite3VdbeResolveLabel(v, d2);
   81871       sqlite3ExprCachePop(pParse);
   81872       break;
   81873     }
   81874     case TK_OR: {
   81875       testcase( jumpIfNull==0 );
   81876       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   81877       sqlite3ExprCachePush(pParse);
   81878       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   81879       sqlite3ExprCachePop(pParse);
   81880       break;
   81881     }
   81882     case TK_NOT: {
   81883       testcase( jumpIfNull==0 );
   81884       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   81885       break;
   81886     }
   81887     case TK_LT:
   81888     case TK_LE:
   81889     case TK_GT:
   81890     case TK_GE:
   81891     case TK_NE:
   81892     case TK_EQ: {
   81893       testcase( jumpIfNull==0 );
   81894       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   81895       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   81896       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   81897                   r1, r2, dest, jumpIfNull);
   81898       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   81899       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   81900       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   81901       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   81902       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
   81903       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
   81904       testcase( regFree1==0 );
   81905       testcase( regFree2==0 );
   81906       break;
   81907     }
   81908     case TK_IS:
   81909     case TK_ISNOT: {
   81910       testcase( op==TK_IS );
   81911       testcase( op==TK_ISNOT );
   81912       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   81913       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   81914       op = (op==TK_IS) ? TK_EQ : TK_NE;
   81915       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   81916                   r1, r2, dest, SQLITE_NULLEQ);
   81917       VdbeCoverageIf(v, op==TK_EQ);
   81918       VdbeCoverageIf(v, op==TK_NE);
   81919       testcase( regFree1==0 );
   81920       testcase( regFree2==0 );
   81921       break;
   81922     }
   81923     case TK_ISNULL:
   81924     case TK_NOTNULL: {
   81925       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
   81926       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
   81927       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   81928       sqlite3VdbeAddOp2(v, op, r1, dest);
   81929       VdbeCoverageIf(v, op==TK_ISNULL);
   81930       VdbeCoverageIf(v, op==TK_NOTNULL);
   81931       testcase( regFree1==0 );
   81932       break;
   81933     }
   81934     case TK_BETWEEN: {
   81935       testcase( jumpIfNull==0 );
   81936       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
   81937       break;
   81938     }
   81939 #ifndef SQLITE_OMIT_SUBQUERY
   81940     case TK_IN: {
   81941       int destIfFalse = sqlite3VdbeMakeLabel(v);
   81942       int destIfNull = jumpIfNull ? dest : destIfFalse;
   81943       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   81944       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   81945       sqlite3VdbeResolveLabel(v, destIfFalse);
   81946       break;
   81947     }
   81948 #endif
   81949     default: {
   81950       if( exprAlwaysTrue(pExpr) ){
   81951         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   81952       }else if( exprAlwaysFalse(pExpr) ){
   81953         /* No-op */
   81954       }else{
   81955         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   81956         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
   81957         VdbeCoverage(v);
   81958         testcase( regFree1==0 );
   81959         testcase( jumpIfNull==0 );
   81960       }
   81961       break;
   81962     }
   81963   }
   81964   sqlite3ReleaseTempReg(pParse, regFree1);
   81965   sqlite3ReleaseTempReg(pParse, regFree2);
   81966 }
   81967 
   81968 /*
   81969 ** Generate code for a boolean expression such that a jump is made
   81970 ** to the label "dest" if the expression is false but execution
   81971 ** continues straight thru if the expression is true.
   81972 **
   81973 ** If the expression evaluates to NULL (neither true nor false) then
   81974 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
   81975 ** is 0.
   81976 */
   81977 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   81978   Vdbe *v = pParse->pVdbe;
   81979   int op = 0;
   81980   int regFree1 = 0;
   81981   int regFree2 = 0;
   81982   int r1, r2;
   81983 
   81984   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   81985   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
   81986   if( pExpr==0 )    return;
   81987 
   81988   /* The value of pExpr->op and op are related as follows:
   81989   **
   81990   **       pExpr->op            op
   81991   **       ---------          ----------
   81992   **       TK_ISNULL          OP_NotNull
   81993   **       TK_NOTNULL         OP_IsNull
   81994   **       TK_NE              OP_Eq
   81995   **       TK_EQ              OP_Ne
   81996   **       TK_GT              OP_Le
   81997   **       TK_LE              OP_Gt
   81998   **       TK_GE              OP_Lt
   81999   **       TK_LT              OP_Ge
   82000   **
   82001   ** For other values of pExpr->op, op is undefined and unused.
   82002   ** The value of TK_ and OP_ constants are arranged such that we
   82003   ** can compute the mapping above using the following expression.
   82004   ** Assert()s verify that the computation is correct.
   82005   */
   82006   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
   82007 
   82008   /* Verify correct alignment of TK_ and OP_ constants
   82009   */
   82010   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
   82011   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
   82012   assert( pExpr->op!=TK_NE || op==OP_Eq );
   82013   assert( pExpr->op!=TK_EQ || op==OP_Ne );
   82014   assert( pExpr->op!=TK_LT || op==OP_Ge );
   82015   assert( pExpr->op!=TK_LE || op==OP_Gt );
   82016   assert( pExpr->op!=TK_GT || op==OP_Le );
   82017   assert( pExpr->op!=TK_GE || op==OP_Lt );
   82018 
   82019   switch( pExpr->op ){
   82020     case TK_AND: {
   82021       testcase( jumpIfNull==0 );
   82022       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   82023       sqlite3ExprCachePush(pParse);
   82024       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   82025       sqlite3ExprCachePop(pParse);
   82026       break;
   82027     }
   82028     case TK_OR: {
   82029       int d2 = sqlite3VdbeMakeLabel(v);
   82030       testcase( jumpIfNull==0 );
   82031       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
   82032       sqlite3ExprCachePush(pParse);
   82033       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   82034       sqlite3VdbeResolveLabel(v, d2);
   82035       sqlite3ExprCachePop(pParse);
   82036       break;
   82037     }
   82038     case TK_NOT: {
   82039       testcase( jumpIfNull==0 );
   82040       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   82041       break;
   82042     }
   82043     case TK_LT:
   82044     case TK_LE:
   82045     case TK_GT:
   82046     case TK_GE:
   82047     case TK_NE:
   82048     case TK_EQ: {
   82049       testcase( jumpIfNull==0 );
   82050       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   82051       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   82052       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   82053                   r1, r2, dest, jumpIfNull);
   82054       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   82055       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   82056       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   82057       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   82058       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
   82059       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
   82060       testcase( regFree1==0 );
   82061       testcase( regFree2==0 );
   82062       break;
   82063     }
   82064     case TK_IS:
   82065     case TK_ISNOT: {
   82066       testcase( pExpr->op==TK_IS );
   82067       testcase( pExpr->op==TK_ISNOT );
   82068       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   82069       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   82070       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
   82071       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   82072                   r1, r2, dest, SQLITE_NULLEQ);
   82073       VdbeCoverageIf(v, op==TK_EQ);
   82074       VdbeCoverageIf(v, op==TK_NE);
   82075       testcase( regFree1==0 );
   82076       testcase( regFree2==0 );
   82077       break;
   82078     }
   82079     case TK_ISNULL:
   82080     case TK_NOTNULL: {
   82081       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   82082       sqlite3VdbeAddOp2(v, op, r1, dest);
   82083       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
   82084       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
   82085       testcase( regFree1==0 );
   82086       break;
   82087     }
   82088     case TK_BETWEEN: {
   82089       testcase( jumpIfNull==0 );
   82090       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
   82091       break;
   82092     }
   82093 #ifndef SQLITE_OMIT_SUBQUERY
   82094     case TK_IN: {
   82095       if( jumpIfNull ){
   82096         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
   82097       }else{
   82098         int destIfNull = sqlite3VdbeMakeLabel(v);
   82099         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
   82100         sqlite3VdbeResolveLabel(v, destIfNull);
   82101       }
   82102       break;
   82103     }
   82104 #endif
   82105     default: {
   82106       if( exprAlwaysFalse(pExpr) ){
   82107         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   82108       }else if( exprAlwaysTrue(pExpr) ){
   82109         /* no-op */
   82110       }else{
   82111         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   82112         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
   82113         VdbeCoverage(v);
   82114         testcase( regFree1==0 );
   82115         testcase( jumpIfNull==0 );
   82116       }
   82117       break;
   82118     }
   82119   }
   82120   sqlite3ReleaseTempReg(pParse, regFree1);
   82121   sqlite3ReleaseTempReg(pParse, regFree2);
   82122 }
   82123 
   82124 /*
   82125 ** Do a deep comparison of two expression trees.  Return 0 if the two
   82126 ** expressions are completely identical.  Return 1 if they differ only
   82127 ** by a COLLATE operator at the top level.  Return 2 if there are differences
   82128 ** other than the top-level COLLATE operator.
   82129 **
   82130 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
   82131 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
   82132 **
   82133 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
   82134 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
   82135 **
   82136 ** Sometimes this routine will return 2 even if the two expressions
   82137 ** really are equivalent.  If we cannot prove that the expressions are
   82138 ** identical, we return 2 just to be safe.  So if this routine
   82139 ** returns 2, then you do not really know for certain if the two
   82140 ** expressions are the same.  But if you get a 0 or 1 return, then you
   82141 ** can be sure the expressions are the same.  In the places where
   82142 ** this routine is used, it does not hurt to get an extra 2 - that
   82143 ** just might result in some slightly slower code.  But returning
   82144 ** an incorrect 0 or 1 could lead to a malfunction.
   82145 */
   82146 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
   82147   u32 combinedFlags;
   82148   if( pA==0 || pB==0 ){
   82149     return pB==pA ? 0 : 2;
   82150   }
   82151   combinedFlags = pA->flags | pB->flags;
   82152   if( combinedFlags & EP_IntValue ){
   82153     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
   82154       return 0;
   82155     }
   82156     return 2;
   82157   }
   82158   if( pA->op!=pB->op ){
   82159     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
   82160       return 1;
   82161     }
   82162     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
   82163       return 1;
   82164     }
   82165     return 2;
   82166   }
   82167   if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
   82168     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
   82169       return pA->op==TK_COLLATE ? 1 : 2;
   82170     }
   82171   }
   82172   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
   82173   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
   82174     if( combinedFlags & EP_xIsSelect ) return 2;
   82175     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
   82176     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
   82177     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
   82178     if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
   82179       if( pA->iColumn!=pB->iColumn ) return 2;
   82180       if( pA->iTable!=pB->iTable
   82181        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
   82182     }
   82183   }
   82184   return 0;
   82185 }
   82186 
   82187 /*
   82188 ** Compare two ExprList objects.  Return 0 if they are identical and
   82189 ** non-zero if they differ in any way.
   82190 **
   82191 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
   82192 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
   82193 **
   82194 ** This routine might return non-zero for equivalent ExprLists.  The
   82195 ** only consequence will be disabled optimizations.  But this routine
   82196 ** must never return 0 if the two ExprList objects are different, or
   82197 ** a malfunction will result.
   82198 **
   82199 ** Two NULL pointers are considered to be the same.  But a NULL pointer
   82200 ** always differs from a non-NULL pointer.
   82201 */
   82202 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
   82203   int i;
   82204   if( pA==0 && pB==0 ) return 0;
   82205   if( pA==0 || pB==0 ) return 1;
   82206   if( pA->nExpr!=pB->nExpr ) return 1;
   82207   for(i=0; i<pA->nExpr; i++){
   82208     Expr *pExprA = pA->a[i].pExpr;
   82209     Expr *pExprB = pB->a[i].pExpr;
   82210     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
   82211     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
   82212   }
   82213   return 0;
   82214 }
   82215 
   82216 /*
   82217 ** Return true if we can prove the pE2 will always be true if pE1 is
   82218 ** true.  Return false if we cannot complete the proof or if pE2 might
   82219 ** be false.  Examples:
   82220 **
   82221 **     pE1: x==5       pE2: x==5             Result: true
   82222 **     pE1: x>0        pE2: x==5             Result: false
   82223 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
   82224 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
   82225 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
   82226 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
   82227 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
   82228 **
   82229 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
   82230 ** Expr.iTable<0 then assume a table number given by iTab.
   82231 **
   82232 ** When in doubt, return false.  Returning true might give a performance
   82233 ** improvement.  Returning false might cause a performance reduction, but
   82234 ** it will always give the correct answer and is hence always safe.
   82235 */
   82236 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
   82237   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
   82238     return 1;
   82239   }
   82240   if( pE2->op==TK_OR
   82241    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
   82242              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
   82243   ){
   82244     return 1;
   82245   }
   82246   if( pE2->op==TK_NOTNULL
   82247    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
   82248    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
   82249   ){
   82250     return 1;
   82251   }
   82252   return 0;
   82253 }
   82254 
   82255 /*
   82256 ** An instance of the following structure is used by the tree walker
   82257 ** to count references to table columns in the arguments of an
   82258 ** aggregate function, in order to implement the
   82259 ** sqlite3FunctionThisSrc() routine.
   82260 */
   82261 struct SrcCount {
   82262   SrcList *pSrc;   /* One particular FROM clause in a nested query */
   82263   int nThis;       /* Number of references to columns in pSrcList */
   82264   int nOther;      /* Number of references to columns in other FROM clauses */
   82265 };
   82266 
   82267 /*
   82268 ** Count the number of references to columns.
   82269 */
   82270 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
   82271   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
   82272   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
   82273   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
   82274   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
   82275   ** NEVER() will need to be removed. */
   82276   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
   82277     int i;
   82278     struct SrcCount *p = pWalker->u.pSrcCount;
   82279     SrcList *pSrc = p->pSrc;
   82280     for(i=0; i<pSrc->nSrc; i++){
   82281       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
   82282     }
   82283     if( i<pSrc->nSrc ){
   82284       p->nThis++;
   82285     }else{
   82286       p->nOther++;
   82287     }
   82288   }
   82289   return WRC_Continue;
   82290 }
   82291 
   82292 /*
   82293 ** Determine if any of the arguments to the pExpr Function reference
   82294 ** pSrcList.  Return true if they do.  Also return true if the function
   82295 ** has no arguments or has only constant arguments.  Return false if pExpr
   82296 ** references columns but not columns of tables found in pSrcList.
   82297 */
   82298 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
   82299   Walker w;
   82300   struct SrcCount cnt;
   82301   assert( pExpr->op==TK_AGG_FUNCTION );
   82302   memset(&w, 0, sizeof(w));
   82303   w.xExprCallback = exprSrcCount;
   82304   w.u.pSrcCount = &cnt;
   82305   cnt.pSrc = pSrcList;
   82306   cnt.nThis = 0;
   82307   cnt.nOther = 0;
   82308   sqlite3WalkExprList(&w, pExpr->x.pList);
   82309   return cnt.nThis>0 || cnt.nOther==0;
   82310 }
   82311 
   82312 /*
   82313 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
   82314 ** the new element.  Return a negative number if malloc fails.
   82315 */
   82316 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
   82317   int i;
   82318   pInfo->aCol = sqlite3ArrayAllocate(
   82319        db,
   82320        pInfo->aCol,
   82321        sizeof(pInfo->aCol[0]),
   82322        &pInfo->nColumn,
   82323        &i
   82324   );
   82325   return i;
   82326 }
   82327 
   82328 /*
   82329 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
   82330 ** the new element.  Return a negative number if malloc fails.
   82331 */
   82332 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
   82333   int i;
   82334   pInfo->aFunc = sqlite3ArrayAllocate(
   82335        db,
   82336        pInfo->aFunc,
   82337        sizeof(pInfo->aFunc[0]),
   82338        &pInfo->nFunc,
   82339        &i
   82340   );
   82341   return i;
   82342 }
   82343 
   82344 /*
   82345 ** This is the xExprCallback for a tree walker.  It is used to
   82346 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
   82347 ** for additional information.
   82348 */
   82349 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
   82350   int i;
   82351   NameContext *pNC = pWalker->u.pNC;
   82352   Parse *pParse = pNC->pParse;
   82353   SrcList *pSrcList = pNC->pSrcList;
   82354   AggInfo *pAggInfo = pNC->pAggInfo;
   82355 
   82356   switch( pExpr->op ){
   82357     case TK_AGG_COLUMN:
   82358     case TK_COLUMN: {
   82359       testcase( pExpr->op==TK_AGG_COLUMN );
   82360       testcase( pExpr->op==TK_COLUMN );
   82361       /* Check to see if the column is in one of the tables in the FROM
   82362       ** clause of the aggregate query */
   82363       if( ALWAYS(pSrcList!=0) ){
   82364         struct SrcList_item *pItem = pSrcList->a;
   82365         for(i=0; i<pSrcList->nSrc; i++, pItem++){
   82366           struct AggInfo_col *pCol;
   82367           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   82368           if( pExpr->iTable==pItem->iCursor ){
   82369             /* If we reach this point, it means that pExpr refers to a table
   82370             ** that is in the FROM clause of the aggregate query.
   82371             **
   82372             ** Make an entry for the column in pAggInfo->aCol[] if there
   82373             ** is not an entry there already.
   82374             */
   82375             int k;
   82376             pCol = pAggInfo->aCol;
   82377             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
   82378               if( pCol->iTable==pExpr->iTable &&
   82379                   pCol->iColumn==pExpr->iColumn ){
   82380                 break;
   82381               }
   82382             }
   82383             if( (k>=pAggInfo->nColumn)
   82384              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
   82385             ){
   82386               pCol = &pAggInfo->aCol[k];
   82387               pCol->pTab = pExpr->pTab;
   82388               pCol->iTable = pExpr->iTable;
   82389               pCol->iColumn = pExpr->iColumn;
   82390               pCol->iMem = ++pParse->nMem;
   82391               pCol->iSorterColumn = -1;
   82392               pCol->pExpr = pExpr;
   82393               if( pAggInfo->pGroupBy ){
   82394                 int j, n;
   82395                 ExprList *pGB = pAggInfo->pGroupBy;
   82396                 struct ExprList_item *pTerm = pGB->a;
   82397                 n = pGB->nExpr;
   82398                 for(j=0; j<n; j++, pTerm++){
   82399                   Expr *pE = pTerm->pExpr;
   82400                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
   82401                       pE->iColumn==pExpr->iColumn ){
   82402                     pCol->iSorterColumn = j;
   82403                     break;
   82404                   }
   82405                 }
   82406               }
   82407               if( pCol->iSorterColumn<0 ){
   82408                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
   82409               }
   82410             }
   82411             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
   82412             ** because it was there before or because we just created it).
   82413             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
   82414             ** pAggInfo->aCol[] entry.
   82415             */
   82416             ExprSetVVAProperty(pExpr, EP_NoReduce);
   82417             pExpr->pAggInfo = pAggInfo;
   82418             pExpr->op = TK_AGG_COLUMN;
   82419             pExpr->iAgg = (i16)k;
   82420             break;
   82421           } /* endif pExpr->iTable==pItem->iCursor */
   82422         } /* end loop over pSrcList */
   82423       }
   82424       return WRC_Prune;
   82425     }
   82426     case TK_AGG_FUNCTION: {
   82427       if( (pNC->ncFlags & NC_InAggFunc)==0
   82428        && pWalker->walkerDepth==pExpr->op2
   82429       ){
   82430         /* Check to see if pExpr is a duplicate of another aggregate
   82431         ** function that is already in the pAggInfo structure
   82432         */
   82433         struct AggInfo_func *pItem = pAggInfo->aFunc;
   82434         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
   82435           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
   82436             break;
   82437           }
   82438         }
   82439         if( i>=pAggInfo->nFunc ){
   82440           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
   82441           */
   82442           u8 enc = ENC(pParse->db);
   82443           i = addAggInfoFunc(pParse->db, pAggInfo);
   82444           if( i>=0 ){
   82445             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   82446             pItem = &pAggInfo->aFunc[i];
   82447             pItem->pExpr = pExpr;
   82448             pItem->iMem = ++pParse->nMem;
   82449             assert( !ExprHasProperty(pExpr, EP_IntValue) );
   82450             pItem->pFunc = sqlite3FindFunction(pParse->db,
   82451                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
   82452                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
   82453             if( pExpr->flags & EP_Distinct ){
   82454               pItem->iDistinct = pParse->nTab++;
   82455             }else{
   82456               pItem->iDistinct = -1;
   82457             }
   82458           }
   82459         }
   82460         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
   82461         */
   82462         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   82463         ExprSetVVAProperty(pExpr, EP_NoReduce);
   82464         pExpr->iAgg = (i16)i;
   82465         pExpr->pAggInfo = pAggInfo;
   82466         return WRC_Prune;
   82467       }else{
   82468         return WRC_Continue;
   82469       }
   82470     }
   82471   }
   82472   return WRC_Continue;
   82473 }
   82474 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
   82475   UNUSED_PARAMETER(pWalker);
   82476   UNUSED_PARAMETER(pSelect);
   82477   return WRC_Continue;
   82478 }
   82479 
   82480 /*
   82481 ** Analyze the pExpr expression looking for aggregate functions and
   82482 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
   82483 ** points to.  Additional entries are made on the AggInfo object as
   82484 ** necessary.
   82485 **
   82486 ** This routine should only be called after the expression has been
   82487 ** analyzed by sqlite3ResolveExprNames().
   82488 */
   82489 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
   82490   Walker w;
   82491   memset(&w, 0, sizeof(w));
   82492   w.xExprCallback = analyzeAggregate;
   82493   w.xSelectCallback = analyzeAggregatesInSelect;
   82494   w.u.pNC = pNC;
   82495   assert( pNC->pSrcList!=0 );
   82496   sqlite3WalkExpr(&w, pExpr);
   82497 }
   82498 
   82499 /*
   82500 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
   82501 ** expression list.  Return the number of errors.
   82502 **
   82503 ** If an error is found, the analysis is cut short.
   82504 */
   82505 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
   82506   struct ExprList_item *pItem;
   82507   int i;
   82508   if( pList ){
   82509     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   82510       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
   82511     }
   82512   }
   82513 }
   82514 
   82515 /*
   82516 ** Allocate a single new register for use to hold some intermediate result.
   82517 */
   82518 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
   82519   if( pParse->nTempReg==0 ){
   82520     return ++pParse->nMem;
   82521   }
   82522   return pParse->aTempReg[--pParse->nTempReg];
   82523 }
   82524 
   82525 /*
   82526 ** Deallocate a register, making available for reuse for some other
   82527 ** purpose.
   82528 **
   82529 ** If a register is currently being used by the column cache, then
   82530 ** the dallocation is deferred until the column cache line that uses
   82531 ** the register becomes stale.
   82532 */
   82533 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
   82534   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   82535     int i;
   82536     struct yColCache *p;
   82537     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   82538       if( p->iReg==iReg ){
   82539         p->tempReg = 1;
   82540         return;
   82541       }
   82542     }
   82543     pParse->aTempReg[pParse->nTempReg++] = iReg;
   82544   }
   82545 }
   82546 
   82547 /*
   82548 ** Allocate or deallocate a block of nReg consecutive registers
   82549 */
   82550 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
   82551   int i, n;
   82552   i = pParse->iRangeReg;
   82553   n = pParse->nRangeReg;
   82554   if( nReg<=n ){
   82555     assert( !usedAsColumnCache(pParse, i, i+n-1) );
   82556     pParse->iRangeReg += nReg;
   82557     pParse->nRangeReg -= nReg;
   82558   }else{
   82559     i = pParse->nMem+1;
   82560     pParse->nMem += nReg;
   82561   }
   82562   return i;
   82563 }
   82564 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
   82565   sqlite3ExprCacheRemove(pParse, iReg, nReg);
   82566   if( nReg>pParse->nRangeReg ){
   82567     pParse->nRangeReg = nReg;
   82568     pParse->iRangeReg = iReg;
   82569   }
   82570 }
   82571 
   82572 /*
   82573 ** Mark all temporary registers as being unavailable for reuse.
   82574 */
   82575 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
   82576   pParse->nTempReg = 0;
   82577   pParse->nRangeReg = 0;
   82578 }
   82579 
   82580 /************** End of expr.c ************************************************/
   82581 /************** Begin file alter.c *******************************************/
   82582 /*
   82583 ** 2005 February 15
   82584 **
   82585 ** The author disclaims copyright to this source code.  In place of
   82586 ** a legal notice, here is a blessing:
   82587 **
   82588 **    May you do good and not evil.
   82589 **    May you find forgiveness for yourself and forgive others.
   82590 **    May you share freely, never taking more than you give.
   82591 **
   82592 *************************************************************************
   82593 ** This file contains C code routines that used to generate VDBE code
   82594 ** that implements the ALTER TABLE command.
   82595 */
   82596 
   82597 /*
   82598 ** The code in this file only exists if we are not omitting the
   82599 ** ALTER TABLE logic from the build.
   82600 */
   82601 #ifndef SQLITE_OMIT_ALTERTABLE
   82602 
   82603 
   82604 /*
   82605 ** This function is used by SQL generated to implement the
   82606 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
   82607 ** CREATE INDEX command. The second is a table name. The table name in
   82608 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
   82609 ** argument and the result returned. Examples:
   82610 **
   82611 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
   82612 **     -> 'CREATE TABLE def(a, b, c)'
   82613 **
   82614 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
   82615 **     -> 'CREATE INDEX i ON def(a, b, c)'
   82616 */
   82617 static void renameTableFunc(
   82618   sqlite3_context *context,
   82619   int NotUsed,
   82620   sqlite3_value **argv
   82621 ){
   82622   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   82623   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   82624 
   82625   int token;
   82626   Token tname;
   82627   unsigned char const *zCsr = zSql;
   82628   int len = 0;
   82629   char *zRet;
   82630 
   82631   sqlite3 *db = sqlite3_context_db_handle(context);
   82632 
   82633   UNUSED_PARAMETER(NotUsed);
   82634 
   82635   /* The principle used to locate the table name in the CREATE TABLE
   82636   ** statement is that the table name is the first non-space token that
   82637   ** is immediately followed by a TK_LP or TK_USING token.
   82638   */
   82639   if( zSql ){
   82640     do {
   82641       if( !*zCsr ){
   82642         /* Ran out of input before finding an opening bracket. Return NULL. */
   82643         return;
   82644       }
   82645 
   82646       /* Store the token that zCsr points to in tname. */
   82647       tname.z = (char*)zCsr;
   82648       tname.n = len;
   82649 
   82650       /* Advance zCsr to the next token. Store that token type in 'token',
   82651       ** and its length in 'len' (to be used next iteration of this loop).
   82652       */
   82653       do {
   82654         zCsr += len;
   82655         len = sqlite3GetToken(zCsr, &token);
   82656       } while( token==TK_SPACE );
   82657       assert( len>0 );
   82658     } while( token!=TK_LP && token!=TK_USING );
   82659 
   82660     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
   82661        zSql, zTableName, tname.z+tname.n);
   82662     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   82663   }
   82664 }
   82665 
   82666 /*
   82667 ** This C function implements an SQL user function that is used by SQL code
   82668 ** generated by the ALTER TABLE ... RENAME command to modify the definition
   82669 ** of any foreign key constraints that use the table being renamed as the
   82670 ** parent table. It is passed three arguments:
   82671 **
   82672 **   1) The complete text of the CREATE TABLE statement being modified,
   82673 **   2) The old name of the table being renamed, and
   82674 **   3) The new name of the table being renamed.
   82675 **
   82676 ** It returns the new CREATE TABLE statement. For example:
   82677 **
   82678 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
   82679 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
   82680 */
   82681 #ifndef SQLITE_OMIT_FOREIGN_KEY
   82682 static void renameParentFunc(
   82683   sqlite3_context *context,
   82684   int NotUsed,
   82685   sqlite3_value **argv
   82686 ){
   82687   sqlite3 *db = sqlite3_context_db_handle(context);
   82688   char *zOutput = 0;
   82689   char *zResult;
   82690   unsigned char const *zInput = sqlite3_value_text(argv[0]);
   82691   unsigned char const *zOld = sqlite3_value_text(argv[1]);
   82692   unsigned char const *zNew = sqlite3_value_text(argv[2]);
   82693 
   82694   unsigned const char *z;         /* Pointer to token */
   82695   int n;                          /* Length of token z */
   82696   int token;                      /* Type of token */
   82697 
   82698   UNUSED_PARAMETER(NotUsed);
   82699   if( zInput==0 || zOld==0 ) return;
   82700   for(z=zInput; *z; z=z+n){
   82701     n = sqlite3GetToken(z, &token);
   82702     if( token==TK_REFERENCES ){
   82703       char *zParent;
   82704       do {
   82705         z += n;
   82706         n = sqlite3GetToken(z, &token);
   82707       }while( token==TK_SPACE );
   82708 
   82709       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
   82710       if( zParent==0 ) break;
   82711       sqlite3Dequote(zParent);
   82712       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
   82713         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
   82714             (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
   82715         );
   82716         sqlite3DbFree(db, zOutput);
   82717         zOutput = zOut;
   82718         zInput = &z[n];
   82719       }
   82720       sqlite3DbFree(db, zParent);
   82721     }
   82722   }
   82723 
   82724   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
   82725   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
   82726   sqlite3DbFree(db, zOutput);
   82727 }
   82728 #endif
   82729 
   82730 #ifndef SQLITE_OMIT_TRIGGER
   82731 /* This function is used by SQL generated to implement the
   82732 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
   82733 ** statement. The second is a table name. The table name in the CREATE
   82734 ** TRIGGER statement is replaced with the third argument and the result
   82735 ** returned. This is analagous to renameTableFunc() above, except for CREATE
   82736 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
   82737 */
   82738 static void renameTriggerFunc(
   82739   sqlite3_context *context,
   82740   int NotUsed,
   82741   sqlite3_value **argv
   82742 ){
   82743   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   82744   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   82745 
   82746   int token;
   82747   Token tname;
   82748   int dist = 3;
   82749   unsigned char const *zCsr = zSql;
   82750   int len = 0;
   82751   char *zRet;
   82752   sqlite3 *db = sqlite3_context_db_handle(context);
   82753 
   82754   UNUSED_PARAMETER(NotUsed);
   82755 
   82756   /* The principle used to locate the table name in the CREATE TRIGGER
   82757   ** statement is that the table name is the first token that is immediatedly
   82758   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
   82759   ** of TK_WHEN, TK_BEGIN or TK_FOR.
   82760   */
   82761   if( zSql ){
   82762     do {
   82763 
   82764       if( !*zCsr ){
   82765         /* Ran out of input before finding the table name. Return NULL. */
   82766         return;
   82767       }
   82768 
   82769       /* Store the token that zCsr points to in tname. */
   82770       tname.z = (char*)zCsr;
   82771       tname.n = len;
   82772 
   82773       /* Advance zCsr to the next token. Store that token type in 'token',
   82774       ** and its length in 'len' (to be used next iteration of this loop).
   82775       */
   82776       do {
   82777         zCsr += len;
   82778         len = sqlite3GetToken(zCsr, &token);
   82779       }while( token==TK_SPACE );
   82780       assert( len>0 );
   82781 
   82782       /* Variable 'dist' stores the number of tokens read since the most
   82783       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
   82784       ** token is read and 'dist' equals 2, the condition stated above
   82785       ** to be met.
   82786       **
   82787       ** Note that ON cannot be a database, table or column name, so
   82788       ** there is no need to worry about syntax like
   82789       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
   82790       */
   82791       dist++;
   82792       if( token==TK_DOT || token==TK_ON ){
   82793         dist = 0;
   82794       }
   82795     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
   82796 
   82797     /* Variable tname now contains the token that is the old table-name
   82798     ** in the CREATE TRIGGER statement.
   82799     */
   82800     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
   82801        zSql, zTableName, tname.z+tname.n);
   82802     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   82803   }
   82804 }
   82805 #endif   /* !SQLITE_OMIT_TRIGGER */
   82806 
   82807 /*
   82808 ** Register built-in functions used to help implement ALTER TABLE
   82809 */
   82810 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
   82811   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
   82812     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
   82813 #ifndef SQLITE_OMIT_TRIGGER
   82814     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
   82815 #endif
   82816 #ifndef SQLITE_OMIT_FOREIGN_KEY
   82817     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
   82818 #endif
   82819   };
   82820   int i;
   82821   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   82822   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
   82823 
   82824   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
   82825     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   82826   }
   82827 }
   82828 
   82829 /*
   82830 ** This function is used to create the text of expressions of the form:
   82831 **
   82832 **   name=<constant1> OR name=<constant2> OR ...
   82833 **
   82834 ** If argument zWhere is NULL, then a pointer string containing the text
   82835 ** "name=<constant>" is returned, where <constant> is the quoted version
   82836 ** of the string passed as argument zConstant. The returned buffer is
   82837 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
   82838 ** caller to ensure that it is eventually freed.
   82839 **
   82840 ** If argument zWhere is not NULL, then the string returned is
   82841 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
   82842 ** In this case zWhere is passed to sqlite3DbFree() before returning.
   82843 **
   82844 */
   82845 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
   82846   char *zNew;
   82847   if( !zWhere ){
   82848     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
   82849   }else{
   82850     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
   82851     sqlite3DbFree(db, zWhere);
   82852   }
   82853   return zNew;
   82854 }
   82855 
   82856 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   82857 /*
   82858 ** Generate the text of a WHERE expression which can be used to select all
   82859 ** tables that have foreign key constraints that refer to table pTab (i.e.
   82860 ** constraints for which pTab is the parent table) from the sqlite_master
   82861 ** table.
   82862 */
   82863 static char *whereForeignKeys(Parse *pParse, Table *pTab){
   82864   FKey *p;
   82865   char *zWhere = 0;
   82866   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   82867     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
   82868   }
   82869   return zWhere;
   82870 }
   82871 #endif
   82872 
   82873 /*
   82874 ** Generate the text of a WHERE expression which can be used to select all
   82875 ** temporary triggers on table pTab from the sqlite_temp_master table. If
   82876 ** table pTab has no temporary triggers, or is itself stored in the
   82877 ** temporary database, NULL is returned.
   82878 */
   82879 static char *whereTempTriggers(Parse *pParse, Table *pTab){
   82880   Trigger *pTrig;
   82881   char *zWhere = 0;
   82882   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
   82883 
   82884   /* If the table is not located in the temp-db (in which case NULL is
   82885   ** returned, loop through the tables list of triggers. For each trigger
   82886   ** that is not part of the temp-db schema, add a clause to the WHERE
   82887   ** expression being built up in zWhere.
   82888   */
   82889   if( pTab->pSchema!=pTempSchema ){
   82890     sqlite3 *db = pParse->db;
   82891     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   82892       if( pTrig->pSchema==pTempSchema ){
   82893         zWhere = whereOrName(db, zWhere, pTrig->zName);
   82894       }
   82895     }
   82896   }
   82897   if( zWhere ){
   82898     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
   82899     sqlite3DbFree(pParse->db, zWhere);
   82900     zWhere = zNew;
   82901   }
   82902   return zWhere;
   82903 }
   82904 
   82905 /*
   82906 ** Generate code to drop and reload the internal representation of table
   82907 ** pTab from the database, including triggers and temporary triggers.
   82908 ** Argument zName is the name of the table in the database schema at
   82909 ** the time the generated code is executed. This can be different from
   82910 ** pTab->zName if this function is being called to code part of an
   82911 ** "ALTER TABLE RENAME TO" statement.
   82912 */
   82913 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
   82914   Vdbe *v;
   82915   char *zWhere;
   82916   int iDb;                   /* Index of database containing pTab */
   82917 #ifndef SQLITE_OMIT_TRIGGER
   82918   Trigger *pTrig;
   82919 #endif
   82920 
   82921   v = sqlite3GetVdbe(pParse);
   82922   if( NEVER(v==0) ) return;
   82923   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   82924   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   82925   assert( iDb>=0 );
   82926 
   82927 #ifndef SQLITE_OMIT_TRIGGER
   82928   /* Drop any table triggers from the internal schema. */
   82929   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   82930     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   82931     assert( iTrigDb==iDb || iTrigDb==1 );
   82932     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
   82933   }
   82934 #endif
   82935 
   82936   /* Drop the table and index from the internal schema.  */
   82937   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   82938 
   82939   /* Reload the table, index and permanent trigger schemas. */
   82940   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
   82941   if( !zWhere ) return;
   82942   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   82943 
   82944 #ifndef SQLITE_OMIT_TRIGGER
   82945   /* Now, if the table is not stored in the temp database, reload any temp
   82946   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
   82947   */
   82948   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   82949     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
   82950   }
   82951 #endif
   82952 }
   82953 
   82954 /*
   82955 ** Parameter zName is the name of a table that is about to be altered
   82956 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
   82957 ** If the table is a system table, this function leaves an error message
   82958 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
   82959 **
   82960 ** Or, if zName is not a system table, zero is returned.
   82961 */
   82962 static int isSystemTable(Parse *pParse, const char *zName){
   82963   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   82964     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
   82965     return 1;
   82966   }
   82967   return 0;
   82968 }
   82969 
   82970 /*
   82971 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
   82972 ** command.
   82973 */
   82974 SQLITE_PRIVATE void sqlite3AlterRenameTable(
   82975   Parse *pParse,            /* Parser context. */
   82976   SrcList *pSrc,            /* The table to rename. */
   82977   Token *pName              /* The new table name. */
   82978 ){
   82979   int iDb;                  /* Database that contains the table */
   82980   char *zDb;                /* Name of database iDb */
   82981   Table *pTab;              /* Table being renamed */
   82982   char *zName = 0;          /* NULL-terminated version of pName */
   82983   sqlite3 *db = pParse->db; /* Database connection */
   82984   int nTabName;             /* Number of UTF-8 characters in zTabName */
   82985   const char *zTabName;     /* Original name of the table */
   82986   Vdbe *v;
   82987 #ifndef SQLITE_OMIT_TRIGGER
   82988   char *zWhere = 0;         /* Where clause to locate temp triggers */
   82989 #endif
   82990   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
   82991   int savedDbFlags;         /* Saved value of db->flags */
   82992 
   82993   savedDbFlags = db->flags;
   82994   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   82995   assert( pSrc->nSrc==1 );
   82996   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   82997 
   82998   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
   82999   if( !pTab ) goto exit_rename_table;
   83000   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   83001   zDb = db->aDb[iDb].zName;
   83002   db->flags |= SQLITE_PreferBuiltin;
   83003 
   83004   /* Get a NULL terminated version of the new table name. */
   83005   zName = sqlite3NameFromToken(db, pName);
   83006   if( !zName ) goto exit_rename_table;
   83007 
   83008   /* Check that a table or index named 'zName' does not already exist
   83009   ** in database iDb. If so, this is an error.
   83010   */
   83011   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
   83012     sqlite3ErrorMsg(pParse,
   83013         "there is already another table or index with this name: %s", zName);
   83014     goto exit_rename_table;
   83015   }
   83016 
   83017   /* Make sure it is not a system table being altered, or a reserved name
   83018   ** that the table is being renamed to.
   83019   */
   83020   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   83021     goto exit_rename_table;
   83022   }
   83023   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
   83024     exit_rename_table;
   83025   }
   83026 
   83027 #ifndef SQLITE_OMIT_VIEW
   83028   if( pTab->pSelect ){
   83029     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
   83030     goto exit_rename_table;
   83031   }
   83032 #endif
   83033 
   83034 #ifndef SQLITE_OMIT_AUTHORIZATION
   83035   /* Invoke the authorization callback. */
   83036   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   83037     goto exit_rename_table;
   83038   }
   83039 #endif
   83040 
   83041 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83042   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   83043     goto exit_rename_table;
   83044   }
   83045   if( IsVirtual(pTab) ){
   83046     pVTab = sqlite3GetVTable(db, pTab);
   83047     if( pVTab->pVtab->pModule->xRename==0 ){
   83048       pVTab = 0;
   83049     }
   83050   }
   83051 #endif
   83052 
   83053   /* Begin a transaction for database iDb.
   83054   ** Then modify the schema cookie (since the ALTER TABLE modifies the
   83055   ** schema). Open a statement transaction if the table is a virtual
   83056   ** table.
   83057   */
   83058   v = sqlite3GetVdbe(pParse);
   83059   if( v==0 ){
   83060     goto exit_rename_table;
   83061   }
   83062   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
   83063   sqlite3ChangeCookie(pParse, iDb);
   83064 
   83065   /* If this is a virtual table, invoke the xRename() function if
   83066   ** one is defined. The xRename() callback will modify the names
   83067   ** of any resources used by the v-table implementation (including other
   83068   ** SQLite tables) that are identified by the name of the virtual table.
   83069   */
   83070 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83071   if( pVTab ){
   83072     int i = ++pParse->nMem;
   83073     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
   83074     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
   83075     sqlite3MayAbort(pParse);
   83076   }
   83077 #endif
   83078 
   83079   /* figure out how many UTF-8 characters are in zName */
   83080   zTabName = pTab->zName;
   83081   nTabName = sqlite3Utf8CharLen(zTabName, -1);
   83082 
   83083 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   83084   if( db->flags&SQLITE_ForeignKeys ){
   83085     /* If foreign-key support is enabled, rewrite the CREATE TABLE
   83086     ** statements corresponding to all child tables of foreign key constraints
   83087     ** for which the renamed table is the parent table.  */
   83088     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
   83089       sqlite3NestedParse(pParse,
   83090           "UPDATE \"%w\".%s SET "
   83091               "sql = sqlite_rename_parent(sql, %Q, %Q) "
   83092               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
   83093       sqlite3DbFree(db, zWhere);
   83094     }
   83095   }
   83096 #endif
   83097 
   83098   /* Modify the sqlite_master table to use the new table name. */
   83099   sqlite3NestedParse(pParse,
   83100       "UPDATE %Q.%s SET "
   83101 #ifdef SQLITE_OMIT_TRIGGER
   83102           "sql = sqlite_rename_table(sql, %Q), "
   83103 #else
   83104           "sql = CASE "
   83105             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
   83106             "ELSE sqlite_rename_table(sql, %Q) END, "
   83107 #endif
   83108           "tbl_name = %Q, "
   83109           "name = CASE "
   83110             "WHEN type='table' THEN %Q "
   83111             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
   83112              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
   83113             "ELSE name END "
   83114       "WHERE tbl_name=%Q COLLATE nocase AND "
   83115           "(type='table' OR type='index' OR type='trigger');",
   83116       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
   83117 #ifndef SQLITE_OMIT_TRIGGER
   83118       zName,
   83119 #endif
   83120       zName, nTabName, zTabName
   83121   );
   83122 
   83123 #ifndef SQLITE_OMIT_AUTOINCREMENT
   83124   /* If the sqlite_sequence table exists in this database, then update
   83125   ** it with the new table name.
   83126   */
   83127   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
   83128     sqlite3NestedParse(pParse,
   83129         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
   83130         zDb, zName, pTab->zName);
   83131   }
   83132 #endif
   83133 
   83134 #ifndef SQLITE_OMIT_TRIGGER
   83135   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
   83136   ** table. Don't do this if the table being ALTERed is itself located in
   83137   ** the temp database.
   83138   */
   83139   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   83140     sqlite3NestedParse(pParse,
   83141         "UPDATE sqlite_temp_master SET "
   83142             "sql = sqlite_rename_trigger(sql, %Q), "
   83143             "tbl_name = %Q "
   83144             "WHERE %s;", zName, zName, zWhere);
   83145     sqlite3DbFree(db, zWhere);
   83146   }
   83147 #endif
   83148 
   83149 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   83150   if( db->flags&SQLITE_ForeignKeys ){
   83151     FKey *p;
   83152     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   83153       Table *pFrom = p->pFrom;
   83154       if( pFrom!=pTab ){
   83155         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
   83156       }
   83157     }
   83158   }
   83159 #endif
   83160 
   83161   /* Drop and reload the internal table schema. */
   83162   reloadTableSchema(pParse, pTab, zName);
   83163 
   83164 exit_rename_table:
   83165   sqlite3SrcListDelete(db, pSrc);
   83166   sqlite3DbFree(db, zName);
   83167   db->flags = savedDbFlags;
   83168 }
   83169 
   83170 
   83171 /*
   83172 ** Generate code to make sure the file format number is at least minFormat.
   83173 ** The generated code will increase the file format number if necessary.
   83174 */
   83175 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
   83176   Vdbe *v;
   83177   v = sqlite3GetVdbe(pParse);
   83178   /* The VDBE should have been allocated before this routine is called.
   83179   ** If that allocation failed, we would have quit before reaching this
   83180   ** point */
   83181   if( ALWAYS(v) ){
   83182     int r1 = sqlite3GetTempReg(pParse);
   83183     int r2 = sqlite3GetTempReg(pParse);
   83184     int j1;
   83185     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
   83186     sqlite3VdbeUsesBtree(v, iDb);
   83187     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
   83188     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
   83189     sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
   83190     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
   83191     sqlite3VdbeJumpHere(v, j1);
   83192     sqlite3ReleaseTempReg(pParse, r1);
   83193     sqlite3ReleaseTempReg(pParse, r2);
   83194   }
   83195 }
   83196 
   83197 /*
   83198 ** This function is called after an "ALTER TABLE ... ADD" statement
   83199 ** has been parsed. Argument pColDef contains the text of the new
   83200 ** column definition.
   83201 **
   83202 ** The Table structure pParse->pNewTable was extended to include
   83203 ** the new column during parsing.
   83204 */
   83205 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   83206   Table *pNew;              /* Copy of pParse->pNewTable */
   83207   Table *pTab;              /* Table being altered */
   83208   int iDb;                  /* Database number */
   83209   const char *zDb;          /* Database name */
   83210   const char *zTab;         /* Table name */
   83211   char *zCol;               /* Null-terminated column definition */
   83212   Column *pCol;             /* The new column */
   83213   Expr *pDflt;              /* Default value for the new column */
   83214   sqlite3 *db;              /* The database connection; */
   83215 
   83216   db = pParse->db;
   83217   if( pParse->nErr || db->mallocFailed ) return;
   83218   pNew = pParse->pNewTable;
   83219   assert( pNew );
   83220 
   83221   assert( sqlite3BtreeHoldsAllMutexes(db) );
   83222   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
   83223   zDb = db->aDb[iDb].zName;
   83224   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   83225   pCol = &pNew->aCol[pNew->nCol-1];
   83226   pDflt = pCol->pDflt;
   83227   pTab = sqlite3FindTable(db, zTab, zDb);
   83228   assert( pTab );
   83229 
   83230 #ifndef SQLITE_OMIT_AUTHORIZATION
   83231   /* Invoke the authorization callback. */
   83232   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   83233     return;
   83234   }
   83235 #endif
   83236 
   83237   /* If the default value for the new column was specified with a
   83238   ** literal NULL, then set pDflt to 0. This simplifies checking
   83239   ** for an SQL NULL default below.
   83240   */
   83241   if( pDflt && pDflt->op==TK_NULL ){
   83242     pDflt = 0;
   83243   }
   83244 
   83245   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
   83246   ** If there is a NOT NULL constraint, then the default value for the
   83247   ** column must not be NULL.
   83248   */
   83249   if( pCol->colFlags & COLFLAG_PRIMKEY ){
   83250     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
   83251     return;
   83252   }
   83253   if( pNew->pIndex ){
   83254     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
   83255     return;
   83256   }
   83257   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
   83258     sqlite3ErrorMsg(pParse,
   83259         "Cannot add a REFERENCES column with non-NULL default value");
   83260     return;
   83261   }
   83262   if( pCol->notNull && !pDflt ){
   83263     sqlite3ErrorMsg(pParse,
   83264         "Cannot add a NOT NULL column with default value NULL");
   83265     return;
   83266   }
   83267 
   83268   /* Ensure the default expression is something that sqlite3ValueFromExpr()
   83269   ** can handle (i.e. not CURRENT_TIME etc.)
   83270   */
   83271   if( pDflt ){
   83272     sqlite3_value *pVal = 0;
   83273     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
   83274       db->mallocFailed = 1;
   83275       return;
   83276     }
   83277     if( !pVal ){
   83278       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   83279       return;
   83280     }
   83281     sqlite3ValueFree(pVal);
   83282   }
   83283 
   83284   /* Modify the CREATE TABLE statement. */
   83285   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   83286   if( zCol ){
   83287     char *zEnd = &zCol[pColDef->n-1];
   83288     int savedDbFlags = db->flags;
   83289     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
   83290       *zEnd-- = '\0';
   83291     }
   83292     db->flags |= SQLITE_PreferBuiltin;
   83293     sqlite3NestedParse(pParse,
   83294         "UPDATE \"%w\".%s SET "
   83295           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
   83296         "WHERE type = 'table' AND name = %Q",
   83297       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
   83298       zTab
   83299     );
   83300     sqlite3DbFree(db, zCol);
   83301     db->flags = savedDbFlags;
   83302   }
   83303 
   83304   /* If the default value of the new column is NULL, then set the file
   83305   ** format to 2. If the default value of the new column is not NULL,
   83306   ** the file format becomes 3.
   83307   */
   83308   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
   83309 
   83310   /* Reload the schema of the modified table. */
   83311   reloadTableSchema(pParse, pTab, pTab->zName);
   83312 }
   83313 
   83314 /*
   83315 ** This function is called by the parser after the table-name in
   83316 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
   83317 ** pSrc is the full-name of the table being altered.
   83318 **
   83319 ** This routine makes a (partial) copy of the Table structure
   83320 ** for the table being altered and sets Parse.pNewTable to point
   83321 ** to it. Routines called by the parser as the column definition
   83322 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
   83323 ** the copy. The copy of the Table structure is deleted by tokenize.c
   83324 ** after parsing is finished.
   83325 **
   83326 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
   83327 ** coding the "ALTER TABLE ... ADD" statement.
   83328 */
   83329 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   83330   Table *pNew;
   83331   Table *pTab;
   83332   Vdbe *v;
   83333   int iDb;
   83334   int i;
   83335   int nAlloc;
   83336   sqlite3 *db = pParse->db;
   83337 
   83338   /* Look up the table being altered. */
   83339   assert( pParse->pNewTable==0 );
   83340   assert( sqlite3BtreeHoldsAllMutexes(db) );
   83341   if( db->mallocFailed ) goto exit_begin_add_column;
   83342   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
   83343   if( !pTab ) goto exit_begin_add_column;
   83344 
   83345 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83346   if( IsVirtual(pTab) ){
   83347     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
   83348     goto exit_begin_add_column;
   83349   }
   83350 #endif
   83351 
   83352   /* Make sure this is not an attempt to ALTER a view. */
   83353   if( pTab->pSelect ){
   83354     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   83355     goto exit_begin_add_column;
   83356   }
   83357   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   83358     goto exit_begin_add_column;
   83359   }
   83360 
   83361   assert( pTab->addColOffset>0 );
   83362   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   83363 
   83364   /* Put a copy of the Table struct in Parse.pNewTable for the
   83365   ** sqlite3AddColumn() function and friends to modify.  But modify
   83366   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
   83367   ** prefix, we insure that the name will not collide with an existing
   83368   ** table because user table are not allowed to have the "sqlite_"
   83369   ** prefix on their name.
   83370   */
   83371   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
   83372   if( !pNew ) goto exit_begin_add_column;
   83373   pParse->pNewTable = pNew;
   83374   pNew->nRef = 1;
   83375   pNew->nCol = pTab->nCol;
   83376   assert( pNew->nCol>0 );
   83377   nAlloc = (((pNew->nCol-1)/8)*8)+8;
   83378   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
   83379   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
   83380   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
   83381   if( !pNew->aCol || !pNew->zName ){
   83382     db->mallocFailed = 1;
   83383     goto exit_begin_add_column;
   83384   }
   83385   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   83386   for(i=0; i<pNew->nCol; i++){
   83387     Column *pCol = &pNew->aCol[i];
   83388     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
   83389     pCol->zColl = 0;
   83390     pCol->zType = 0;
   83391     pCol->pDflt = 0;
   83392     pCol->zDflt = 0;
   83393   }
   83394   pNew->pSchema = db->aDb[iDb].pSchema;
   83395   pNew->addColOffset = pTab->addColOffset;
   83396   pNew->nRef = 1;
   83397 
   83398   /* Begin a transaction and increment the schema cookie.  */
   83399   sqlite3BeginWriteOperation(pParse, 0, iDb);
   83400   v = sqlite3GetVdbe(pParse);
   83401   if( !v ) goto exit_begin_add_column;
   83402   sqlite3ChangeCookie(pParse, iDb);
   83403 
   83404 exit_begin_add_column:
   83405   sqlite3SrcListDelete(db, pSrc);
   83406   return;
   83407 }
   83408 #endif  /* SQLITE_ALTER_TABLE */
   83409 
   83410 /************** End of alter.c ***********************************************/
   83411 /************** Begin file analyze.c *****************************************/
   83412 /*
   83413 ** 2005-07-08
   83414 **
   83415 ** The author disclaims copyright to this source code.  In place of
   83416 ** a legal notice, here is a blessing:
   83417 **
   83418 **    May you do good and not evil.
   83419 **    May you find forgiveness for yourself and forgive others.
   83420 **    May you share freely, never taking more than you give.
   83421 **
   83422 *************************************************************************
   83423 ** This file contains code associated with the ANALYZE command.
   83424 **
   83425 ** The ANALYZE command gather statistics about the content of tables
   83426 ** and indices.  These statistics are made available to the query planner
   83427 ** to help it make better decisions about how to perform queries.
   83428 **
   83429 ** The following system tables are or have been supported:
   83430 **
   83431 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
   83432 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
   83433 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
   83434 **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
   83435 **
   83436 ** Additional tables might be added in future releases of SQLite.
   83437 ** The sqlite_stat2 table is not created or used unless the SQLite version
   83438 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
   83439 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
   83440 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
   83441 ** created and used by SQLite versions 3.7.9 and later and with
   83442 ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
   83443 ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
   83444 ** version of sqlite_stat3 and is only available when compiled with
   83445 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
   83446 ** not possible to enable both STAT3 and STAT4 at the same time.  If they
   83447 ** are both enabled, then STAT4 takes precedence.
   83448 **
   83449 ** For most applications, sqlite_stat1 provides all the statisics required
   83450 ** for the query planner to make good choices.
   83451 **
   83452 ** Format of sqlite_stat1:
   83453 **
   83454 ** There is normally one row per index, with the index identified by the
   83455 ** name in the idx column.  The tbl column is the name of the table to
   83456 ** which the index belongs.  In each such row, the stat column will be
   83457 ** a string consisting of a list of integers.  The first integer in this
   83458 ** list is the number of rows in the index.  (This is the same as the
   83459 ** number of rows in the table, except for partial indices.)  The second
   83460 ** integer is the average number of rows in the index that have the same
   83461 ** value in the first column of the index.  The third integer is the average
   83462 ** number of rows in the index that have the same value for the first two
   83463 ** columns.  The N-th integer (for N>1) is the average number of rows in
   83464 ** the index which have the same value for the first N-1 columns.  For
   83465 ** a K-column index, there will be K+1 integers in the stat column.  If
   83466 ** the index is unique, then the last integer will be 1.
   83467 **
   83468 ** The list of integers in the stat column can optionally be followed
   83469 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
   83470 ** must be separated from the last integer by a single space.  If the
   83471 ** "unordered" keyword is present, then the query planner assumes that
   83472 ** the index is unordered and will not use the index for a range query.
   83473 **
   83474 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
   83475 ** column contains a single integer which is the (estimated) number of
   83476 ** rows in the table identified by sqlite_stat1.tbl.
   83477 **
   83478 ** Format of sqlite_stat2:
   83479 **
   83480 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
   83481 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
   83482 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
   83483 ** about the distribution of keys within an index.  The index is identified by
   83484 ** the "idx" column and the "tbl" column is the name of the table to which
   83485 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
   83486 ** table for each index.
   83487 **
   83488 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
   83489 ** inclusive are samples of the left-most key value in the index taken at
   83490 ** evenly spaced points along the index.  Let the number of samples be S
   83491 ** (10 in the standard build) and let C be the number of rows in the index.
   83492 ** Then the sampled rows are given by:
   83493 **
   83494 **     rownumber = (i*C*2 + C)/(S*2)
   83495 **
   83496 ** For i between 0 and S-1.  Conceptually, the index space is divided into
   83497 ** S uniform buckets and the samples are the middle row from each bucket.
   83498 **
   83499 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
   83500 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
   83501 ** writes the sqlite_stat2 table.  This version of SQLite only supports
   83502 ** sqlite_stat3.
   83503 **
   83504 ** Format for sqlite_stat3:
   83505 **
   83506 ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
   83507 ** sqlite_stat4 format will be described first.  Further information
   83508 ** about sqlite_stat3 follows the sqlite_stat4 description.
   83509 **
   83510 ** Format for sqlite_stat4:
   83511 **
   83512 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
   83513 ** to aid the query planner in choosing good indices based on the values
   83514 ** that indexed columns are compared against in the WHERE clauses of
   83515 ** queries.
   83516 **
   83517 ** The sqlite_stat4 table contains multiple entries for each index.
   83518 ** The idx column names the index and the tbl column is the table of the
   83519 ** index.  If the idx and tbl columns are the same, then the sample is
   83520 ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
   83521 ** binary encoding of a key from the index.  The nEq column is a
   83522 ** list of integers.  The first integer is the approximate number
   83523 ** of entries in the index whose left-most column exactly matches
   83524 ** the left-most column of the sample.  The second integer in nEq
   83525 ** is the approximate number of entries in the index where the
   83526 ** first two columns match the first two columns of the sample.
   83527 ** And so forth.  nLt is another list of integers that show the approximate
   83528 ** number of entries that are strictly less than the sample.  The first
   83529 ** integer in nLt contains the number of entries in the index where the
   83530 ** left-most column is less than the left-most column of the sample.
   83531 ** The K-th integer in the nLt entry is the number of index entries
   83532 ** where the first K columns are less than the first K columns of the
   83533 ** sample.  The nDLt column is like nLt except that it contains the
   83534 ** number of distinct entries in the index that are less than the
   83535 ** sample.
   83536 **
   83537 ** There can be an arbitrary number of sqlite_stat4 entries per index.
   83538 ** The ANALYZE command will typically generate sqlite_stat4 tables
   83539 ** that contain between 10 and 40 samples which are distributed across
   83540 ** the key space, though not uniformly, and which include samples with
   83541 ** large nEq values.
   83542 **
   83543 ** Format for sqlite_stat3 redux:
   83544 **
   83545 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
   83546 ** looks at the left-most column of the index.  The sqlite_stat3.sample
   83547 ** column contains the actual value of the left-most column instead
   83548 ** of a blob encoding of the complete index key as is found in
   83549 ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
   83550 ** all contain just a single integer which is the same as the first
   83551 ** integer in the equivalent columns in sqlite_stat4.
   83552 */
   83553 #ifndef SQLITE_OMIT_ANALYZE
   83554 
   83555 #if defined(SQLITE_ENABLE_STAT4)
   83556 # define IsStat4     1
   83557 # define IsStat3     0
   83558 #elif defined(SQLITE_ENABLE_STAT3)
   83559 # define IsStat4     0
   83560 # define IsStat3     1
   83561 #else
   83562 # define IsStat4     0
   83563 # define IsStat3     0
   83564 # undef SQLITE_STAT4_SAMPLES
   83565 # define SQLITE_STAT4_SAMPLES 1
   83566 #endif
   83567 #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
   83568 
   83569 /*
   83570 ** This routine generates code that opens the sqlite_statN tables.
   83571 ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
   83572 ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
   83573 ** appropriate compile-time options are provided.
   83574 **
   83575 ** If the sqlite_statN tables do not previously exist, it is created.
   83576 **
   83577 ** Argument zWhere may be a pointer to a buffer containing a table name,
   83578 ** or it may be a NULL pointer. If it is not NULL, then all entries in
   83579 ** the sqlite_statN tables associated with the named table are deleted.
   83580 ** If zWhere==0, then code is generated to delete all stat table entries.
   83581 */
   83582 static void openStatTable(
   83583   Parse *pParse,          /* Parsing context */
   83584   int iDb,                /* The database we are looking in */
   83585   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
   83586   const char *zWhere,     /* Delete entries for this table or index */
   83587   const char *zWhereType  /* Either "tbl" or "idx" */
   83588 ){
   83589   static const struct {
   83590     const char *zName;
   83591     const char *zCols;
   83592   } aTable[] = {
   83593     { "sqlite_stat1", "tbl,idx,stat" },
   83594 #if defined(SQLITE_ENABLE_STAT4)
   83595     { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
   83596     { "sqlite_stat3", 0 },
   83597 #elif defined(SQLITE_ENABLE_STAT3)
   83598     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
   83599     { "sqlite_stat4", 0 },
   83600 #else
   83601     { "sqlite_stat3", 0 },
   83602     { "sqlite_stat4", 0 },
   83603 #endif
   83604   };
   83605   int i;
   83606   sqlite3 *db = pParse->db;
   83607   Db *pDb;
   83608   Vdbe *v = sqlite3GetVdbe(pParse);
   83609   int aRoot[ArraySize(aTable)];
   83610   u8 aCreateTbl[ArraySize(aTable)];
   83611 
   83612   if( v==0 ) return;
   83613   assert( sqlite3BtreeHoldsAllMutexes(db) );
   83614   assert( sqlite3VdbeDb(v)==db );
   83615   pDb = &db->aDb[iDb];
   83616 
   83617   /* Create new statistic tables if they do not exist, or clear them
   83618   ** if they do already exist.
   83619   */
   83620   for(i=0; i<ArraySize(aTable); i++){
   83621     const char *zTab = aTable[i].zName;
   83622     Table *pStat;
   83623     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
   83624       if( aTable[i].zCols ){
   83625         /* The sqlite_statN table does not exist. Create it. Note that a
   83626         ** side-effect of the CREATE TABLE statement is to leave the rootpage
   83627         ** of the new table in register pParse->regRoot. This is important
   83628         ** because the OpenWrite opcode below will be needing it. */
   83629         sqlite3NestedParse(pParse,
   83630             "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
   83631         );
   83632         aRoot[i] = pParse->regRoot;
   83633         aCreateTbl[i] = OPFLAG_P2ISREG;
   83634       }
   83635     }else{
   83636       /* The table already exists. If zWhere is not NULL, delete all entries
   83637       ** associated with the table zWhere. If zWhere is NULL, delete the
   83638       ** entire contents of the table. */
   83639       aRoot[i] = pStat->tnum;
   83640       aCreateTbl[i] = 0;
   83641       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
   83642       if( zWhere ){
   83643         sqlite3NestedParse(pParse,
   83644            "DELETE FROM %Q.%s WHERE %s=%Q",
   83645            pDb->zName, zTab, zWhereType, zWhere
   83646         );
   83647       }else{
   83648         /* The sqlite_stat[134] table already exists.  Delete all rows. */
   83649         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
   83650       }
   83651     }
   83652   }
   83653 
   83654   /* Open the sqlite_stat[134] tables for writing. */
   83655   for(i=0; aTable[i].zCols; i++){
   83656     assert( i<ArraySize(aTable) );
   83657     sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
   83658     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
   83659     VdbeComment((v, aTable[i].zName));
   83660   }
   83661 }
   83662 
   83663 /*
   83664 ** Recommended number of samples for sqlite_stat4
   83665 */
   83666 #ifndef SQLITE_STAT4_SAMPLES
   83667 # define SQLITE_STAT4_SAMPLES 24
   83668 #endif
   83669 
   83670 /*
   83671 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
   83672 ** share an instance of the following structure to hold their state
   83673 ** information.
   83674 */
   83675 typedef struct Stat4Accum Stat4Accum;
   83676 typedef struct Stat4Sample Stat4Sample;
   83677 struct Stat4Sample {
   83678   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
   83679   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
   83680 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83681   tRowcnt *anLt;                  /* sqlite_stat4.nLt */
   83682   union {
   83683     i64 iRowid;                     /* Rowid in main table of the key */
   83684     u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
   83685   } u;
   83686   u32 nRowid;                     /* Sizeof aRowid[] */
   83687   u8 isPSample;                   /* True if a periodic sample */
   83688   int iCol;                       /* If !isPSample, the reason for inclusion */
   83689   u32 iHash;                      /* Tiebreaker hash */
   83690 #endif
   83691 };
   83692 struct Stat4Accum {
   83693   tRowcnt nRow;             /* Number of rows in the entire table */
   83694   tRowcnt nPSample;         /* How often to do a periodic sample */
   83695   int nCol;                 /* Number of columns in index + pk/rowid */
   83696   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
   83697   int mxSample;             /* Maximum number of samples to accumulate */
   83698   Stat4Sample current;      /* Current row as a Stat4Sample */
   83699   u32 iPrn;                 /* Pseudo-random number used for sampling */
   83700   Stat4Sample *aBest;       /* Array of nCol best samples */
   83701   int iMin;                 /* Index in a[] of entry with minimum score */
   83702   int nSample;              /* Current number of samples */
   83703   int iGet;                 /* Index of current sample accessed by stat_get() */
   83704   Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
   83705   sqlite3 *db;              /* Database connection, for malloc() */
   83706 };
   83707 
   83708 /* Reclaim memory used by a Stat4Sample
   83709 */
   83710 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83711 static void sampleClear(sqlite3 *db, Stat4Sample *p){
   83712   assert( db!=0 );
   83713   if( p->nRowid ){
   83714     sqlite3DbFree(db, p->u.aRowid);
   83715     p->nRowid = 0;
   83716   }
   83717 }
   83718 #endif
   83719 
   83720 /* Initialize the BLOB value of a ROWID
   83721 */
   83722 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83723 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
   83724   assert( db!=0 );
   83725   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   83726   p->u.aRowid = sqlite3DbMallocRaw(db, n);
   83727   if( p->u.aRowid ){
   83728     p->nRowid = n;
   83729     memcpy(p->u.aRowid, pData, n);
   83730   }else{
   83731     p->nRowid = 0;
   83732   }
   83733 }
   83734 #endif
   83735 
   83736 /* Initialize the INTEGER value of a ROWID.
   83737 */
   83738 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83739 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
   83740   assert( db!=0 );
   83741   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   83742   p->nRowid = 0;
   83743   p->u.iRowid = iRowid;
   83744 }
   83745 #endif
   83746 
   83747 
   83748 /*
   83749 ** Copy the contents of object (*pFrom) into (*pTo).
   83750 */
   83751 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83752 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
   83753   pTo->isPSample = pFrom->isPSample;
   83754   pTo->iCol = pFrom->iCol;
   83755   pTo->iHash = pFrom->iHash;
   83756   memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
   83757   memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
   83758   memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
   83759   if( pFrom->nRowid ){
   83760     sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
   83761   }else{
   83762     sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
   83763   }
   83764 }
   83765 #endif
   83766 
   83767 /*
   83768 ** Reclaim all memory of a Stat4Accum structure.
   83769 */
   83770 static void stat4Destructor(void *pOld){
   83771   Stat4Accum *p = (Stat4Accum*)pOld;
   83772 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83773   int i;
   83774   for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
   83775   for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
   83776   sampleClear(p->db, &p->current);
   83777 #endif
   83778   sqlite3DbFree(p->db, p);
   83779 }
   83780 
   83781 /*
   83782 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
   83783 ** are:
   83784 **     N:    The number of columns in the index including the rowid/pk (note 1)
   83785 **     K:    The number of columns in the index excluding the rowid/pk.
   83786 **     C:    The number of rows in the index (note 2)
   83787 **
   83788 ** Note 1:  In the special case of the covering index that implements a
   83789 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
   83790 ** total number of columns in the table.
   83791 **
   83792 ** Note 2:  C is only used for STAT3 and STAT4.
   83793 **
   83794 ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
   83795 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
   83796 ** PRIMARY KEY of the table.  The covering index that implements the
   83797 ** original WITHOUT ROWID table as N==K as a special case.
   83798 **
   83799 ** This routine allocates the Stat4Accum object in heap memory. The return
   83800 ** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
   83801 ** the size of the blob is sizeof(void*) bytes).
   83802 */
   83803 static void statInit(
   83804   sqlite3_context *context,
   83805   int argc,
   83806   sqlite3_value **argv
   83807 ){
   83808   Stat4Accum *p;
   83809   int nCol;                       /* Number of columns in index being sampled */
   83810   int nKeyCol;                    /* Number of key columns */
   83811   int nColUp;                     /* nCol rounded up for alignment */
   83812   int n;                          /* Bytes of space to allocate */
   83813   sqlite3 *db;                    /* Database connection */
   83814 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83815   int mxSample = SQLITE_STAT4_SAMPLES;
   83816 #endif
   83817 
   83818   /* Decode the three function arguments */
   83819   UNUSED_PARAMETER(argc);
   83820   nCol = sqlite3_value_int(argv[0]);
   83821   assert( nCol>0 );
   83822   nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
   83823   nKeyCol = sqlite3_value_int(argv[1]);
   83824   assert( nKeyCol<=nCol );
   83825   assert( nKeyCol>0 );
   83826 
   83827   /* Allocate the space required for the Stat4Accum object */
   83828   n = sizeof(*p)
   83829     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
   83830     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
   83831 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83832     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
   83833     + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
   83834     + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
   83835 #endif
   83836   ;
   83837   db = sqlite3_context_db_handle(context);
   83838   p = sqlite3DbMallocZero(db, n);
   83839   if( p==0 ){
   83840     sqlite3_result_error_nomem(context);
   83841     return;
   83842   }
   83843 
   83844   p->db = db;
   83845   p->nRow = 0;
   83846   p->nCol = nCol;
   83847   p->nKeyCol = nKeyCol;
   83848   p->current.anDLt = (tRowcnt*)&p[1];
   83849   p->current.anEq = &p->current.anDLt[nColUp];
   83850 
   83851 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83852   {
   83853     u8 *pSpace;                     /* Allocated space not yet assigned */
   83854     int i;                          /* Used to iterate through p->aSample[] */
   83855 
   83856     p->iGet = -1;
   83857     p->mxSample = mxSample;
   83858     p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
   83859     p->current.anLt = &p->current.anEq[nColUp];
   83860     p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[2])*0xd0944565;
   83861 
   83862     /* Set up the Stat4Accum.a[] and aBest[] arrays */
   83863     p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
   83864     p->aBest = &p->a[mxSample];
   83865     pSpace = (u8*)(&p->a[mxSample+nCol]);
   83866     for(i=0; i<(mxSample+nCol); i++){
   83867       p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   83868       p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   83869       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   83870     }
   83871     assert( (pSpace - (u8*)p)==n );
   83872 
   83873     for(i=0; i<nCol; i++){
   83874       p->aBest[i].iCol = i;
   83875     }
   83876   }
   83877 #endif
   83878 
   83879   /* Return a pointer to the allocated object to the caller */
   83880   sqlite3_result_blob(context, p, sizeof(p), stat4Destructor);
   83881 }
   83882 static const FuncDef statInitFuncdef = {
   83883   2+IsStat34,      /* nArg */
   83884   SQLITE_UTF8,     /* funcFlags */
   83885   0,               /* pUserData */
   83886   0,               /* pNext */
   83887   statInit,        /* xFunc */
   83888   0,               /* xStep */
   83889   0,               /* xFinalize */
   83890   "stat_init",     /* zName */
   83891   0,               /* pHash */
   83892   0                /* pDestructor */
   83893 };
   83894 
   83895 #ifdef SQLITE_ENABLE_STAT4
   83896 /*
   83897 ** pNew and pOld are both candidate non-periodic samples selected for
   83898 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
   83899 ** considering only any trailing columns and the sample hash value, this
   83900 ** function returns true if sample pNew is to be preferred over pOld.
   83901 ** In other words, if we assume that the cardinalities of the selected
   83902 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
   83903 **
   83904 ** This function assumes that for each argument sample, the contents of
   83905 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
   83906 */
   83907 static int sampleIsBetterPost(
   83908   Stat4Accum *pAccum,
   83909   Stat4Sample *pNew,
   83910   Stat4Sample *pOld
   83911 ){
   83912   int nCol = pAccum->nCol;
   83913   int i;
   83914   assert( pNew->iCol==pOld->iCol );
   83915   for(i=pNew->iCol+1; i<nCol; i++){
   83916     if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
   83917     if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
   83918   }
   83919   if( pNew->iHash>pOld->iHash ) return 1;
   83920   return 0;
   83921 }
   83922 #endif
   83923 
   83924 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   83925 /*
   83926 ** Return true if pNew is to be preferred over pOld.
   83927 **
   83928 ** This function assumes that for each argument sample, the contents of
   83929 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
   83930 */
   83931 static int sampleIsBetter(
   83932   Stat4Accum *pAccum,
   83933   Stat4Sample *pNew,
   83934   Stat4Sample *pOld
   83935 ){
   83936   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
   83937   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
   83938 
   83939   assert( pOld->isPSample==0 && pNew->isPSample==0 );
   83940   assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
   83941 
   83942   if( (nEqNew>nEqOld) ) return 1;
   83943 #ifdef SQLITE_ENABLE_STAT4
   83944   if( nEqNew==nEqOld ){
   83945     if( pNew->iCol<pOld->iCol ) return 1;
   83946     return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
   83947   }
   83948   return 0;
   83949 #else
   83950   return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
   83951 #endif
   83952 }
   83953 
   83954 /*
   83955 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
   83956 ** remove the least desirable sample from p->a[] to make room.
   83957 */
   83958 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
   83959   Stat4Sample *pSample = 0;
   83960   int i;
   83961 
   83962   assert( IsStat4 || nEqZero==0 );
   83963 
   83964 #ifdef SQLITE_ENABLE_STAT4
   83965   if( pNew->isPSample==0 ){
   83966     Stat4Sample *pUpgrade = 0;
   83967     assert( pNew->anEq[pNew->iCol]>0 );
   83968 
   83969     /* This sample is being added because the prefix that ends in column
   83970     ** iCol occurs many times in the table. However, if we have already
   83971     ** added a sample that shares this prefix, there is no need to add
   83972     ** this one. Instead, upgrade the priority of the highest priority
   83973     ** existing sample that shares this prefix.  */
   83974     for(i=p->nSample-1; i>=0; i--){
   83975       Stat4Sample *pOld = &p->a[i];
   83976       if( pOld->anEq[pNew->iCol]==0 ){
   83977         if( pOld->isPSample ) return;
   83978         assert( pOld->iCol>pNew->iCol );
   83979         assert( sampleIsBetter(p, pNew, pOld) );
   83980         if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
   83981           pUpgrade = pOld;
   83982         }
   83983       }
   83984     }
   83985     if( pUpgrade ){
   83986       pUpgrade->iCol = pNew->iCol;
   83987       pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
   83988       goto find_new_min;
   83989     }
   83990   }
   83991 #endif
   83992 
   83993   /* If necessary, remove sample iMin to make room for the new sample. */
   83994   if( p->nSample>=p->mxSample ){
   83995     Stat4Sample *pMin = &p->a[p->iMin];
   83996     tRowcnt *anEq = pMin->anEq;
   83997     tRowcnt *anLt = pMin->anLt;
   83998     tRowcnt *anDLt = pMin->anDLt;
   83999     sampleClear(p->db, pMin);
   84000     memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
   84001     pSample = &p->a[p->nSample-1];
   84002     pSample->nRowid = 0;
   84003     pSample->anEq = anEq;
   84004     pSample->anDLt = anDLt;
   84005     pSample->anLt = anLt;
   84006     p->nSample = p->mxSample-1;
   84007   }
   84008 
   84009   /* The "rows less-than" for the rowid column must be greater than that
   84010   ** for the last sample in the p->a[] array. Otherwise, the samples would
   84011   ** be out of order. */
   84012 #ifdef SQLITE_ENABLE_STAT4
   84013   assert( p->nSample==0
   84014        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
   84015 #endif
   84016 
   84017   /* Insert the new sample */
   84018   pSample = &p->a[p->nSample];
   84019   sampleCopy(p, pSample, pNew);
   84020   p->nSample++;
   84021 
   84022   /* Zero the first nEqZero entries in the anEq[] array. */
   84023   memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
   84024 
   84025 #ifdef SQLITE_ENABLE_STAT4
   84026  find_new_min:
   84027 #endif
   84028   if( p->nSample>=p->mxSample ){
   84029     int iMin = -1;
   84030     for(i=0; i<p->mxSample; i++){
   84031       if( p->a[i].isPSample ) continue;
   84032       if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
   84033         iMin = i;
   84034       }
   84035     }
   84036     assert( iMin>=0 );
   84037     p->iMin = iMin;
   84038   }
   84039 }
   84040 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   84041 
   84042 /*
   84043 ** Field iChng of the index being scanned has changed. So at this point
   84044 ** p->current contains a sample that reflects the previous row of the
   84045 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
   84046 ** correct at this point.
   84047 */
   84048 static void samplePushPrevious(Stat4Accum *p, int iChng){
   84049 #ifdef SQLITE_ENABLE_STAT4
   84050   int i;
   84051 
   84052   /* Check if any samples from the aBest[] array should be pushed
   84053   ** into IndexSample.a[] at this point.  */
   84054   for(i=(p->nCol-2); i>=iChng; i--){
   84055     Stat4Sample *pBest = &p->aBest[i];
   84056     pBest->anEq[i] = p->current.anEq[i];
   84057     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
   84058       sampleInsert(p, pBest, i);
   84059     }
   84060   }
   84061 
   84062   /* Update the anEq[] fields of any samples already collected. */
   84063   for(i=p->nSample-1; i>=0; i--){
   84064     int j;
   84065     for(j=iChng; j<p->nCol; j++){
   84066       if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
   84067     }
   84068   }
   84069 #endif
   84070 
   84071 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
   84072   if( iChng==0 ){
   84073     tRowcnt nLt = p->current.anLt[0];
   84074     tRowcnt nEq = p->current.anEq[0];
   84075 
   84076     /* Check if this is to be a periodic sample. If so, add it. */
   84077     if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
   84078       p->current.isPSample = 1;
   84079       sampleInsert(p, &p->current, 0);
   84080       p->current.isPSample = 0;
   84081     }else
   84082 
   84083     /* Or if it is a non-periodic sample. Add it in this case too. */
   84084     if( p->nSample<p->mxSample
   84085      || sampleIsBetter(p, &p->current, &p->a[p->iMin])
   84086     ){
   84087       sampleInsert(p, &p->current, 0);
   84088     }
   84089   }
   84090 #endif
   84091 
   84092 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
   84093   UNUSED_PARAMETER( p );
   84094   UNUSED_PARAMETER( iChng );
   84095 #endif
   84096 }
   84097 
   84098 /*
   84099 ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
   84100 ** Arguments:
   84101 **
   84102 **    P     Pointer to the Stat4Accum object created by stat_init()
   84103 **    C     Index of left-most column to differ from previous row
   84104 **    R     Rowid for the current row.  Might be a key record for
   84105 **          WITHOUT ROWID tables.
   84106 **
   84107 ** This SQL function always returns NULL.  It's purpose it to accumulate
   84108 ** statistical data and/or samples in the Stat4Accum object about the
   84109 ** index being analyzed.  The stat_get() SQL function will later be used to
   84110 ** extract relevant information for constructing the sqlite_statN tables.
   84111 **
   84112 ** The R parameter is only used for STAT3 and STAT4
   84113 */
   84114 static void statPush(
   84115   sqlite3_context *context,
   84116   int argc,
   84117   sqlite3_value **argv
   84118 ){
   84119   int i;
   84120 
   84121   /* The three function arguments */
   84122   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
   84123   int iChng = sqlite3_value_int(argv[1]);
   84124 
   84125   UNUSED_PARAMETER( argc );
   84126   UNUSED_PARAMETER( context );
   84127   assert( p->nCol>0 );
   84128   assert( iChng<p->nCol );
   84129 
   84130   if( p->nRow==0 ){
   84131     /* This is the first call to this function. Do initialization. */
   84132     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
   84133   }else{
   84134     /* Second and subsequent calls get processed here */
   84135     samplePushPrevious(p, iChng);
   84136 
   84137     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
   84138     ** to the current row of the index. */
   84139     for(i=0; i<iChng; i++){
   84140       p->current.anEq[i]++;
   84141     }
   84142     for(i=iChng; i<p->nCol; i++){
   84143       p->current.anDLt[i]++;
   84144 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84145       p->current.anLt[i] += p->current.anEq[i];
   84146 #endif
   84147       p->current.anEq[i] = 1;
   84148     }
   84149   }
   84150   p->nRow++;
   84151 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84152   if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
   84153     sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
   84154   }else{
   84155     sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
   84156                                        sqlite3_value_blob(argv[2]));
   84157   }
   84158   p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
   84159 #endif
   84160 
   84161 #ifdef SQLITE_ENABLE_STAT4
   84162   {
   84163     tRowcnt nLt = p->current.anLt[p->nCol-1];
   84164 
   84165     /* Check if this is to be a periodic sample. If so, add it. */
   84166     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
   84167       p->current.isPSample = 1;
   84168       p->current.iCol = 0;
   84169       sampleInsert(p, &p->current, p->nCol-1);
   84170       p->current.isPSample = 0;
   84171     }
   84172 
   84173     /* Update the aBest[] array. */
   84174     for(i=0; i<(p->nCol-1); i++){
   84175       p->current.iCol = i;
   84176       if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
   84177         sampleCopy(p, &p->aBest[i], &p->current);
   84178       }
   84179     }
   84180   }
   84181 #endif
   84182 }
   84183 static const FuncDef statPushFuncdef = {
   84184   2+IsStat34,      /* nArg */
   84185   SQLITE_UTF8,     /* funcFlags */
   84186   0,               /* pUserData */
   84187   0,               /* pNext */
   84188   statPush,        /* xFunc */
   84189   0,               /* xStep */
   84190   0,               /* xFinalize */
   84191   "stat_push",     /* zName */
   84192   0,               /* pHash */
   84193   0                /* pDestructor */
   84194 };
   84195 
   84196 #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
   84197 #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
   84198 #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
   84199 #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
   84200 #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
   84201 
   84202 /*
   84203 ** Implementation of the stat_get(P,J) SQL function.  This routine is
   84204 ** used to query statistical information that has been gathered into
   84205 ** the Stat4Accum object by prior calls to stat_push().  The P parameter
   84206 ** is a BLOB which is decoded into a pointer to the Stat4Accum objects.
   84207 ** The content to returned is determined by the parameter J
   84208 ** which is one of the STAT_GET_xxxx values defined above.
   84209 **
   84210 ** If neither STAT3 nor STAT4 are enabled, then J is always
   84211 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
   84212 ** a one-parameter function, stat_get(P), that always returns the
   84213 ** stat1 table entry information.
   84214 */
   84215 static void statGet(
   84216   sqlite3_context *context,
   84217   int argc,
   84218   sqlite3_value **argv
   84219 ){
   84220   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
   84221 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84222   /* STAT3 and STAT4 have a parameter on this routine. */
   84223   int eCall = sqlite3_value_int(argv[1]);
   84224   assert( argc==2 );
   84225   assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
   84226        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
   84227        || eCall==STAT_GET_NDLT
   84228   );
   84229   if( eCall==STAT_GET_STAT1 )
   84230 #else
   84231   assert( argc==1 );
   84232 #endif
   84233   {
   84234     /* Return the value to store in the "stat" column of the sqlite_stat1
   84235     ** table for this index.
   84236     **
   84237     ** The value is a string composed of a list of integers describing
   84238     ** the index. The first integer in the list is the total number of
   84239     ** entries in the index. There is one additional integer in the list
   84240     ** for each indexed column. This additional integer is an estimate of
   84241     ** the number of rows matched by a stabbing query on the index using
   84242     ** a key with the corresponding number of fields. In other words,
   84243     ** if the index is on columns (a,b) and the sqlite_stat1 value is
   84244     ** "100 10 2", then SQLite estimates that:
   84245     **
   84246     **   * the index contains 100 rows,
   84247     **   * "WHERE a=?" matches 10 rows, and
   84248     **   * "WHERE a=? AND b=?" matches 2 rows.
   84249     **
   84250     ** If D is the count of distinct values and K is the total number of
   84251     ** rows, then each estimate is computed as:
   84252     **
   84253     **        I = (K+D-1)/D
   84254     */
   84255     char *z;
   84256     int i;
   84257 
   84258     char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
   84259     if( zRet==0 ){
   84260       sqlite3_result_error_nomem(context);
   84261       return;
   84262     }
   84263 
   84264     sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
   84265     z = zRet + sqlite3Strlen30(zRet);
   84266     for(i=0; i<p->nKeyCol; i++){
   84267       u64 nDistinct = p->current.anDLt[i] + 1;
   84268       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
   84269       sqlite3_snprintf(24, z, " %llu", iVal);
   84270       z += sqlite3Strlen30(z);
   84271       assert( p->current.anEq[i] );
   84272     }
   84273     assert( z[0]=='\0' && z>zRet );
   84274 
   84275     sqlite3_result_text(context, zRet, -1, sqlite3_free);
   84276   }
   84277 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84278   else if( eCall==STAT_GET_ROWID ){
   84279     if( p->iGet<0 ){
   84280       samplePushPrevious(p, 0);
   84281       p->iGet = 0;
   84282     }
   84283     if( p->iGet<p->nSample ){
   84284       Stat4Sample *pS = p->a + p->iGet;
   84285       if( pS->nRowid==0 ){
   84286         sqlite3_result_int64(context, pS->u.iRowid);
   84287       }else{
   84288         sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
   84289                             SQLITE_TRANSIENT);
   84290       }
   84291     }
   84292   }else{
   84293     tRowcnt *aCnt = 0;
   84294 
   84295     assert( p->iGet<p->nSample );
   84296     switch( eCall ){
   84297       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
   84298       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
   84299       default: {
   84300         aCnt = p->a[p->iGet].anDLt;
   84301         p->iGet++;
   84302         break;
   84303       }
   84304     }
   84305 
   84306     if( IsStat3 ){
   84307       sqlite3_result_int64(context, (i64)aCnt[0]);
   84308     }else{
   84309       char *zRet = sqlite3MallocZero(p->nCol * 25);
   84310       if( zRet==0 ){
   84311         sqlite3_result_error_nomem(context);
   84312       }else{
   84313         int i;
   84314         char *z = zRet;
   84315         for(i=0; i<p->nCol; i++){
   84316           sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
   84317           z += sqlite3Strlen30(z);
   84318         }
   84319         assert( z[0]=='\0' && z>zRet );
   84320         z[-1] = '\0';
   84321         sqlite3_result_text(context, zRet, -1, sqlite3_free);
   84322       }
   84323     }
   84324   }
   84325 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   84326 #ifndef SQLITE_DEBUG
   84327   UNUSED_PARAMETER( argc );
   84328 #endif
   84329 }
   84330 static const FuncDef statGetFuncdef = {
   84331   1+IsStat34,      /* nArg */
   84332   SQLITE_UTF8,     /* funcFlags */
   84333   0,               /* pUserData */
   84334   0,               /* pNext */
   84335   statGet,         /* xFunc */
   84336   0,               /* xStep */
   84337   0,               /* xFinalize */
   84338   "stat_get",      /* zName */
   84339   0,               /* pHash */
   84340   0                /* pDestructor */
   84341 };
   84342 
   84343 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
   84344   assert( regOut!=regStat4 && regOut!=regStat4+1 );
   84345 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84346   sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
   84347 #elif SQLITE_DEBUG
   84348   assert( iParam==STAT_GET_STAT1 );
   84349 #else
   84350   UNUSED_PARAMETER( iParam );
   84351 #endif
   84352   sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
   84353   sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
   84354   sqlite3VdbeChangeP5(v, 1 + IsStat34);
   84355 }
   84356 
   84357 /*
   84358 ** Generate code to do an analysis of all indices associated with
   84359 ** a single table.
   84360 */
   84361 static void analyzeOneTable(
   84362   Parse *pParse,   /* Parser context */
   84363   Table *pTab,     /* Table whose indices are to be analyzed */
   84364   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
   84365   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
   84366   int iMem,        /* Available memory locations begin here */
   84367   int iTab         /* Next available cursor */
   84368 ){
   84369   sqlite3 *db = pParse->db;    /* Database handle */
   84370   Index *pIdx;                 /* An index to being analyzed */
   84371   int iIdxCur;                 /* Cursor open on index being analyzed */
   84372   int iTabCur;                 /* Table cursor */
   84373   Vdbe *v;                     /* The virtual machine being built up */
   84374   int i;                       /* Loop counter */
   84375   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
   84376   int iDb;                     /* Index of database containing pTab */
   84377   u8 needTableCnt = 1;         /* True to count the table */
   84378   int regNewRowid = iMem++;    /* Rowid for the inserted record */
   84379   int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
   84380   int regChng = iMem++;        /* Index of changed index field */
   84381 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84382   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
   84383 #endif
   84384   int regTemp = iMem++;        /* Temporary use register */
   84385   int regTabname = iMem++;     /* Register containing table name */
   84386   int regIdxname = iMem++;     /* Register containing index name */
   84387   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
   84388   int regPrev = iMem;          /* MUST BE LAST (see below) */
   84389 
   84390   pParse->nMem = MAX(pParse->nMem, iMem);
   84391   v = sqlite3GetVdbe(pParse);
   84392   if( v==0 || NEVER(pTab==0) ){
   84393     return;
   84394   }
   84395   if( pTab->tnum==0 ){
   84396     /* Do not gather statistics on views or virtual tables */
   84397     return;
   84398   }
   84399   if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
   84400     /* Do not gather statistics on system tables */
   84401     return;
   84402   }
   84403   assert( sqlite3BtreeHoldsAllMutexes(db) );
   84404   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   84405   assert( iDb>=0 );
   84406   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   84407 #ifndef SQLITE_OMIT_AUTHORIZATION
   84408   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
   84409       db->aDb[iDb].zName ) ){
   84410     return;
   84411   }
   84412 #endif
   84413 
   84414   /* Establish a read-lock on the table at the shared-cache level.
   84415   ** Open a read-only cursor on the table. Also allocate a cursor number
   84416   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
   84417   ** this time though.  */
   84418   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   84419   iTabCur = iTab++;
   84420   iIdxCur = iTab++;
   84421   pParse->nTab = MAX(pParse->nTab, iTab);
   84422   sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
   84423   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
   84424 
   84425   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   84426     int nCol;                     /* Number of columns in pIdx. "N" */
   84427     int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
   84428     int addrNextRow;              /* Address of "next_row:" */
   84429     const char *zIdxName;         /* Name of the index */
   84430     int nColTest;                 /* Number of columns to test for changes */
   84431 
   84432     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
   84433     if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
   84434     if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
   84435       nCol = pIdx->nKeyCol;
   84436       zIdxName = pTab->zName;
   84437       nColTest = nCol - 1;
   84438     }else{
   84439       nCol = pIdx->nColumn;
   84440       zIdxName = pIdx->zName;
   84441       nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
   84442     }
   84443 
   84444     /* Populate the register containing the index name. */
   84445     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
   84446     VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
   84447 
   84448     /*
   84449     ** Pseudo-code for loop that calls stat_push():
   84450     **
   84451     **   Rewind csr
   84452     **   if eof(csr) goto end_of_scan;
   84453     **   regChng = 0
   84454     **   goto chng_addr_0;
   84455     **
   84456     **  next_row:
   84457     **   regChng = 0
   84458     **   if( idx(0) != regPrev(0) ) goto chng_addr_0
   84459     **   regChng = 1
   84460     **   if( idx(1) != regPrev(1) ) goto chng_addr_1
   84461     **   ...
   84462     **   regChng = N
   84463     **   goto chng_addr_N
   84464     **
   84465     **  chng_addr_0:
   84466     **   regPrev(0) = idx(0)
   84467     **  chng_addr_1:
   84468     **   regPrev(1) = idx(1)
   84469     **  ...
   84470     **
   84471     **  endDistinctTest:
   84472     **   regRowid = idx(rowid)
   84473     **   stat_push(P, regChng, regRowid)
   84474     **   Next csr
   84475     **   if !eof(csr) goto next_row;
   84476     **
   84477     **  end_of_scan:
   84478     */
   84479 
   84480     /* Make sure there are enough memory cells allocated to accommodate
   84481     ** the regPrev array and a trailing rowid (the rowid slot is required
   84482     ** when building a record to insert into the sample column of
   84483     ** the sqlite_stat4 table.  */
   84484     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
   84485 
   84486     /* Open a read-only cursor on the index being analyzed. */
   84487     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
   84488     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
   84489     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   84490     VdbeComment((v, "%s", pIdx->zName));
   84491 
   84492     /* Invoke the stat_init() function. The arguments are:
   84493     **
   84494     **    (1) the number of columns in the index including the rowid
   84495     **        (or for a WITHOUT ROWID table, the number of PK columns),
   84496     **    (2) the number of columns in the key without the rowid/pk
   84497     **    (3) the number of rows in the index,
   84498     **
   84499     **
   84500     ** The third argument is only used for STAT3 and STAT4
   84501     */
   84502 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84503     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
   84504 #endif
   84505     sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
   84506     sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
   84507     sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
   84508     sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
   84509     sqlite3VdbeChangeP5(v, 2+IsStat34);
   84510 
   84511     /* Implementation of the following:
   84512     **
   84513     **   Rewind csr
   84514     **   if eof(csr) goto end_of_scan;
   84515     **   regChng = 0
   84516     **   goto next_push_0;
   84517     **
   84518     */
   84519     addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
   84520     VdbeCoverage(v);
   84521     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
   84522     addrNextRow = sqlite3VdbeCurrentAddr(v);
   84523 
   84524     if( nColTest>0 ){
   84525       int endDistinctTest = sqlite3VdbeMakeLabel(v);
   84526       int *aGotoChng;               /* Array of jump instruction addresses */
   84527       aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
   84528       if( aGotoChng==0 ) continue;
   84529 
   84530       /*
   84531       **  next_row:
   84532       **   regChng = 0
   84533       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
   84534       **   regChng = 1
   84535       **   if( idx(1) != regPrev(1) ) goto chng_addr_1
   84536       **   ...
   84537       **   regChng = N
   84538       **   goto endDistinctTest
   84539       */
   84540       sqlite3VdbeAddOp0(v, OP_Goto);
   84541       addrNextRow = sqlite3VdbeCurrentAddr(v);
   84542       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
   84543         /* For a single-column UNIQUE index, once we have found a non-NULL
   84544         ** row, we know that all the rest will be distinct, so skip
   84545         ** subsequent distinctness tests. */
   84546         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
   84547         VdbeCoverage(v);
   84548       }
   84549       for(i=0; i<nColTest; i++){
   84550         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
   84551         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
   84552         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
   84553         aGotoChng[i] =
   84554         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
   84555         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   84556         VdbeCoverage(v);
   84557       }
   84558       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
   84559       sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
   84560 
   84561 
   84562       /*
   84563       **  chng_addr_0:
   84564       **   regPrev(0) = idx(0)
   84565       **  chng_addr_1:
   84566       **   regPrev(1) = idx(1)
   84567       **  ...
   84568       */
   84569       sqlite3VdbeJumpHere(v, addrNextRow-1);
   84570       for(i=0; i<nColTest; i++){
   84571         sqlite3VdbeJumpHere(v, aGotoChng[i]);
   84572         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
   84573       }
   84574       sqlite3VdbeResolveLabel(v, endDistinctTest);
   84575       sqlite3DbFree(db, aGotoChng);
   84576     }
   84577 
   84578     /*
   84579     **  chng_addr_N:
   84580     **   regRowid = idx(rowid)            // STAT34 only
   84581     **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
   84582     **   Next csr
   84583     **   if !eof(csr) goto next_row;
   84584     */
   84585 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84586     assert( regRowid==(regStat4+2) );
   84587     if( HasRowid(pTab) ){
   84588       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
   84589     }else{
   84590       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
   84591       int j, k, regKey;
   84592       regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
   84593       for(j=0; j<pPk->nKeyCol; j++){
   84594         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
   84595         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
   84596         VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
   84597       }
   84598       sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
   84599       sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
   84600     }
   84601 #endif
   84602     assert( regChng==(regStat4+1) );
   84603     sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
   84604     sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
   84605     sqlite3VdbeChangeP5(v, 2+IsStat34);
   84606     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
   84607 
   84608     /* Add the entry to the stat1 table. */
   84609     callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
   84610     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
   84611     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   84612     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
   84613     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   84614 
   84615     /* Add the entries to the stat3 or stat4 table. */
   84616 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84617     {
   84618       int regEq = regStat1;
   84619       int regLt = regStat1+1;
   84620       int regDLt = regStat1+2;
   84621       int regSample = regStat1+3;
   84622       int regCol = regStat1+4;
   84623       int regSampleRowid = regCol + nCol;
   84624       int addrNext;
   84625       int addrIsNull;
   84626       u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
   84627 
   84628       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
   84629 
   84630       addrNext = sqlite3VdbeCurrentAddr(v);
   84631       callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
   84632       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
   84633       VdbeCoverage(v);
   84634       callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
   84635       callStatGet(v, regStat4, STAT_GET_NLT, regLt);
   84636       callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
   84637       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
   84638       /* We know that the regSampleRowid row exists because it was read by
   84639       ** the previous loop.  Thus the not-found jump of seekOp will never
   84640       ** be taken */
   84641       VdbeCoverageNeverTaken(v);
   84642 #ifdef SQLITE_ENABLE_STAT3
   84643       sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
   84644                                       pIdx->aiColumn[0], regSample);
   84645 #else
   84646       for(i=0; i<nCol; i++){
   84647         i16 iCol = pIdx->aiColumn[i];
   84648         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
   84649       }
   84650       sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
   84651 #endif
   84652       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
   84653       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
   84654       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
   84655       sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
   84656       sqlite3VdbeJumpHere(v, addrIsNull);
   84657     }
   84658 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   84659 
   84660     /* End of analysis */
   84661     sqlite3VdbeJumpHere(v, addrRewind);
   84662   }
   84663 
   84664 
   84665   /* Create a single sqlite_stat1 entry containing NULL as the index
   84666   ** name and the row count as the content.
   84667   */
   84668   if( pOnlyIdx==0 && needTableCnt ){
   84669     VdbeComment((v, "%s", pTab->zName));
   84670     sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
   84671     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
   84672     sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
   84673     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
   84674     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   84675     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
   84676     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   84677     sqlite3VdbeJumpHere(v, jZeroRows);
   84678   }
   84679 }
   84680 
   84681 
   84682 /*
   84683 ** Generate code that will cause the most recent index analysis to
   84684 ** be loaded into internal hash tables where is can be used.
   84685 */
   84686 static void loadAnalysis(Parse *pParse, int iDb){
   84687   Vdbe *v = sqlite3GetVdbe(pParse);
   84688   if( v ){
   84689     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
   84690   }
   84691 }
   84692 
   84693 /*
   84694 ** Generate code that will do an analysis of an entire database
   84695 */
   84696 static void analyzeDatabase(Parse *pParse, int iDb){
   84697   sqlite3 *db = pParse->db;
   84698   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
   84699   HashElem *k;
   84700   int iStatCur;
   84701   int iMem;
   84702   int iTab;
   84703 
   84704   sqlite3BeginWriteOperation(pParse, 0, iDb);
   84705   iStatCur = pParse->nTab;
   84706   pParse->nTab += 3;
   84707   openStatTable(pParse, iDb, iStatCur, 0, 0);
   84708   iMem = pParse->nMem+1;
   84709   iTab = pParse->nTab;
   84710   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   84711   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   84712     Table *pTab = (Table*)sqliteHashData(k);
   84713     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
   84714   }
   84715   loadAnalysis(pParse, iDb);
   84716 }
   84717 
   84718 /*
   84719 ** Generate code that will do an analysis of a single table in
   84720 ** a database.  If pOnlyIdx is not NULL then it is a single index
   84721 ** in pTab that should be analyzed.
   84722 */
   84723 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
   84724   int iDb;
   84725   int iStatCur;
   84726 
   84727   assert( pTab!=0 );
   84728   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   84729   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   84730   sqlite3BeginWriteOperation(pParse, 0, iDb);
   84731   iStatCur = pParse->nTab;
   84732   pParse->nTab += 3;
   84733   if( pOnlyIdx ){
   84734     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
   84735   }else{
   84736     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
   84737   }
   84738   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
   84739   loadAnalysis(pParse, iDb);
   84740 }
   84741 
   84742 /*
   84743 ** Generate code for the ANALYZE command.  The parser calls this routine
   84744 ** when it recognizes an ANALYZE command.
   84745 **
   84746 **        ANALYZE                            -- 1
   84747 **        ANALYZE  <database>                -- 2
   84748 **        ANALYZE  ?<database>.?<tablename>  -- 3
   84749 **
   84750 ** Form 1 causes all indices in all attached databases to be analyzed.
   84751 ** Form 2 analyzes all indices the single database named.
   84752 ** Form 3 analyzes all indices associated with the named table.
   84753 */
   84754 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
   84755   sqlite3 *db = pParse->db;
   84756   int iDb;
   84757   int i;
   84758   char *z, *zDb;
   84759   Table *pTab;
   84760   Index *pIdx;
   84761   Token *pTableName;
   84762   Vdbe *v;
   84763 
   84764   /* Read the database schema. If an error occurs, leave an error message
   84765   ** and code in pParse and return NULL. */
   84766   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   84767   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   84768     return;
   84769   }
   84770 
   84771   assert( pName2!=0 || pName1==0 );
   84772   if( pName1==0 ){
   84773     /* Form 1:  Analyze everything */
   84774     for(i=0; i<db->nDb; i++){
   84775       if( i==1 ) continue;  /* Do not analyze the TEMP database */
   84776       analyzeDatabase(pParse, i);
   84777     }
   84778   }else if( pName2->n==0 ){
   84779     /* Form 2:  Analyze the database or table named */
   84780     iDb = sqlite3FindDb(db, pName1);
   84781     if( iDb>=0 ){
   84782       analyzeDatabase(pParse, iDb);
   84783     }else{
   84784       z = sqlite3NameFromToken(db, pName1);
   84785       if( z ){
   84786         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
   84787           analyzeTable(pParse, pIdx->pTable, pIdx);
   84788         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
   84789           analyzeTable(pParse, pTab, 0);
   84790         }
   84791         sqlite3DbFree(db, z);
   84792       }
   84793     }
   84794   }else{
   84795     /* Form 3: Analyze the fully qualified table name */
   84796     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
   84797     if( iDb>=0 ){
   84798       zDb = db->aDb[iDb].zName;
   84799       z = sqlite3NameFromToken(db, pTableName);
   84800       if( z ){
   84801         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
   84802           analyzeTable(pParse, pIdx->pTable, pIdx);
   84803         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
   84804           analyzeTable(pParse, pTab, 0);
   84805         }
   84806         sqlite3DbFree(db, z);
   84807       }
   84808     }
   84809   }
   84810   v = sqlite3GetVdbe(pParse);
   84811   if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
   84812 }
   84813 
   84814 /*
   84815 ** Used to pass information from the analyzer reader through to the
   84816 ** callback routine.
   84817 */
   84818 typedef struct analysisInfo analysisInfo;
   84819 struct analysisInfo {
   84820   sqlite3 *db;
   84821   const char *zDatabase;
   84822 };
   84823 
   84824 /*
   84825 ** The first argument points to a nul-terminated string containing a
   84826 ** list of space separated integers. Read the first nOut of these into
   84827 ** the array aOut[].
   84828 */
   84829 static void decodeIntArray(
   84830   char *zIntArray,       /* String containing int array to decode */
   84831   int nOut,              /* Number of slots in aOut[] */
   84832   tRowcnt *aOut,         /* Store integers here */
   84833   LogEst *aLog,          /* Or, if aOut==0, here */
   84834   Index *pIndex          /* Handle extra flags for this index, if not NULL */
   84835 ){
   84836   char *z = zIntArray;
   84837   int c;
   84838   int i;
   84839   tRowcnt v;
   84840 
   84841 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84842   if( z==0 ) z = "";
   84843 #else
   84844   if( NEVER(z==0) ) z = "";
   84845 #endif
   84846   for(i=0; *z && i<nOut; i++){
   84847     v = 0;
   84848     while( (c=z[0])>='0' && c<='9' ){
   84849       v = v*10 + c - '0';
   84850       z++;
   84851     }
   84852 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84853     if( aOut ){
   84854       aOut[i] = v;
   84855     }else
   84856 #else
   84857     assert( aOut==0 );
   84858     UNUSED_PARAMETER(aOut);
   84859 #endif
   84860     {
   84861       aLog[i] = sqlite3LogEst(v);
   84862     }
   84863     if( *z==' ' ) z++;
   84864   }
   84865 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
   84866   assert( pIndex!=0 );
   84867 #else
   84868   if( pIndex )
   84869 #endif
   84870   while( z[0] ){
   84871     if( sqlite3_strglob("unordered*", z)==0 ){
   84872       pIndex->bUnordered = 1;
   84873     }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
   84874       pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
   84875     }
   84876 #ifdef SQLITE_ENABLE_COSTMULT
   84877     else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
   84878       pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
   84879     }
   84880 #endif
   84881     while( z[0]!=0 && z[0]!=' ' ) z++;
   84882     while( z[0]==' ' ) z++;
   84883   }
   84884 }
   84885 
   84886 /*
   84887 ** This callback is invoked once for each index when reading the
   84888 ** sqlite_stat1 table.
   84889 **
   84890 **     argv[0] = name of the table
   84891 **     argv[1] = name of the index (might be NULL)
   84892 **     argv[2] = results of analysis - on integer for each column
   84893 **
   84894 ** Entries for which argv[1]==NULL simply record the number of rows in
   84895 ** the table.
   84896 */
   84897 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
   84898   analysisInfo *pInfo = (analysisInfo*)pData;
   84899   Index *pIndex;
   84900   Table *pTable;
   84901   const char *z;
   84902 
   84903   assert( argc==3 );
   84904   UNUSED_PARAMETER2(NotUsed, argc);
   84905 
   84906   if( argv==0 || argv[0]==0 || argv[2]==0 ){
   84907     return 0;
   84908   }
   84909   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
   84910   if( pTable==0 ){
   84911     return 0;
   84912   }
   84913   if( argv[1]==0 ){
   84914     pIndex = 0;
   84915   }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
   84916     pIndex = sqlite3PrimaryKeyIndex(pTable);
   84917   }else{
   84918     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
   84919   }
   84920   z = argv[2];
   84921 
   84922   if( pIndex ){
   84923     pIndex->bUnordered = 0;
   84924     decodeIntArray((char*)z, pIndex->nKeyCol+1, 0, pIndex->aiRowLogEst, pIndex);
   84925     if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
   84926   }else{
   84927     Index fakeIdx;
   84928     fakeIdx.szIdxRow = pTable->szTabRow;
   84929 #ifdef SQLITE_ENABLE_COSTMULT
   84930     fakeIdx.pTable = pTable;
   84931 #endif
   84932     decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
   84933     pTable->szTabRow = fakeIdx.szIdxRow;
   84934   }
   84935 
   84936   return 0;
   84937 }
   84938 
   84939 /*
   84940 ** If the Index.aSample variable is not NULL, delete the aSample[] array
   84941 ** and its contents.
   84942 */
   84943 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
   84944 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84945   if( pIdx->aSample ){
   84946     int j;
   84947     for(j=0; j<pIdx->nSample; j++){
   84948       IndexSample *p = &pIdx->aSample[j];
   84949       sqlite3DbFree(db, p->p);
   84950     }
   84951     sqlite3DbFree(db, pIdx->aSample);
   84952   }
   84953   if( db && db->pnBytesFreed==0 ){
   84954     pIdx->nSample = 0;
   84955     pIdx->aSample = 0;
   84956   }
   84957 #else
   84958   UNUSED_PARAMETER(db);
   84959   UNUSED_PARAMETER(pIdx);
   84960 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   84961 }
   84962 
   84963 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   84964 /*
   84965 ** Populate the pIdx->aAvgEq[] array based on the samples currently
   84966 ** stored in pIdx->aSample[].
   84967 */
   84968 static void initAvgEq(Index *pIdx){
   84969   if( pIdx ){
   84970     IndexSample *aSample = pIdx->aSample;
   84971     IndexSample *pFinal = &aSample[pIdx->nSample-1];
   84972     int iCol;
   84973     int nCol = 1;
   84974     if( pIdx->nSampleCol>1 ){
   84975       /* If this is stat4 data, then calculate aAvgEq[] values for all
   84976       ** sample columns except the last. The last is always set to 1, as
   84977       ** once the trailing PK fields are considered all index keys are
   84978       ** unique.  */
   84979       nCol = pIdx->nSampleCol-1;
   84980       pIdx->aAvgEq[nCol] = 1;
   84981     }
   84982     for(iCol=0; iCol<nCol; iCol++){
   84983       int i;                    /* Used to iterate through samples */
   84984       tRowcnt sumEq = 0;        /* Sum of the nEq values */
   84985       tRowcnt nSum = 0;         /* Number of terms contributing to sumEq */
   84986       tRowcnt avgEq = 0;
   84987       tRowcnt nDLt = pFinal->anDLt[iCol];
   84988 
   84989       /* Set nSum to the number of distinct (iCol+1) field prefixes that
   84990       ** occur in the stat4 table for this index before pFinal. Set
   84991       ** sumEq to the sum of the nEq values for column iCol for the same
   84992       ** set (adding the value only once where there exist dupicate
   84993       ** prefixes).  */
   84994       for(i=0; i<(pIdx->nSample-1); i++){
   84995         if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
   84996           sumEq += aSample[i].anEq[iCol];
   84997           nSum++;
   84998         }
   84999       }
   85000       if( nDLt>nSum ){
   85001         avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
   85002       }
   85003       if( avgEq==0 ) avgEq = 1;
   85004       pIdx->aAvgEq[iCol] = avgEq;
   85005     }
   85006   }
   85007 }
   85008 
   85009 /*
   85010 ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
   85011 ** is supplied instead, find the PRIMARY KEY index for that table.
   85012 */
   85013 static Index *findIndexOrPrimaryKey(
   85014   sqlite3 *db,
   85015   const char *zName,
   85016   const char *zDb
   85017 ){
   85018   Index *pIdx = sqlite3FindIndex(db, zName, zDb);
   85019   if( pIdx==0 ){
   85020     Table *pTab = sqlite3FindTable(db, zName, zDb);
   85021     if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
   85022   }
   85023   return pIdx;
   85024 }
   85025 
   85026 /*
   85027 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
   85028 ** into the relevant Index.aSample[] arrays.
   85029 **
   85030 ** Arguments zSql1 and zSql2 must point to SQL statements that return
   85031 ** data equivalent to the following (statements are different for stat3,
   85032 ** see the caller of this function for details):
   85033 **
   85034 **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
   85035 **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
   85036 **
   85037 ** where %Q is replaced with the database name before the SQL is executed.
   85038 */
   85039 static int loadStatTbl(
   85040   sqlite3 *db,                  /* Database handle */
   85041   int bStat3,                   /* Assume single column records only */
   85042   const char *zSql1,            /* SQL statement 1 (see above) */
   85043   const char *zSql2,            /* SQL statement 2 (see above) */
   85044   const char *zDb               /* Database name (e.g. "main") */
   85045 ){
   85046   int rc;                       /* Result codes from subroutines */
   85047   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
   85048   char *zSql;                   /* Text of the SQL statement */
   85049   Index *pPrevIdx = 0;          /* Previous index in the loop */
   85050   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
   85051 
   85052   assert( db->lookaside.bEnabled==0 );
   85053   zSql = sqlite3MPrintf(db, zSql1, zDb);
   85054   if( !zSql ){
   85055     return SQLITE_NOMEM;
   85056   }
   85057   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   85058   sqlite3DbFree(db, zSql);
   85059   if( rc ) return rc;
   85060 
   85061   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   85062     int nIdxCol = 1;              /* Number of columns in stat4 records */
   85063 
   85064     char *zIndex;   /* Index name */
   85065     Index *pIdx;    /* Pointer to the index object */
   85066     int nSample;    /* Number of samples */
   85067     int nByte;      /* Bytes of space required */
   85068     int i;          /* Bytes of space required */
   85069     tRowcnt *pSpace;
   85070 
   85071     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   85072     if( zIndex==0 ) continue;
   85073     nSample = sqlite3_column_int(pStmt, 1);
   85074     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
   85075     assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
   85076     /* Index.nSample is non-zero at this point if data has already been
   85077     ** loaded from the stat4 table. In this case ignore stat3 data.  */
   85078     if( pIdx==0 || pIdx->nSample ) continue;
   85079     if( bStat3==0 ){
   85080       assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
   85081       if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
   85082         nIdxCol = pIdx->nKeyCol;
   85083       }else{
   85084         nIdxCol = pIdx->nColumn;
   85085       }
   85086     }
   85087     pIdx->nSampleCol = nIdxCol;
   85088     nByte = sizeof(IndexSample) * nSample;
   85089     nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
   85090     nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
   85091 
   85092     pIdx->aSample = sqlite3DbMallocZero(db, nByte);
   85093     if( pIdx->aSample==0 ){
   85094       sqlite3_finalize(pStmt);
   85095       return SQLITE_NOMEM;
   85096     }
   85097     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
   85098     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
   85099     for(i=0; i<nSample; i++){
   85100       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
   85101       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
   85102       pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
   85103     }
   85104     assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
   85105   }
   85106   rc = sqlite3_finalize(pStmt);
   85107   if( rc ) return rc;
   85108 
   85109   zSql = sqlite3MPrintf(db, zSql2, zDb);
   85110   if( !zSql ){
   85111     return SQLITE_NOMEM;
   85112   }
   85113   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   85114   sqlite3DbFree(db, zSql);
   85115   if( rc ) return rc;
   85116 
   85117   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   85118     char *zIndex;                 /* Index name */
   85119     Index *pIdx;                  /* Pointer to the index object */
   85120     int nCol = 1;                 /* Number of columns in index */
   85121 
   85122     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   85123     if( zIndex==0 ) continue;
   85124     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
   85125     if( pIdx==0 ) continue;
   85126     /* This next condition is true if data has already been loaded from
   85127     ** the sqlite_stat4 table. In this case ignore stat3 data.  */
   85128     nCol = pIdx->nSampleCol;
   85129     if( bStat3 && nCol>1 ) continue;
   85130     if( pIdx!=pPrevIdx ){
   85131       initAvgEq(pPrevIdx);
   85132       pPrevIdx = pIdx;
   85133     }
   85134     pSample = &pIdx->aSample[pIdx->nSample];
   85135     decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
   85136     decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
   85137     decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
   85138 
   85139     /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
   85140     ** This is in case the sample record is corrupted. In that case, the
   85141     ** sqlite3VdbeRecordCompare() may read up to two varints past the
   85142     ** end of the allocated buffer before it realizes it is dealing with
   85143     ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
   85144     ** a buffer overread.  */
   85145     pSample->n = sqlite3_column_bytes(pStmt, 4);
   85146     pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
   85147     if( pSample->p==0 ){
   85148       sqlite3_finalize(pStmt);
   85149       return SQLITE_NOMEM;
   85150     }
   85151     memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
   85152     pIdx->nSample++;
   85153   }
   85154   rc = sqlite3_finalize(pStmt);
   85155   if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
   85156   return rc;
   85157 }
   85158 
   85159 /*
   85160 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
   85161 ** the Index.aSample[] arrays of all indices.
   85162 */
   85163 static int loadStat4(sqlite3 *db, const char *zDb){
   85164   int rc = SQLITE_OK;             /* Result codes from subroutines */
   85165 
   85166   assert( db->lookaside.bEnabled==0 );
   85167   if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
   85168     rc = loadStatTbl(db, 0,
   85169       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
   85170       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
   85171       zDb
   85172     );
   85173   }
   85174 
   85175   if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
   85176     rc = loadStatTbl(db, 1,
   85177       "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
   85178       "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
   85179       zDb
   85180     );
   85181   }
   85182 
   85183   return rc;
   85184 }
   85185 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   85186 
   85187 /*
   85188 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
   85189 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
   85190 ** arrays. The contents of sqlite_stat3/4 are used to populate the
   85191 ** Index.aSample[] arrays.
   85192 **
   85193 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
   85194 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
   85195 ** during compilation and the sqlite_stat3/4 table is present, no data is
   85196 ** read from it.
   85197 **
   85198 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
   85199 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
   85200 ** returned. However, in this case, data is read from the sqlite_stat1
   85201 ** table (if it is present) before returning.
   85202 **
   85203 ** If an OOM error occurs, this function always sets db->mallocFailed.
   85204 ** This means if the caller does not care about other errors, the return
   85205 ** code may be ignored.
   85206 */
   85207 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   85208   analysisInfo sInfo;
   85209   HashElem *i;
   85210   char *zSql;
   85211   int rc;
   85212 
   85213   assert( iDb>=0 && iDb<db->nDb );
   85214   assert( db->aDb[iDb].pBt!=0 );
   85215 
   85216   /* Clear any prior statistics */
   85217   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   85218   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
   85219     Index *pIdx = sqliteHashData(i);
   85220     sqlite3DefaultRowEst(pIdx);
   85221 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   85222     sqlite3DeleteIndexSamples(db, pIdx);
   85223     pIdx->aSample = 0;
   85224 #endif
   85225   }
   85226 
   85227   /* Check to make sure the sqlite_stat1 table exists */
   85228   sInfo.db = db;
   85229   sInfo.zDatabase = db->aDb[iDb].zName;
   85230   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
   85231     return SQLITE_ERROR;
   85232   }
   85233 
   85234   /* Load new statistics out of the sqlite_stat1 table */
   85235   zSql = sqlite3MPrintf(db,
   85236       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
   85237   if( zSql==0 ){
   85238     rc = SQLITE_NOMEM;
   85239   }else{
   85240     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
   85241     sqlite3DbFree(db, zSql);
   85242   }
   85243 
   85244 
   85245   /* Load the statistics from the sqlite_stat4 table. */
   85246 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   85247   if( rc==SQLITE_OK ){
   85248     int lookasideEnabled = db->lookaside.bEnabled;
   85249     db->lookaside.bEnabled = 0;
   85250     rc = loadStat4(db, sInfo.zDatabase);
   85251     db->lookaside.bEnabled = lookasideEnabled;
   85252   }
   85253 #endif
   85254 
   85255   if( rc==SQLITE_NOMEM ){
   85256     db->mallocFailed = 1;
   85257   }
   85258   return rc;
   85259 }
   85260 
   85261 
   85262 #endif /* SQLITE_OMIT_ANALYZE */
   85263 
   85264 /************** End of analyze.c *********************************************/
   85265 /************** Begin file attach.c ******************************************/
   85266 /*
   85267 ** 2003 April 6
   85268 **
   85269 ** The author disclaims copyright to this source code.  In place of
   85270 ** a legal notice, here is a blessing:
   85271 **
   85272 **    May you do good and not evil.
   85273 **    May you find forgiveness for yourself and forgive others.
   85274 **    May you share freely, never taking more than you give.
   85275 **
   85276 *************************************************************************
   85277 ** This file contains code used to implement the ATTACH and DETACH commands.
   85278 */
   85279 
   85280 #ifndef SQLITE_OMIT_ATTACH
   85281 /*
   85282 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
   85283 ** is slightly different from resolving a normal SQL expression, because simple
   85284 ** identifiers are treated as strings, not possible column names or aliases.
   85285 **
   85286 ** i.e. if the parser sees:
   85287 **
   85288 **     ATTACH DATABASE abc AS def
   85289 **
   85290 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
   85291 ** looking for columns of the same name.
   85292 **
   85293 ** This only applies to the root node of pExpr, so the statement:
   85294 **
   85295 **     ATTACH DATABASE abc||def AS 'db2'
   85296 **
   85297 ** will fail because neither abc or def can be resolved.
   85298 */
   85299 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
   85300 {
   85301   int rc = SQLITE_OK;
   85302   if( pExpr ){
   85303     if( pExpr->op!=TK_ID ){
   85304       rc = sqlite3ResolveExprNames(pName, pExpr);
   85305     }else{
   85306       pExpr->op = TK_STRING;
   85307     }
   85308   }
   85309   return rc;
   85310 }
   85311 
   85312 /*
   85313 ** An SQL user-function registered to do the work of an ATTACH statement. The
   85314 ** three arguments to the function come directly from an attach statement:
   85315 **
   85316 **     ATTACH DATABASE x AS y KEY z
   85317 **
   85318 **     SELECT sqlite_attach(x, y, z)
   85319 **
   85320 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
   85321 ** third argument.
   85322 */
   85323 static void attachFunc(
   85324   sqlite3_context *context,
   85325   int NotUsed,
   85326   sqlite3_value **argv
   85327 ){
   85328   int i;
   85329   int rc = 0;
   85330   sqlite3 *db = sqlite3_context_db_handle(context);
   85331   const char *zName;
   85332   const char *zFile;
   85333   char *zPath = 0;
   85334   char *zErr = 0;
   85335   unsigned int flags;
   85336   Db *aNew;
   85337   char *zErrDyn = 0;
   85338   sqlite3_vfs *pVfs;
   85339 
   85340   UNUSED_PARAMETER(NotUsed);
   85341 
   85342   zFile = (const char *)sqlite3_value_text(argv[0]);
   85343   zName = (const char *)sqlite3_value_text(argv[1]);
   85344   if( zFile==0 ) zFile = "";
   85345   if( zName==0 ) zName = "";
   85346 
   85347   /* Check for the following errors:
   85348   **
   85349   **     * Too many attached databases,
   85350   **     * Transaction currently open
   85351   **     * Specified database name already being used.
   85352   */
   85353   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
   85354     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
   85355       db->aLimit[SQLITE_LIMIT_ATTACHED]
   85356     );
   85357     goto attach_error;
   85358   }
   85359   if( !db->autoCommit ){
   85360     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
   85361     goto attach_error;
   85362   }
   85363   for(i=0; i<db->nDb; i++){
   85364     char *z = db->aDb[i].zName;
   85365     assert( z && zName );
   85366     if( sqlite3StrICmp(z, zName)==0 ){
   85367       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
   85368       goto attach_error;
   85369     }
   85370   }
   85371 
   85372   /* Allocate the new entry in the db->aDb[] array and initialize the schema
   85373   ** hash tables.
   85374   */
   85375   if( db->aDb==db->aDbStatic ){
   85376     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
   85377     if( aNew==0 ) return;
   85378     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
   85379   }else{
   85380     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
   85381     if( aNew==0 ) return;
   85382   }
   85383   db->aDb = aNew;
   85384   aNew = &db->aDb[db->nDb];
   85385   memset(aNew, 0, sizeof(*aNew));
   85386 
   85387   /* Open the database file. If the btree is successfully opened, use
   85388   ** it to obtain the database schema. At this point the schema may
   85389   ** or may not be initialized.
   85390   */
   85391   flags = db->openFlags;
   85392   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
   85393   if( rc!=SQLITE_OK ){
   85394     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   85395     sqlite3_result_error(context, zErr, -1);
   85396     sqlite3_free(zErr);
   85397     return;
   85398   }
   85399   assert( pVfs );
   85400   flags |= SQLITE_OPEN_MAIN_DB;
   85401   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
   85402   sqlite3_free( zPath );
   85403   db->nDb++;
   85404   if( rc==SQLITE_CONSTRAINT ){
   85405     rc = SQLITE_ERROR;
   85406     zErrDyn = sqlite3MPrintf(db, "database is already attached");
   85407   }else if( rc==SQLITE_OK ){
   85408     Pager *pPager;
   85409     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
   85410     if( !aNew->pSchema ){
   85411       rc = SQLITE_NOMEM;
   85412     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
   85413       zErrDyn = sqlite3MPrintf(db,
   85414         "attached databases must use the same text encoding as main database");
   85415       rc = SQLITE_ERROR;
   85416     }
   85417     pPager = sqlite3BtreePager(aNew->pBt);
   85418     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
   85419     sqlite3BtreeSecureDelete(aNew->pBt,
   85420                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
   85421 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   85422     sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
   85423 #endif
   85424   }
   85425   aNew->safety_level = 3;
   85426   aNew->zName = sqlite3DbStrDup(db, zName);
   85427   if( rc==SQLITE_OK && aNew->zName==0 ){
   85428     rc = SQLITE_NOMEM;
   85429   }
   85430 
   85431 
   85432 #ifdef SQLITE_HAS_CODEC
   85433   if( rc==SQLITE_OK ){
   85434     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
   85435     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   85436     int nKey;
   85437     char *zKey;
   85438     int t = sqlite3_value_type(argv[2]);
   85439     switch( t ){
   85440       case SQLITE_INTEGER:
   85441       case SQLITE_FLOAT:
   85442         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
   85443         rc = SQLITE_ERROR;
   85444         break;
   85445 
   85446       case SQLITE_TEXT:
   85447       case SQLITE_BLOB:
   85448         nKey = sqlite3_value_bytes(argv[2]);
   85449         zKey = (char *)sqlite3_value_blob(argv[2]);
   85450         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   85451         break;
   85452 
   85453       case SQLITE_NULL:
   85454         /* No key specified.  Use the key from the main database */
   85455         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   85456         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
   85457           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   85458         }
   85459         break;
   85460     }
   85461   }
   85462 #endif
   85463 
   85464   /* If the file was opened successfully, read the schema for the new database.
   85465   ** If this fails, or if opening the file failed, then close the file and
   85466   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
   85467   ** we found it.
   85468   */
   85469   if( rc==SQLITE_OK ){
   85470     sqlite3BtreeEnterAll(db);
   85471     rc = sqlite3Init(db, &zErrDyn);
   85472     sqlite3BtreeLeaveAll(db);
   85473   }
   85474   if( rc ){
   85475     int iDb = db->nDb - 1;
   85476     assert( iDb>=2 );
   85477     if( db->aDb[iDb].pBt ){
   85478       sqlite3BtreeClose(db->aDb[iDb].pBt);
   85479       db->aDb[iDb].pBt = 0;
   85480       db->aDb[iDb].pSchema = 0;
   85481     }
   85482     sqlite3ResetAllSchemasOfConnection(db);
   85483     db->nDb = iDb;
   85484     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   85485       db->mallocFailed = 1;
   85486       sqlite3DbFree(db, zErrDyn);
   85487       zErrDyn = sqlite3MPrintf(db, "out of memory");
   85488     }else if( zErrDyn==0 ){
   85489       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
   85490     }
   85491     goto attach_error;
   85492   }
   85493 
   85494   return;
   85495 
   85496 attach_error:
   85497   /* Return an error if we get here */
   85498   if( zErrDyn ){
   85499     sqlite3_result_error(context, zErrDyn, -1);
   85500     sqlite3DbFree(db, zErrDyn);
   85501   }
   85502   if( rc ) sqlite3_result_error_code(context, rc);
   85503 }
   85504 
   85505 /*
   85506 ** An SQL user-function registered to do the work of an DETACH statement. The
   85507 ** three arguments to the function come directly from a detach statement:
   85508 **
   85509 **     DETACH DATABASE x
   85510 **
   85511 **     SELECT sqlite_detach(x)
   85512 */
   85513 static void detachFunc(
   85514   sqlite3_context *context,
   85515   int NotUsed,
   85516   sqlite3_value **argv
   85517 ){
   85518   const char *zName = (const char *)sqlite3_value_text(argv[0]);
   85519   sqlite3 *db = sqlite3_context_db_handle(context);
   85520   int i;
   85521   Db *pDb = 0;
   85522   char zErr[128];
   85523 
   85524   UNUSED_PARAMETER(NotUsed);
   85525 
   85526   if( zName==0 ) zName = "";
   85527   for(i=0; i<db->nDb; i++){
   85528     pDb = &db->aDb[i];
   85529     if( pDb->pBt==0 ) continue;
   85530     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
   85531   }
   85532 
   85533   if( i>=db->nDb ){
   85534     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
   85535     goto detach_error;
   85536   }
   85537   if( i<2 ){
   85538     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
   85539     goto detach_error;
   85540   }
   85541   if( !db->autoCommit ){
   85542     sqlite3_snprintf(sizeof(zErr), zErr,
   85543                      "cannot DETACH database within transaction");
   85544     goto detach_error;
   85545   }
   85546   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
   85547     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
   85548     goto detach_error;
   85549   }
   85550 
   85551   sqlite3BtreeClose(pDb->pBt);
   85552   pDb->pBt = 0;
   85553   pDb->pSchema = 0;
   85554   sqlite3ResetAllSchemasOfConnection(db);
   85555   return;
   85556 
   85557 detach_error:
   85558   sqlite3_result_error(context, zErr, -1);
   85559 }
   85560 
   85561 /*
   85562 ** This procedure generates VDBE code for a single invocation of either the
   85563 ** sqlite_detach() or sqlite_attach() SQL user functions.
   85564 */
   85565 static void codeAttach(
   85566   Parse *pParse,       /* The parser context */
   85567   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
   85568   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
   85569   Expr *pAuthArg,      /* Expression to pass to authorization callback */
   85570   Expr *pFilename,     /* Name of database file */
   85571   Expr *pDbname,       /* Name of the database to use internally */
   85572   Expr *pKey           /* Database key for encryption extension */
   85573 ){
   85574   int rc;
   85575   NameContext sName;
   85576   Vdbe *v;
   85577   sqlite3* db = pParse->db;
   85578   int regArgs;
   85579 
   85580   memset(&sName, 0, sizeof(NameContext));
   85581   sName.pParse = pParse;
   85582 
   85583   if(
   85584       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
   85585       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
   85586       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
   85587   ){
   85588     pParse->nErr++;
   85589     goto attach_end;
   85590   }
   85591 
   85592 #ifndef SQLITE_OMIT_AUTHORIZATION
   85593   if( pAuthArg ){
   85594     char *zAuthArg;
   85595     if( pAuthArg->op==TK_STRING ){
   85596       zAuthArg = pAuthArg->u.zToken;
   85597     }else{
   85598       zAuthArg = 0;
   85599     }
   85600     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
   85601     if(rc!=SQLITE_OK ){
   85602       goto attach_end;
   85603     }
   85604   }
   85605 #endif /* SQLITE_OMIT_AUTHORIZATION */
   85606 
   85607 
   85608   v = sqlite3GetVdbe(pParse);
   85609   regArgs = sqlite3GetTempRange(pParse, 4);
   85610   sqlite3ExprCode(pParse, pFilename, regArgs);
   85611   sqlite3ExprCode(pParse, pDbname, regArgs+1);
   85612   sqlite3ExprCode(pParse, pKey, regArgs+2);
   85613 
   85614   assert( v || db->mallocFailed );
   85615   if( v ){
   85616     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
   85617     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
   85618     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
   85619     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
   85620 
   85621     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
   85622     ** statement only). For DETACH, set it to false (expire all existing
   85623     ** statements).
   85624     */
   85625     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
   85626   }
   85627 
   85628 attach_end:
   85629   sqlite3ExprDelete(db, pFilename);
   85630   sqlite3ExprDelete(db, pDbname);
   85631   sqlite3ExprDelete(db, pKey);
   85632 }
   85633 
   85634 /*
   85635 ** Called by the parser to compile a DETACH statement.
   85636 **
   85637 **     DETACH pDbname
   85638 */
   85639 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
   85640   static const FuncDef detach_func = {
   85641     1,                /* nArg */
   85642     SQLITE_UTF8,      /* funcFlags */
   85643     0,                /* pUserData */
   85644     0,                /* pNext */
   85645     detachFunc,       /* xFunc */
   85646     0,                /* xStep */
   85647     0,                /* xFinalize */
   85648     "sqlite_detach",  /* zName */
   85649     0,                /* pHash */
   85650     0                 /* pDestructor */
   85651   };
   85652   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
   85653 }
   85654 
   85655 /*
   85656 ** Called by the parser to compile an ATTACH statement.
   85657 **
   85658 **     ATTACH p AS pDbname KEY pKey
   85659 */
   85660 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
   85661   static const FuncDef attach_func = {
   85662     3,                /* nArg */
   85663     SQLITE_UTF8,      /* funcFlags */
   85664     0,                /* pUserData */
   85665     0,                /* pNext */
   85666     attachFunc,       /* xFunc */
   85667     0,                /* xStep */
   85668     0,                /* xFinalize */
   85669     "sqlite_attach",  /* zName */
   85670     0,                /* pHash */
   85671     0                 /* pDestructor */
   85672   };
   85673   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
   85674 }
   85675 #endif /* SQLITE_OMIT_ATTACH */
   85676 
   85677 /*
   85678 ** Initialize a DbFixer structure.  This routine must be called prior
   85679 ** to passing the structure to one of the sqliteFixAAAA() routines below.
   85680 */
   85681 SQLITE_PRIVATE void sqlite3FixInit(
   85682   DbFixer *pFix,      /* The fixer to be initialized */
   85683   Parse *pParse,      /* Error messages will be written here */
   85684   int iDb,            /* This is the database that must be used */
   85685   const char *zType,  /* "view", "trigger", or "index" */
   85686   const Token *pName  /* Name of the view, trigger, or index */
   85687 ){
   85688   sqlite3 *db;
   85689 
   85690   db = pParse->db;
   85691   assert( db->nDb>iDb );
   85692   pFix->pParse = pParse;
   85693   pFix->zDb = db->aDb[iDb].zName;
   85694   pFix->pSchema = db->aDb[iDb].pSchema;
   85695   pFix->zType = zType;
   85696   pFix->pName = pName;
   85697   pFix->bVarOnly = (iDb==1);
   85698 }
   85699 
   85700 /*
   85701 ** The following set of routines walk through the parse tree and assign
   85702 ** a specific database to all table references where the database name
   85703 ** was left unspecified in the original SQL statement.  The pFix structure
   85704 ** must have been initialized by a prior call to sqlite3FixInit().
   85705 **
   85706 ** These routines are used to make sure that an index, trigger, or
   85707 ** view in one database does not refer to objects in a different database.
   85708 ** (Exception: indices, triggers, and views in the TEMP database are
   85709 ** allowed to refer to anything.)  If a reference is explicitly made
   85710 ** to an object in a different database, an error message is added to
   85711 ** pParse->zErrMsg and these routines return non-zero.  If everything
   85712 ** checks out, these routines return 0.
   85713 */
   85714 SQLITE_PRIVATE int sqlite3FixSrcList(
   85715   DbFixer *pFix,       /* Context of the fixation */
   85716   SrcList *pList       /* The Source list to check and modify */
   85717 ){
   85718   int i;
   85719   const char *zDb;
   85720   struct SrcList_item *pItem;
   85721 
   85722   if( NEVER(pList==0) ) return 0;
   85723   zDb = pFix->zDb;
   85724   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   85725     if( pFix->bVarOnly==0 ){
   85726       if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
   85727         sqlite3ErrorMsg(pFix->pParse,
   85728             "%s %T cannot reference objects in database %s",
   85729             pFix->zType, pFix->pName, pItem->zDatabase);
   85730         return 1;
   85731       }
   85732       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
   85733       pItem->zDatabase = 0;
   85734       pItem->pSchema = pFix->pSchema;
   85735     }
   85736 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   85737     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
   85738     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
   85739 #endif
   85740   }
   85741   return 0;
   85742 }
   85743 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   85744 SQLITE_PRIVATE int sqlite3FixSelect(
   85745   DbFixer *pFix,       /* Context of the fixation */
   85746   Select *pSelect      /* The SELECT statement to be fixed to one database */
   85747 ){
   85748   while( pSelect ){
   85749     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
   85750       return 1;
   85751     }
   85752     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
   85753       return 1;
   85754     }
   85755     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
   85756       return 1;
   85757     }
   85758     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
   85759       return 1;
   85760     }
   85761     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
   85762       return 1;
   85763     }
   85764     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
   85765       return 1;
   85766     }
   85767     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
   85768       return 1;
   85769     }
   85770     if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
   85771       return 1;
   85772     }
   85773     pSelect = pSelect->pPrior;
   85774   }
   85775   return 0;
   85776 }
   85777 SQLITE_PRIVATE int sqlite3FixExpr(
   85778   DbFixer *pFix,     /* Context of the fixation */
   85779   Expr *pExpr        /* The expression to be fixed to one database */
   85780 ){
   85781   while( pExpr ){
   85782     if( pExpr->op==TK_VARIABLE ){
   85783       if( pFix->pParse->db->init.busy ){
   85784         pExpr->op = TK_NULL;
   85785       }else{
   85786         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
   85787         return 1;
   85788       }
   85789     }
   85790     if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
   85791     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   85792       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
   85793     }else{
   85794       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
   85795     }
   85796     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
   85797       return 1;
   85798     }
   85799     pExpr = pExpr->pLeft;
   85800   }
   85801   return 0;
   85802 }
   85803 SQLITE_PRIVATE int sqlite3FixExprList(
   85804   DbFixer *pFix,     /* Context of the fixation */
   85805   ExprList *pList    /* The expression to be fixed to one database */
   85806 ){
   85807   int i;
   85808   struct ExprList_item *pItem;
   85809   if( pList==0 ) return 0;
   85810   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
   85811     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
   85812       return 1;
   85813     }
   85814   }
   85815   return 0;
   85816 }
   85817 #endif
   85818 
   85819 #ifndef SQLITE_OMIT_TRIGGER
   85820 SQLITE_PRIVATE int sqlite3FixTriggerStep(
   85821   DbFixer *pFix,     /* Context of the fixation */
   85822   TriggerStep *pStep /* The trigger step be fixed to one database */
   85823 ){
   85824   while( pStep ){
   85825     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
   85826       return 1;
   85827     }
   85828     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
   85829       return 1;
   85830     }
   85831     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
   85832       return 1;
   85833     }
   85834     pStep = pStep->pNext;
   85835   }
   85836   return 0;
   85837 }
   85838 #endif
   85839 
   85840 /************** End of attach.c **********************************************/
   85841 /************** Begin file auth.c ********************************************/
   85842 /*
   85843 ** 2003 January 11
   85844 **
   85845 ** The author disclaims copyright to this source code.  In place of
   85846 ** a legal notice, here is a blessing:
   85847 **
   85848 **    May you do good and not evil.
   85849 **    May you find forgiveness for yourself and forgive others.
   85850 **    May you share freely, never taking more than you give.
   85851 **
   85852 *************************************************************************
   85853 ** This file contains code used to implement the sqlite3_set_authorizer()
   85854 ** API.  This facility is an optional feature of the library.  Embedded
   85855 ** systems that do not need this facility may omit it by recompiling
   85856 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
   85857 */
   85858 
   85859 /*
   85860 ** All of the code in this file may be omitted by defining a single
   85861 ** macro.
   85862 */
   85863 #ifndef SQLITE_OMIT_AUTHORIZATION
   85864 
   85865 /*
   85866 ** Set or clear the access authorization function.
   85867 **
   85868 ** The access authorization function is be called during the compilation
   85869 ** phase to verify that the user has read and/or write access permission on
   85870 ** various fields of the database.  The first argument to the auth function
   85871 ** is a copy of the 3rd argument to this routine.  The second argument
   85872 ** to the auth function is one of these constants:
   85873 **
   85874 **       SQLITE_CREATE_INDEX
   85875 **       SQLITE_CREATE_TABLE
   85876 **       SQLITE_CREATE_TEMP_INDEX
   85877 **       SQLITE_CREATE_TEMP_TABLE
   85878 **       SQLITE_CREATE_TEMP_TRIGGER
   85879 **       SQLITE_CREATE_TEMP_VIEW
   85880 **       SQLITE_CREATE_TRIGGER
   85881 **       SQLITE_CREATE_VIEW
   85882 **       SQLITE_DELETE
   85883 **       SQLITE_DROP_INDEX
   85884 **       SQLITE_DROP_TABLE
   85885 **       SQLITE_DROP_TEMP_INDEX
   85886 **       SQLITE_DROP_TEMP_TABLE
   85887 **       SQLITE_DROP_TEMP_TRIGGER
   85888 **       SQLITE_DROP_TEMP_VIEW
   85889 **       SQLITE_DROP_TRIGGER
   85890 **       SQLITE_DROP_VIEW
   85891 **       SQLITE_INSERT
   85892 **       SQLITE_PRAGMA
   85893 **       SQLITE_READ
   85894 **       SQLITE_SELECT
   85895 **       SQLITE_TRANSACTION
   85896 **       SQLITE_UPDATE
   85897 **
   85898 ** The third and fourth arguments to the auth function are the name of
   85899 ** the table and the column that are being accessed.  The auth function
   85900 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
   85901 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
   85902 ** means that the SQL statement will never-run - the sqlite3_exec() call
   85903 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
   85904 ** should run but attempts to read the specified column will return NULL
   85905 ** and attempts to write the column will be ignored.
   85906 **
   85907 ** Setting the auth function to NULL disables this hook.  The default
   85908 ** setting of the auth function is NULL.
   85909 */
   85910 SQLITE_API int sqlite3_set_authorizer(
   85911   sqlite3 *db,
   85912   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   85913   void *pArg
   85914 ){
   85915   sqlite3_mutex_enter(db->mutex);
   85916   db->xAuth = xAuth;
   85917   db->pAuthArg = pArg;
   85918   sqlite3ExpirePreparedStatements(db);
   85919   sqlite3_mutex_leave(db->mutex);
   85920   return SQLITE_OK;
   85921 }
   85922 
   85923 /*
   85924 ** Write an error message into pParse->zErrMsg that explains that the
   85925 ** user-supplied authorization function returned an illegal value.
   85926 */
   85927 static void sqliteAuthBadReturnCode(Parse *pParse){
   85928   sqlite3ErrorMsg(pParse, "authorizer malfunction");
   85929   pParse->rc = SQLITE_ERROR;
   85930 }
   85931 
   85932 /*
   85933 ** Invoke the authorization callback for permission to read column zCol from
   85934 ** table zTab in database zDb. This function assumes that an authorization
   85935 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
   85936 **
   85937 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
   85938 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
   85939 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
   85940 */
   85941 SQLITE_PRIVATE int sqlite3AuthReadCol(
   85942   Parse *pParse,                  /* The parser context */
   85943   const char *zTab,               /* Table name */
   85944   const char *zCol,               /* Column name */
   85945   int iDb                         /* Index of containing database. */
   85946 ){
   85947   sqlite3 *db = pParse->db;       /* Database handle */
   85948   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
   85949   int rc;                         /* Auth callback return code */
   85950 
   85951   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
   85952   if( rc==SQLITE_DENY ){
   85953     if( db->nDb>2 || iDb!=0 ){
   85954       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
   85955     }else{
   85956       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
   85957     }
   85958     pParse->rc = SQLITE_AUTH;
   85959   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
   85960     sqliteAuthBadReturnCode(pParse);
   85961   }
   85962   return rc;
   85963 }
   85964 
   85965 /*
   85966 ** The pExpr should be a TK_COLUMN expression.  The table referred to
   85967 ** is in pTabList or else it is the NEW or OLD table of a trigger.
   85968 ** Check to see if it is OK to read this particular column.
   85969 **
   85970 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
   85971 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
   85972 ** then generate an error.
   85973 */
   85974 SQLITE_PRIVATE void sqlite3AuthRead(
   85975   Parse *pParse,        /* The parser context */
   85976   Expr *pExpr,          /* The expression to check authorization on */
   85977   Schema *pSchema,      /* The schema of the expression */
   85978   SrcList *pTabList     /* All table that pExpr might refer to */
   85979 ){
   85980   sqlite3 *db = pParse->db;
   85981   Table *pTab = 0;      /* The table being read */
   85982   const char *zCol;     /* Name of the column of the table */
   85983   int iSrc;             /* Index in pTabList->a[] of table being read */
   85984   int iDb;              /* The index of the database the expression refers to */
   85985   int iCol;             /* Index of column in table */
   85986 
   85987   if( db->xAuth==0 ) return;
   85988   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   85989   if( iDb<0 ){
   85990     /* An attempt to read a column out of a subquery or other
   85991     ** temporary table. */
   85992     return;
   85993   }
   85994 
   85995   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
   85996   if( pExpr->op==TK_TRIGGER ){
   85997     pTab = pParse->pTriggerTab;
   85998   }else{
   85999     assert( pTabList );
   86000     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
   86001       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
   86002         pTab = pTabList->a[iSrc].pTab;
   86003         break;
   86004       }
   86005     }
   86006   }
   86007   iCol = pExpr->iColumn;
   86008   if( NEVER(pTab==0) ) return;
   86009 
   86010   if( iCol>=0 ){
   86011     assert( iCol<pTab->nCol );
   86012     zCol = pTab->aCol[iCol].zName;
   86013   }else if( pTab->iPKey>=0 ){
   86014     assert( pTab->iPKey<pTab->nCol );
   86015     zCol = pTab->aCol[pTab->iPKey].zName;
   86016   }else{
   86017     zCol = "ROWID";
   86018   }
   86019   assert( iDb>=0 && iDb<db->nDb );
   86020   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
   86021     pExpr->op = TK_NULL;
   86022   }
   86023 }
   86024 
   86025 /*
   86026 ** Do an authorization check using the code and arguments given.  Return
   86027 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
   86028 ** is returned, then the error count and error message in pParse are
   86029 ** modified appropriately.
   86030 */
   86031 SQLITE_PRIVATE int sqlite3AuthCheck(
   86032   Parse *pParse,
   86033   int code,
   86034   const char *zArg1,
   86035   const char *zArg2,
   86036   const char *zArg3
   86037 ){
   86038   sqlite3 *db = pParse->db;
   86039   int rc;
   86040 
   86041   /* Don't do any authorization checks if the database is initialising
   86042   ** or if the parser is being invoked from within sqlite3_declare_vtab.
   86043   */
   86044   if( db->init.busy || IN_DECLARE_VTAB ){
   86045     return SQLITE_OK;
   86046   }
   86047 
   86048   if( db->xAuth==0 ){
   86049     return SQLITE_OK;
   86050   }
   86051   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
   86052   if( rc==SQLITE_DENY ){
   86053     sqlite3ErrorMsg(pParse, "not authorized");
   86054     pParse->rc = SQLITE_AUTH;
   86055   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
   86056     rc = SQLITE_DENY;
   86057     sqliteAuthBadReturnCode(pParse);
   86058   }
   86059   return rc;
   86060 }
   86061 
   86062 /*
   86063 ** Push an authorization context.  After this routine is called, the
   86064 ** zArg3 argument to authorization callbacks will be zContext until
   86065 ** popped.  Or if pParse==0, this routine is a no-op.
   86066 */
   86067 SQLITE_PRIVATE void sqlite3AuthContextPush(
   86068   Parse *pParse,
   86069   AuthContext *pContext,
   86070   const char *zContext
   86071 ){
   86072   assert( pParse );
   86073   pContext->pParse = pParse;
   86074   pContext->zAuthContext = pParse->zAuthContext;
   86075   pParse->zAuthContext = zContext;
   86076 }
   86077 
   86078 /*
   86079 ** Pop an authorization context that was previously pushed
   86080 ** by sqlite3AuthContextPush
   86081 */
   86082 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
   86083   if( pContext->pParse ){
   86084     pContext->pParse->zAuthContext = pContext->zAuthContext;
   86085     pContext->pParse = 0;
   86086   }
   86087 }
   86088 
   86089 #endif /* SQLITE_OMIT_AUTHORIZATION */
   86090 
   86091 /************** End of auth.c ************************************************/
   86092 /************** Begin file build.c *******************************************/
   86093 /*
   86094 ** 2001 September 15
   86095 **
   86096 ** The author disclaims copyright to this source code.  In place of
   86097 ** a legal notice, here is a blessing:
   86098 **
   86099 **    May you do good and not evil.
   86100 **    May you find forgiveness for yourself and forgive others.
   86101 **    May you share freely, never taking more than you give.
   86102 **
   86103 *************************************************************************
   86104 ** This file contains C code routines that are called by the SQLite parser
   86105 ** when syntax rules are reduced.  The routines in this file handle the
   86106 ** following kinds of SQL syntax:
   86107 **
   86108 **     CREATE TABLE
   86109 **     DROP TABLE
   86110 **     CREATE INDEX
   86111 **     DROP INDEX
   86112 **     creating ID lists
   86113 **     BEGIN TRANSACTION
   86114 **     COMMIT
   86115 **     ROLLBACK
   86116 */
   86117 
   86118 /*
   86119 ** This routine is called when a new SQL statement is beginning to
   86120 ** be parsed.  Initialize the pParse structure as needed.
   86121 */
   86122 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
   86123   pParse->explain = (u8)explainFlag;
   86124   pParse->nVar = 0;
   86125 }
   86126 
   86127 #ifndef SQLITE_OMIT_SHARED_CACHE
   86128 /*
   86129 ** The TableLock structure is only used by the sqlite3TableLock() and
   86130 ** codeTableLocks() functions.
   86131 */
   86132 struct TableLock {
   86133   int iDb;             /* The database containing the table to be locked */
   86134   int iTab;            /* The root page of the table to be locked */
   86135   u8 isWriteLock;      /* True for write lock.  False for a read lock */
   86136   const char *zName;   /* Name of the table */
   86137 };
   86138 
   86139 /*
   86140 ** Record the fact that we want to lock a table at run-time.
   86141 **
   86142 ** The table to be locked has root page iTab and is found in database iDb.
   86143 ** A read or a write lock can be taken depending on isWritelock.
   86144 **
   86145 ** This routine just records the fact that the lock is desired.  The
   86146 ** code to make the lock occur is generated by a later call to
   86147 ** codeTableLocks() which occurs during sqlite3FinishCoding().
   86148 */
   86149 SQLITE_PRIVATE void sqlite3TableLock(
   86150   Parse *pParse,     /* Parsing context */
   86151   int iDb,           /* Index of the database containing the table to lock */
   86152   int iTab,          /* Root page number of the table to be locked */
   86153   u8 isWriteLock,    /* True for a write lock */
   86154   const char *zName  /* Name of the table to be locked */
   86155 ){
   86156   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   86157   int i;
   86158   int nBytes;
   86159   TableLock *p;
   86160   assert( iDb>=0 );
   86161 
   86162   for(i=0; i<pToplevel->nTableLock; i++){
   86163     p = &pToplevel->aTableLock[i];
   86164     if( p->iDb==iDb && p->iTab==iTab ){
   86165       p->isWriteLock = (p->isWriteLock || isWriteLock);
   86166       return;
   86167     }
   86168   }
   86169 
   86170   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
   86171   pToplevel->aTableLock =
   86172       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
   86173   if( pToplevel->aTableLock ){
   86174     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
   86175     p->iDb = iDb;
   86176     p->iTab = iTab;
   86177     p->isWriteLock = isWriteLock;
   86178     p->zName = zName;
   86179   }else{
   86180     pToplevel->nTableLock = 0;
   86181     pToplevel->db->mallocFailed = 1;
   86182   }
   86183 }
   86184 
   86185 /*
   86186 ** Code an OP_TableLock instruction for each table locked by the
   86187 ** statement (configured by calls to sqlite3TableLock()).
   86188 */
   86189 static void codeTableLocks(Parse *pParse){
   86190   int i;
   86191   Vdbe *pVdbe;
   86192 
   86193   pVdbe = sqlite3GetVdbe(pParse);
   86194   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
   86195 
   86196   for(i=0; i<pParse->nTableLock; i++){
   86197     TableLock *p = &pParse->aTableLock[i];
   86198     int p1 = p->iDb;
   86199     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   86200                       p->zName, P4_STATIC);
   86201   }
   86202 }
   86203 #else
   86204   #define codeTableLocks(x)
   86205 #endif
   86206 
   86207 /*
   86208 ** Return TRUE if the given yDbMask object is empty - if it contains no
   86209 ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
   86210 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
   86211 */
   86212 #if SQLITE_MAX_ATTACHED>30
   86213 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
   86214   int i;
   86215   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
   86216   return 1;
   86217 }
   86218 #endif
   86219 
   86220 /*
   86221 ** This routine is called after a single SQL statement has been
   86222 ** parsed and a VDBE program to execute that statement has been
   86223 ** prepared.  This routine puts the finishing touches on the
   86224 ** VDBE program and resets the pParse structure for the next
   86225 ** parse.
   86226 **
   86227 ** Note that if an error occurred, it might be the case that
   86228 ** no VDBE code was generated.
   86229 */
   86230 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
   86231   sqlite3 *db;
   86232   Vdbe *v;
   86233 
   86234   assert( pParse->pToplevel==0 );
   86235   db = pParse->db;
   86236   if( db->mallocFailed ) return;
   86237   if( pParse->nested ) return;
   86238   if( pParse->nErr ) return;
   86239 
   86240   /* Begin by generating some termination code at the end of the
   86241   ** vdbe program
   86242   */
   86243   v = sqlite3GetVdbe(pParse);
   86244   assert( !pParse->isMultiWrite
   86245        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   86246   if( v ){
   86247     while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
   86248     sqlite3VdbeAddOp0(v, OP_Halt);
   86249 
   86250     /* The cookie mask contains one bit for each database file open.
   86251     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   86252     ** set for each database that is used.  Generate code to start a
   86253     ** transaction on each used database and to verify the schema cookie
   86254     ** on each used database.
   86255     */
   86256     if( db->mallocFailed==0
   86257      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
   86258     ){
   86259       int iDb, i;
   86260       assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
   86261       sqlite3VdbeJumpHere(v, 0);
   86262       for(iDb=0; iDb<db->nDb; iDb++){
   86263         if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
   86264         sqlite3VdbeUsesBtree(v, iDb);
   86265         sqlite3VdbeAddOp4Int(v,
   86266           OP_Transaction,                    /* Opcode */
   86267           iDb,                               /* P1 */
   86268           DbMaskTest(pParse->writeMask,iDb), /* P2 */
   86269           pParse->cookieValue[iDb],          /* P3 */
   86270           db->aDb[iDb].pSchema->iGeneration  /* P4 */
   86271         );
   86272         if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
   86273       }
   86274 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86275       for(i=0; i<pParse->nVtabLock; i++){
   86276         char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   86277         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   86278       }
   86279       pParse->nVtabLock = 0;
   86280 #endif
   86281 
   86282       /* Once all the cookies have been verified and transactions opened,
   86283       ** obtain the required table-locks. This is a no-op unless the
   86284       ** shared-cache feature is enabled.
   86285       */
   86286       codeTableLocks(pParse);
   86287 
   86288       /* Initialize any AUTOINCREMENT data structures required.
   86289       */
   86290       sqlite3AutoincrementBegin(pParse);
   86291 
   86292       /* Code constant expressions that where factored out of inner loops */
   86293       if( pParse->pConstExpr ){
   86294         ExprList *pEL = pParse->pConstExpr;
   86295         pParse->okConstFactor = 0;
   86296         for(i=0; i<pEL->nExpr; i++){
   86297           sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
   86298         }
   86299       }
   86300 
   86301       /* Finally, jump back to the beginning of the executable code. */
   86302       sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
   86303     }
   86304   }
   86305 
   86306 
   86307   /* Get the VDBE program ready for execution
   86308   */
   86309   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
   86310     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   86311     /* A minimum of one cursor is required if autoincrement is used
   86312     *  See ticket [a696379c1f08866] */
   86313     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
   86314     sqlite3VdbeMakeReady(v, pParse);
   86315     pParse->rc = SQLITE_DONE;
   86316     pParse->colNamesSet = 0;
   86317   }else{
   86318     pParse->rc = SQLITE_ERROR;
   86319   }
   86320   pParse->nTab = 0;
   86321   pParse->nMem = 0;
   86322   pParse->nSet = 0;
   86323   pParse->nVar = 0;
   86324   DbMaskZero(pParse->cookieMask);
   86325 }
   86326 
   86327 /*
   86328 ** Run the parser and code generator recursively in order to generate
   86329 ** code for the SQL statement given onto the end of the pParse context
   86330 ** currently under construction.  When the parser is run recursively
   86331 ** this way, the final OP_Halt is not appended and other initialization
   86332 ** and finalization steps are omitted because those are handling by the
   86333 ** outermost parser.
   86334 **
   86335 ** Not everything is nestable.  This facility is designed to permit
   86336 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   86337 ** care if you decide to try to use this routine for some other purposes.
   86338 */
   86339 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   86340   va_list ap;
   86341   char *zSql;
   86342   char *zErrMsg = 0;
   86343   sqlite3 *db = pParse->db;
   86344 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
   86345   char saveBuf[SAVE_SZ];
   86346 
   86347   if( pParse->nErr ) return;
   86348   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   86349   va_start(ap, zFormat);
   86350   zSql = sqlite3VMPrintf(db, zFormat, ap);
   86351   va_end(ap);
   86352   if( zSql==0 ){
   86353     return;   /* A malloc must have failed */
   86354   }
   86355   pParse->nested++;
   86356   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   86357   memset(&pParse->nVar, 0, SAVE_SZ);
   86358   sqlite3RunParser(pParse, zSql, &zErrMsg);
   86359   sqlite3DbFree(db, zErrMsg);
   86360   sqlite3DbFree(db, zSql);
   86361   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
   86362   pParse->nested--;
   86363 }
   86364 
   86365 /*
   86366 ** Locate the in-memory structure that describes a particular database
   86367 ** table given the name of that table and (optionally) the name of the
   86368 ** database containing the table.  Return NULL if not found.
   86369 **
   86370 ** If zDatabase is 0, all databases are searched for the table and the
   86371 ** first matching table is returned.  (No checking for duplicate table
   86372 ** names is done.)  The search order is TEMP first, then MAIN, then any
   86373 ** auxiliary databases added using the ATTACH command.
   86374 **
   86375 ** See also sqlite3LocateTable().
   86376 */
   86377 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   86378   Table *p = 0;
   86379   int i;
   86380   int nName;
   86381   assert( zName!=0 );
   86382   nName = sqlite3Strlen30(zName);
   86383   /* All mutexes are required for schema access.  Make sure we hold them. */
   86384   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   86385   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   86386     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   86387     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   86388     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   86389     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
   86390     if( p ) break;
   86391   }
   86392   return p;
   86393 }
   86394 
   86395 /*
   86396 ** Locate the in-memory structure that describes a particular database
   86397 ** table given the name of that table and (optionally) the name of the
   86398 ** database containing the table.  Return NULL if not found.  Also leave an
   86399 ** error message in pParse->zErrMsg.
   86400 **
   86401 ** The difference between this routine and sqlite3FindTable() is that this
   86402 ** routine leaves an error message in pParse->zErrMsg where
   86403 ** sqlite3FindTable() does not.
   86404 */
   86405 SQLITE_PRIVATE Table *sqlite3LocateTable(
   86406   Parse *pParse,         /* context in which to report errors */
   86407   int isView,            /* True if looking for a VIEW rather than a TABLE */
   86408   const char *zName,     /* Name of the table we are looking for */
   86409   const char *zDbase     /* Name of the database.  Might be NULL */
   86410 ){
   86411   Table *p;
   86412 
   86413   /* Read the database schema. If an error occurs, leave an error message
   86414   ** and code in pParse and return NULL. */
   86415   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   86416     return 0;
   86417   }
   86418 
   86419   p = sqlite3FindTable(pParse->db, zName, zDbase);
   86420   if( p==0 ){
   86421     const char *zMsg = isView ? "no such view" : "no such table";
   86422     if( zDbase ){
   86423       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   86424     }else{
   86425       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   86426     }
   86427     pParse->checkSchema = 1;
   86428   }
   86429   return p;
   86430 }
   86431 
   86432 /*
   86433 ** Locate the table identified by *p.
   86434 **
   86435 ** This is a wrapper around sqlite3LocateTable(). The difference between
   86436 ** sqlite3LocateTable() and this function is that this function restricts
   86437 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
   86438 ** non-NULL if it is part of a view or trigger program definition. See
   86439 ** sqlite3FixSrcList() for details.
   86440 */
   86441 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
   86442   Parse *pParse,
   86443   int isView,
   86444   struct SrcList_item *p
   86445 ){
   86446   const char *zDb;
   86447   assert( p->pSchema==0 || p->zDatabase==0 );
   86448   if( p->pSchema ){
   86449     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
   86450     zDb = pParse->db->aDb[iDb].zName;
   86451   }else{
   86452     zDb = p->zDatabase;
   86453   }
   86454   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
   86455 }
   86456 
   86457 /*
   86458 ** Locate the in-memory structure that describes
   86459 ** a particular index given the name of that index
   86460 ** and the name of the database that contains the index.
   86461 ** Return NULL if not found.
   86462 **
   86463 ** If zDatabase is 0, all databases are searched for the
   86464 ** table and the first matching index is returned.  (No checking
   86465 ** for duplicate index names is done.)  The search order is
   86466 ** TEMP first, then MAIN, then any auxiliary databases added
   86467 ** using the ATTACH command.
   86468 */
   86469 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   86470   Index *p = 0;
   86471   int i;
   86472   int nName = sqlite3Strlen30(zName);
   86473   /* All mutexes are required for schema access.  Make sure we hold them. */
   86474   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   86475   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   86476     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   86477     Schema *pSchema = db->aDb[j].pSchema;
   86478     assert( pSchema );
   86479     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   86480     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   86481     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
   86482     if( p ) break;
   86483   }
   86484   return p;
   86485 }
   86486 
   86487 /*
   86488 ** Reclaim the memory used by an index
   86489 */
   86490 static void freeIndex(sqlite3 *db, Index *p){
   86491 #ifndef SQLITE_OMIT_ANALYZE
   86492   sqlite3DeleteIndexSamples(db, p);
   86493 #endif
   86494   if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
   86495   sqlite3ExprDelete(db, p->pPartIdxWhere);
   86496   sqlite3DbFree(db, p->zColAff);
   86497   if( p->isResized ) sqlite3DbFree(db, p->azColl);
   86498   sqlite3DbFree(db, p);
   86499 }
   86500 
   86501 /*
   86502 ** For the index called zIdxName which is found in the database iDb,
   86503 ** unlike that index from its Table then remove the index from
   86504 ** the index hash table and free all memory structures associated
   86505 ** with the index.
   86506 */
   86507 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   86508   Index *pIndex;
   86509   int len;
   86510   Hash *pHash;
   86511 
   86512   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   86513   pHash = &db->aDb[iDb].pSchema->idxHash;
   86514   len = sqlite3Strlen30(zIdxName);
   86515   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
   86516   if( ALWAYS(pIndex) ){
   86517     if( pIndex->pTable->pIndex==pIndex ){
   86518       pIndex->pTable->pIndex = pIndex->pNext;
   86519     }else{
   86520       Index *p;
   86521       /* Justification of ALWAYS();  The index must be on the list of
   86522       ** indices. */
   86523       p = pIndex->pTable->pIndex;
   86524       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
   86525       if( ALWAYS(p && p->pNext==pIndex) ){
   86526         p->pNext = pIndex->pNext;
   86527       }
   86528     }
   86529     freeIndex(db, pIndex);
   86530   }
   86531   db->flags |= SQLITE_InternChanges;
   86532 }
   86533 
   86534 /*
   86535 ** Look through the list of open database files in db->aDb[] and if
   86536 ** any have been closed, remove them from the list.  Reallocate the
   86537 ** db->aDb[] structure to a smaller size, if possible.
   86538 **
   86539 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
   86540 ** are never candidates for being collapsed.
   86541 */
   86542 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
   86543   int i, j;
   86544   for(i=j=2; i<db->nDb; i++){
   86545     struct Db *pDb = &db->aDb[i];
   86546     if( pDb->pBt==0 ){
   86547       sqlite3DbFree(db, pDb->zName);
   86548       pDb->zName = 0;
   86549       continue;
   86550     }
   86551     if( j<i ){
   86552       db->aDb[j] = db->aDb[i];
   86553     }
   86554     j++;
   86555   }
   86556   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
   86557   db->nDb = j;
   86558   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   86559     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   86560     sqlite3DbFree(db, db->aDb);
   86561     db->aDb = db->aDbStatic;
   86562   }
   86563 }
   86564 
   86565 /*
   86566 ** Reset the schema for the database at index iDb.  Also reset the
   86567 ** TEMP schema.
   86568 */
   86569 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
   86570   Db *pDb;
   86571   assert( iDb<db->nDb );
   86572 
   86573   /* Case 1:  Reset the single schema identified by iDb */
   86574   pDb = &db->aDb[iDb];
   86575   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   86576   assert( pDb->pSchema!=0 );
   86577   sqlite3SchemaClear(pDb->pSchema);
   86578 
   86579   /* If any database other than TEMP is reset, then also reset TEMP
   86580   ** since TEMP might be holding triggers that reference tables in the
   86581   ** other database.
   86582   */
   86583   if( iDb!=1 ){
   86584     pDb = &db->aDb[1];
   86585     assert( pDb->pSchema!=0 );
   86586     sqlite3SchemaClear(pDb->pSchema);
   86587   }
   86588   return;
   86589 }
   86590 
   86591 /*
   86592 ** Erase all schema information from all attached databases (including
   86593 ** "main" and "temp") for a single database connection.
   86594 */
   86595 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
   86596   int i;
   86597   sqlite3BtreeEnterAll(db);
   86598   for(i=0; i<db->nDb; i++){
   86599     Db *pDb = &db->aDb[i];
   86600     if( pDb->pSchema ){
   86601       sqlite3SchemaClear(pDb->pSchema);
   86602     }
   86603   }
   86604   db->flags &= ~SQLITE_InternChanges;
   86605   sqlite3VtabUnlockList(db);
   86606   sqlite3BtreeLeaveAll(db);
   86607   sqlite3CollapseDatabaseArray(db);
   86608 }
   86609 
   86610 /*
   86611 ** This routine is called when a commit occurs.
   86612 */
   86613 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
   86614   db->flags &= ~SQLITE_InternChanges;
   86615 }
   86616 
   86617 /*
   86618 ** Delete memory allocated for the column names of a table or view (the
   86619 ** Table.aCol[] array).
   86620 */
   86621 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
   86622   int i;
   86623   Column *pCol;
   86624   assert( pTable!=0 );
   86625   if( (pCol = pTable->aCol)!=0 ){
   86626     for(i=0; i<pTable->nCol; i++, pCol++){
   86627       sqlite3DbFree(db, pCol->zName);
   86628       sqlite3ExprDelete(db, pCol->pDflt);
   86629       sqlite3DbFree(db, pCol->zDflt);
   86630       sqlite3DbFree(db, pCol->zType);
   86631       sqlite3DbFree(db, pCol->zColl);
   86632     }
   86633     sqlite3DbFree(db, pTable->aCol);
   86634   }
   86635 }
   86636 
   86637 /*
   86638 ** Remove the memory data structures associated with the given
   86639 ** Table.  No changes are made to disk by this routine.
   86640 **
   86641 ** This routine just deletes the data structure.  It does not unlink
   86642 ** the table data structure from the hash table.  But it does destroy
   86643 ** memory structures of the indices and foreign keys associated with
   86644 ** the table.
   86645 **
   86646 ** The db parameter is optional.  It is needed if the Table object
   86647 ** contains lookaside memory.  (Table objects in the schema do not use
   86648 ** lookaside memory, but some ephemeral Table objects do.)  Or the
   86649 ** db parameter can be used with db->pnBytesFreed to measure the memory
   86650 ** used by the Table object.
   86651 */
   86652 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
   86653   Index *pIndex, *pNext;
   86654   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
   86655 
   86656   assert( !pTable || pTable->nRef>0 );
   86657 
   86658   /* Do not delete the table until the reference count reaches zero. */
   86659   if( !pTable ) return;
   86660   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
   86661 
   86662   /* Record the number of outstanding lookaside allocations in schema Tables
   86663   ** prior to doing any free() operations.  Since schema Tables do not use
   86664   ** lookaside, this number should not change. */
   86665   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
   86666                          db->lookaside.nOut : 0 );
   86667 
   86668   /* Delete all indices associated with this table. */
   86669   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   86670     pNext = pIndex->pNext;
   86671     assert( pIndex->pSchema==pTable->pSchema );
   86672     if( !db || db->pnBytesFreed==0 ){
   86673       char *zName = pIndex->zName;
   86674       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
   86675          &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
   86676       );
   86677       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   86678       assert( pOld==pIndex || pOld==0 );
   86679     }
   86680     freeIndex(db, pIndex);
   86681   }
   86682 
   86683   /* Delete any foreign keys attached to this table. */
   86684   sqlite3FkDelete(db, pTable);
   86685 
   86686   /* Delete the Table structure itself.
   86687   */
   86688   sqliteDeleteColumnNames(db, pTable);
   86689   sqlite3DbFree(db, pTable->zName);
   86690   sqlite3DbFree(db, pTable->zColAff);
   86691   sqlite3SelectDelete(db, pTable->pSelect);
   86692 #ifndef SQLITE_OMIT_CHECK
   86693   sqlite3ExprListDelete(db, pTable->pCheck);
   86694 #endif
   86695 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86696   sqlite3VtabClear(db, pTable);
   86697 #endif
   86698   sqlite3DbFree(db, pTable);
   86699 
   86700   /* Verify that no lookaside memory was used by schema tables */
   86701   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
   86702 }
   86703 
   86704 /*
   86705 ** Unlink the given table from the hash tables and the delete the
   86706 ** table structure with all its indices and foreign keys.
   86707 */
   86708 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   86709   Table *p;
   86710   Db *pDb;
   86711 
   86712   assert( db!=0 );
   86713   assert( iDb>=0 && iDb<db->nDb );
   86714   assert( zTabName );
   86715   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   86716   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
   86717   pDb = &db->aDb[iDb];
   86718   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
   86719                         sqlite3Strlen30(zTabName),0);
   86720   sqlite3DeleteTable(db, p);
   86721   db->flags |= SQLITE_InternChanges;
   86722 }
   86723 
   86724 /*
   86725 ** Given a token, return a string that consists of the text of that
   86726 ** token.  Space to hold the returned string
   86727 ** is obtained from sqliteMalloc() and must be freed by the calling
   86728 ** function.
   86729 **
   86730 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
   86731 ** surround the body of the token are removed.
   86732 **
   86733 ** Tokens are often just pointers into the original SQL text and so
   86734 ** are not \000 terminated and are not persistent.  The returned string
   86735 ** is \000 terminated and is persistent.
   86736 */
   86737 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   86738   char *zName;
   86739   if( pName ){
   86740     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   86741     sqlite3Dequote(zName);
   86742   }else{
   86743     zName = 0;
   86744   }
   86745   return zName;
   86746 }
   86747 
   86748 /*
   86749 ** Open the sqlite_master table stored in database number iDb for
   86750 ** writing. The table is opened using cursor 0.
   86751 */
   86752 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
   86753   Vdbe *v = sqlite3GetVdbe(p);
   86754   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   86755   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
   86756   if( p->nTab==0 ){
   86757     p->nTab = 1;
   86758   }
   86759 }
   86760 
   86761 /*
   86762 ** Parameter zName points to a nul-terminated buffer containing the name
   86763 ** of a database ("main", "temp" or the name of an attached db). This
   86764 ** function returns the index of the named database in db->aDb[], or
   86765 ** -1 if the named db cannot be found.
   86766 */
   86767 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
   86768   int i = -1;         /* Database number */
   86769   if( zName ){
   86770     Db *pDb;
   86771     int n = sqlite3Strlen30(zName);
   86772     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   86773       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
   86774           0==sqlite3StrICmp(pDb->zName, zName) ){
   86775         break;
   86776       }
   86777     }
   86778   }
   86779   return i;
   86780 }
   86781 
   86782 /*
   86783 ** The token *pName contains the name of a database (either "main" or
   86784 ** "temp" or the name of an attached db). This routine returns the
   86785 ** index of the named database in db->aDb[], or -1 if the named db
   86786 ** does not exist.
   86787 */
   86788 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
   86789   int i;                               /* Database number */
   86790   char *zName;                         /* Name we are searching for */
   86791   zName = sqlite3NameFromToken(db, pName);
   86792   i = sqlite3FindDbName(db, zName);
   86793   sqlite3DbFree(db, zName);
   86794   return i;
   86795 }
   86796 
   86797 /* The table or view or trigger name is passed to this routine via tokens
   86798 ** pName1 and pName2. If the table name was fully qualified, for example:
   86799 **
   86800 ** CREATE TABLE xxx.yyy (...);
   86801 **
   86802 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   86803 ** the table name is not fully qualified, i.e.:
   86804 **
   86805 ** CREATE TABLE yyy(...);
   86806 **
   86807 ** Then pName1 is set to "yyy" and pName2 is "".
   86808 **
   86809 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   86810 ** pName2) that stores the unqualified table name.  The index of the
   86811 ** database "xxx" is returned.
   86812 */
   86813 SQLITE_PRIVATE int sqlite3TwoPartName(
   86814   Parse *pParse,      /* Parsing and code generating context */
   86815   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   86816   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   86817   Token **pUnqual     /* Write the unqualified object name here */
   86818 ){
   86819   int iDb;                    /* Database holding the object */
   86820   sqlite3 *db = pParse->db;
   86821 
   86822   if( ALWAYS(pName2!=0) && pName2->n>0 ){
   86823     if( db->init.busy ) {
   86824       sqlite3ErrorMsg(pParse, "corrupt database");
   86825       pParse->nErr++;
   86826       return -1;
   86827     }
   86828     *pUnqual = pName2;
   86829     iDb = sqlite3FindDb(db, pName1);
   86830     if( iDb<0 ){
   86831       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   86832       pParse->nErr++;
   86833       return -1;
   86834     }
   86835   }else{
   86836     assert( db->init.iDb==0 || db->init.busy );
   86837     iDb = db->init.iDb;
   86838     *pUnqual = pName1;
   86839   }
   86840   return iDb;
   86841 }
   86842 
   86843 /*
   86844 ** This routine is used to check if the UTF-8 string zName is a legal
   86845 ** unqualified name for a new schema object (table, index, view or
   86846 ** trigger). All names are legal except those that begin with the string
   86847 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   86848 ** is reserved for internal use.
   86849 */
   86850 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   86851   if( !pParse->db->init.busy && pParse->nested==0
   86852           && (pParse->db->flags & SQLITE_WriteSchema)==0
   86853           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   86854     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   86855     return SQLITE_ERROR;
   86856   }
   86857   return SQLITE_OK;
   86858 }
   86859 
   86860 /*
   86861 ** Return the PRIMARY KEY index of a table
   86862 */
   86863 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
   86864   Index *p;
   86865   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
   86866   return p;
   86867 }
   86868 
   86869 /*
   86870 ** Return the column of index pIdx that corresponds to table
   86871 ** column iCol.  Return -1 if not found.
   86872 */
   86873 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
   86874   int i;
   86875   for(i=0; i<pIdx->nColumn; i++){
   86876     if( iCol==pIdx->aiColumn[i] ) return i;
   86877   }
   86878   return -1;
   86879 }
   86880 
   86881 /*
   86882 ** Begin constructing a new table representation in memory.  This is
   86883 ** the first of several action routines that get called in response
   86884 ** to a CREATE TABLE statement.  In particular, this routine is called
   86885 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   86886 ** flag is true if the table should be stored in the auxiliary database
   86887 ** file instead of in the main database file.  This is normally the case
   86888 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
   86889 ** CREATE and TABLE.
   86890 **
   86891 ** The new table record is initialized and put in pParse->pNewTable.
   86892 ** As more of the CREATE TABLE statement is parsed, additional action
   86893 ** routines will be called to add more information to this record.
   86894 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   86895 ** is called to complete the construction of the new table record.
   86896 */
   86897 SQLITE_PRIVATE void sqlite3StartTable(
   86898   Parse *pParse,   /* Parser context */
   86899   Token *pName1,   /* First part of the name of the table or view */
   86900   Token *pName2,   /* Second part of the name of the table or view */
   86901   int isTemp,      /* True if this is a TEMP table */
   86902   int isView,      /* True if this is a VIEW */
   86903   int isVirtual,   /* True if this is a VIRTUAL table */
   86904   int noErr        /* Do nothing if table already exists */
   86905 ){
   86906   Table *pTable;
   86907   char *zName = 0; /* The name of the new table */
   86908   sqlite3 *db = pParse->db;
   86909   Vdbe *v;
   86910   int iDb;         /* Database number to create the table in */
   86911   Token *pName;    /* Unqualified name of the table to create */
   86912 
   86913   /* The table or view name to create is passed to this routine via tokens
   86914   ** pName1 and pName2. If the table name was fully qualified, for example:
   86915   **
   86916   ** CREATE TABLE xxx.yyy (...);
   86917   **
   86918   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   86919   ** the table name is not fully qualified, i.e.:
   86920   **
   86921   ** CREATE TABLE yyy(...);
   86922   **
   86923   ** Then pName1 is set to "yyy" and pName2 is "".
   86924   **
   86925   ** The call below sets the pName pointer to point at the token (pName1 or
   86926   ** pName2) that stores the unqualified table name. The variable iDb is
   86927   ** set to the index of the database that the table or view is to be
   86928   ** created in.
   86929   */
   86930   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   86931   if( iDb<0 ) return;
   86932   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
   86933     /* If creating a temp table, the name may not be qualified. Unless
   86934     ** the database name is "temp" anyway.  */
   86935     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   86936     return;
   86937   }
   86938   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   86939 
   86940   pParse->sNameToken = *pName;
   86941   zName = sqlite3NameFromToken(db, pName);
   86942   if( zName==0 ) return;
   86943   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   86944     goto begin_table_error;
   86945   }
   86946   if( db->init.iDb==1 ) isTemp = 1;
   86947 #ifndef SQLITE_OMIT_AUTHORIZATION
   86948   assert( (isTemp & 1)==isTemp );
   86949   {
   86950     int code;
   86951     char *zDb = db->aDb[iDb].zName;
   86952     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   86953       goto begin_table_error;
   86954     }
   86955     if( isView ){
   86956       if( !OMIT_TEMPDB && isTemp ){
   86957         code = SQLITE_CREATE_TEMP_VIEW;
   86958       }else{
   86959         code = SQLITE_CREATE_VIEW;
   86960       }
   86961     }else{
   86962       if( !OMIT_TEMPDB && isTemp ){
   86963         code = SQLITE_CREATE_TEMP_TABLE;
   86964       }else{
   86965         code = SQLITE_CREATE_TABLE;
   86966       }
   86967     }
   86968     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
   86969       goto begin_table_error;
   86970     }
   86971   }
   86972 #endif
   86973 
   86974   /* Make sure the new table name does not collide with an existing
   86975   ** index or table name in the same database.  Issue an error message if
   86976   ** it does. The exception is if the statement being parsed was passed
   86977   ** to an sqlite3_declare_vtab() call. In that case only the column names
   86978   ** and types will be used, so there is no need to test for namespace
   86979   ** collisions.
   86980   */
   86981   if( !IN_DECLARE_VTAB ){
   86982     char *zDb = db->aDb[iDb].zName;
   86983     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   86984       goto begin_table_error;
   86985     }
   86986     pTable = sqlite3FindTable(db, zName, zDb);
   86987     if( pTable ){
   86988       if( !noErr ){
   86989         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   86990       }else{
   86991         assert( !db->init.busy );
   86992         sqlite3CodeVerifySchema(pParse, iDb);
   86993       }
   86994       goto begin_table_error;
   86995     }
   86996     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
   86997       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   86998       goto begin_table_error;
   86999     }
   87000   }
   87001 
   87002   pTable = sqlite3DbMallocZero(db, sizeof(Table));
   87003   if( pTable==0 ){
   87004     db->mallocFailed = 1;
   87005     pParse->rc = SQLITE_NOMEM;
   87006     pParse->nErr++;
   87007     goto begin_table_error;
   87008   }
   87009   pTable->zName = zName;
   87010   pTable->iPKey = -1;
   87011   pTable->pSchema = db->aDb[iDb].pSchema;
   87012   pTable->nRef = 1;
   87013   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   87014   assert( pParse->pNewTable==0 );
   87015   pParse->pNewTable = pTable;
   87016 
   87017   /* If this is the magic sqlite_sequence table used by autoincrement,
   87018   ** then record a pointer to this table in the main database structure
   87019   ** so that INSERT can find the table easily.
   87020   */
   87021 #ifndef SQLITE_OMIT_AUTOINCREMENT
   87022   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   87023     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   87024     pTable->pSchema->pSeqTab = pTable;
   87025   }
   87026 #endif
   87027 
   87028   /* Begin generating the code that will insert the table record into
   87029   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   87030   ** and allocate the record number for the table entry now.  Before any
   87031   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   87032   ** indices to be created and the table record must come before the
   87033   ** indices.  Hence, the record number for the table must be allocated
   87034   ** now.
   87035   */
   87036   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   87037     int j1;
   87038     int fileFormat;
   87039     int reg1, reg2, reg3;
   87040     sqlite3BeginWriteOperation(pParse, 0, iDb);
   87041 
   87042 #ifndef SQLITE_OMIT_VIRTUALTABLE
   87043     if( isVirtual ){
   87044       sqlite3VdbeAddOp0(v, OP_VBegin);
   87045     }
   87046 #endif
   87047 
   87048     /* If the file format and encoding in the database have not been set,
   87049     ** set them now.
   87050     */
   87051     reg1 = pParse->regRowid = ++pParse->nMem;
   87052     reg2 = pParse->regRoot = ++pParse->nMem;
   87053     reg3 = ++pParse->nMem;
   87054     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   87055     sqlite3VdbeUsesBtree(v, iDb);
   87056     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
   87057     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   87058                   1 : SQLITE_MAX_FILE_FORMAT;
   87059     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
   87060     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
   87061     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
   87062     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
   87063     sqlite3VdbeJumpHere(v, j1);
   87064 
   87065     /* This just creates a place-holder record in the sqlite_master table.
   87066     ** The record created does not contain anything yet.  It will be replaced
   87067     ** by the real entry in code generated at sqlite3EndTable().
   87068     **
   87069     ** The rowid for the new entry is left in register pParse->regRowid.
   87070     ** The root page number of the new table is left in reg pParse->regRoot.
   87071     ** The rowid and root page number values are needed by the code that
   87072     ** sqlite3EndTable will generate.
   87073     */
   87074 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   87075     if( isView || isVirtual ){
   87076       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
   87077     }else
   87078 #endif
   87079     {
   87080       pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
   87081     }
   87082     sqlite3OpenMasterTable(pParse, iDb);
   87083     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
   87084     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
   87085     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
   87086     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   87087     sqlite3VdbeAddOp0(v, OP_Close);
   87088   }
   87089 
   87090   /* Normal (non-error) return. */
   87091   return;
   87092 
   87093   /* If an error occurs, we jump here */
   87094 begin_table_error:
   87095   sqlite3DbFree(db, zName);
   87096   return;
   87097 }
   87098 
   87099 /*
   87100 ** This macro is used to compare two strings in a case-insensitive manner.
   87101 ** It is slightly faster than calling sqlite3StrICmp() directly, but
   87102 ** produces larger code.
   87103 **
   87104 ** WARNING: This macro is not compatible with the strcmp() family. It
   87105 ** returns true if the two strings are equal, otherwise false.
   87106 */
   87107 #define STRICMP(x, y) (\
   87108 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
   87109 sqlite3UpperToLower[*(unsigned char *)(y)]     \
   87110 && sqlite3StrICmp((x)+1,(y)+1)==0 )
   87111 
   87112 /*
   87113 ** Add a new column to the table currently being constructed.
   87114 **
   87115 ** The parser calls this routine once for each column declaration
   87116 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
   87117 ** first to get things going.  Then this routine is called for each
   87118 ** column.
   87119 */
   87120 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
   87121   Table *p;
   87122   int i;
   87123   char *z;
   87124   Column *pCol;
   87125   sqlite3 *db = pParse->db;
   87126   if( (p = pParse->pNewTable)==0 ) return;
   87127 #if SQLITE_MAX_COLUMN
   87128   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   87129     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
   87130     return;
   87131   }
   87132 #endif
   87133   z = sqlite3NameFromToken(db, pName);
   87134   if( z==0 ) return;
   87135   for(i=0; i<p->nCol; i++){
   87136     if( STRICMP(z, p->aCol[i].zName) ){
   87137       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
   87138       sqlite3DbFree(db, z);
   87139       return;
   87140     }
   87141   }
   87142   if( (p->nCol & 0x7)==0 ){
   87143     Column *aNew;
   87144     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
   87145     if( aNew==0 ){
   87146       sqlite3DbFree(db, z);
   87147       return;
   87148     }
   87149     p->aCol = aNew;
   87150   }
   87151   pCol = &p->aCol[p->nCol];
   87152   memset(pCol, 0, sizeof(p->aCol[0]));
   87153   pCol->zName = z;
   87154 
   87155   /* If there is no type specified, columns have the default affinity
   87156   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
   87157   ** be called next to set pCol->affinity correctly.
   87158   */
   87159   pCol->affinity = SQLITE_AFF_NONE;
   87160   pCol->szEst = 1;
   87161   p->nCol++;
   87162 }
   87163 
   87164 /*
   87165 ** This routine is called by the parser while in the middle of
   87166 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
   87167 ** been seen on a column.  This routine sets the notNull flag on
   87168 ** the column currently under construction.
   87169 */
   87170 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
   87171   Table *p;
   87172   p = pParse->pNewTable;
   87173   if( p==0 || NEVER(p->nCol<1) ) return;
   87174   p->aCol[p->nCol-1].notNull = (u8)onError;
   87175 }
   87176 
   87177 /*
   87178 ** Scan the column type name zType (length nType) and return the
   87179 ** associated affinity type.
   87180 **
   87181 ** This routine does a case-independent search of zType for the
   87182 ** substrings in the following table. If one of the substrings is
   87183 ** found, the corresponding affinity is returned. If zType contains
   87184 ** more than one of the substrings, entries toward the top of
   87185 ** the table take priority. For example, if zType is 'BLOBINT',
   87186 ** SQLITE_AFF_INTEGER is returned.
   87187 **
   87188 ** Substring     | Affinity
   87189 ** --------------------------------
   87190 ** 'INT'         | SQLITE_AFF_INTEGER
   87191 ** 'CHAR'        | SQLITE_AFF_TEXT
   87192 ** 'CLOB'        | SQLITE_AFF_TEXT
   87193 ** 'TEXT'        | SQLITE_AFF_TEXT
   87194 ** 'BLOB'        | SQLITE_AFF_NONE
   87195 ** 'REAL'        | SQLITE_AFF_REAL
   87196 ** 'FLOA'        | SQLITE_AFF_REAL
   87197 ** 'DOUB'        | SQLITE_AFF_REAL
   87198 **
   87199 ** If none of the substrings in the above table are found,
   87200 ** SQLITE_AFF_NUMERIC is returned.
   87201 */
   87202 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
   87203   u32 h = 0;
   87204   char aff = SQLITE_AFF_NUMERIC;
   87205   const char *zChar = 0;
   87206 
   87207   if( zIn==0 ) return aff;
   87208   while( zIn[0] ){
   87209     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
   87210     zIn++;
   87211     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
   87212       aff = SQLITE_AFF_TEXT;
   87213       zChar = zIn;
   87214     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
   87215       aff = SQLITE_AFF_TEXT;
   87216     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
   87217       aff = SQLITE_AFF_TEXT;
   87218     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
   87219         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
   87220       aff = SQLITE_AFF_NONE;
   87221       if( zIn[0]=='(' ) zChar = zIn;
   87222 #ifndef SQLITE_OMIT_FLOATING_POINT
   87223     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
   87224         && aff==SQLITE_AFF_NUMERIC ){
   87225       aff = SQLITE_AFF_REAL;
   87226     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
   87227         && aff==SQLITE_AFF_NUMERIC ){
   87228       aff = SQLITE_AFF_REAL;
   87229     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
   87230         && aff==SQLITE_AFF_NUMERIC ){
   87231       aff = SQLITE_AFF_REAL;
   87232 #endif
   87233     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
   87234       aff = SQLITE_AFF_INTEGER;
   87235       break;
   87236     }
   87237   }
   87238 
   87239   /* If pszEst is not NULL, store an estimate of the field size.  The
   87240   ** estimate is scaled so that the size of an integer is 1.  */
   87241   if( pszEst ){
   87242     *pszEst = 1;   /* default size is approx 4 bytes */
   87243     if( aff<=SQLITE_AFF_NONE ){
   87244       if( zChar ){
   87245         while( zChar[0] ){
   87246           if( sqlite3Isdigit(zChar[0]) ){
   87247             int v = 0;
   87248             sqlite3GetInt32(zChar, &v);
   87249             v = v/4 + 1;
   87250             if( v>255 ) v = 255;
   87251             *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
   87252             break;
   87253           }
   87254           zChar++;
   87255         }
   87256       }else{
   87257         *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
   87258       }
   87259     }
   87260   }
   87261   return aff;
   87262 }
   87263 
   87264 /*
   87265 ** This routine is called by the parser while in the middle of
   87266 ** parsing a CREATE TABLE statement.  The pFirst token is the first
   87267 ** token in the sequence of tokens that describe the type of the
   87268 ** column currently under construction.   pLast is the last token
   87269 ** in the sequence.  Use this information to construct a string
   87270 ** that contains the typename of the column and store that string
   87271 ** in zType.
   87272 */
   87273 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
   87274   Table *p;
   87275   Column *pCol;
   87276 
   87277   p = pParse->pNewTable;
   87278   if( p==0 || NEVER(p->nCol<1) ) return;
   87279   pCol = &p->aCol[p->nCol-1];
   87280   assert( pCol->zType==0 );
   87281   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
   87282   pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
   87283 }
   87284 
   87285 /*
   87286 ** The expression is the default value for the most recently added column
   87287 ** of the table currently under construction.
   87288 **
   87289 ** Default value expressions must be constant.  Raise an exception if this
   87290 ** is not the case.
   87291 **
   87292 ** This routine is called by the parser while in the middle of
   87293 ** parsing a CREATE TABLE statement.
   87294 */
   87295 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
   87296   Table *p;
   87297   Column *pCol;
   87298   sqlite3 *db = pParse->db;
   87299   p = pParse->pNewTable;
   87300   if( p!=0 ){
   87301     pCol = &(p->aCol[p->nCol-1]);
   87302     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
   87303       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
   87304           pCol->zName);
   87305     }else{
   87306       /* A copy of pExpr is used instead of the original, as pExpr contains
   87307       ** tokens that point to volatile memory. The 'span' of the expression
   87308       ** is required by pragma table_info.
   87309       */
   87310       sqlite3ExprDelete(db, pCol->pDflt);
   87311       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
   87312       sqlite3DbFree(db, pCol->zDflt);
   87313       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   87314                                      (int)(pSpan->zEnd - pSpan->zStart));
   87315     }
   87316   }
   87317   sqlite3ExprDelete(db, pSpan->pExpr);
   87318 }
   87319 
   87320 /*
   87321 ** Designate the PRIMARY KEY for the table.  pList is a list of names
   87322 ** of columns that form the primary key.  If pList is NULL, then the
   87323 ** most recently added column of the table is the primary key.
   87324 **
   87325 ** A table can have at most one primary key.  If the table already has
   87326 ** a primary key (and this is the second primary key) then create an
   87327 ** error.
   87328 **
   87329 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
   87330 ** then we will try to use that column as the rowid.  Set the Table.iPKey
   87331 ** field of the table under construction to be the index of the
   87332 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
   87333 ** no INTEGER PRIMARY KEY.
   87334 **
   87335 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
   87336 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
   87337 */
   87338 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   87339   Parse *pParse,    /* Parsing context */
   87340   ExprList *pList,  /* List of field names to be indexed */
   87341   int onError,      /* What to do with a uniqueness conflict */
   87342   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
   87343   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
   87344 ){
   87345   Table *pTab = pParse->pNewTable;
   87346   char *zType = 0;
   87347   int iCol = -1, i;
   87348   int nTerm;
   87349   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
   87350   if( pTab->tabFlags & TF_HasPrimaryKey ){
   87351     sqlite3ErrorMsg(pParse,
   87352       "table \"%s\" has more than one primary key", pTab->zName);
   87353     goto primary_key_exit;
   87354   }
   87355   pTab->tabFlags |= TF_HasPrimaryKey;
   87356   if( pList==0 ){
   87357     iCol = pTab->nCol - 1;
   87358     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
   87359     zType = pTab->aCol[iCol].zType;
   87360     nTerm = 1;
   87361   }else{
   87362     nTerm = pList->nExpr;
   87363     for(i=0; i<nTerm; i++){
   87364       for(iCol=0; iCol<pTab->nCol; iCol++){
   87365         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
   87366           pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
   87367           zType = pTab->aCol[iCol].zType;
   87368           break;
   87369         }
   87370       }
   87371     }
   87372   }
   87373   if( nTerm==1
   87374    && zType && sqlite3StrICmp(zType, "INTEGER")==0
   87375    && sortOrder==SQLITE_SO_ASC
   87376   ){
   87377     pTab->iPKey = iCol;
   87378     pTab->keyConf = (u8)onError;
   87379     assert( autoInc==0 || autoInc==1 );
   87380     pTab->tabFlags |= autoInc*TF_Autoincrement;
   87381     if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
   87382   }else if( autoInc ){
   87383 #ifndef SQLITE_OMIT_AUTOINCREMENT
   87384     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
   87385        "INTEGER PRIMARY KEY");
   87386 #endif
   87387   }else{
   87388     Vdbe *v = pParse->pVdbe;
   87389     Index *p;
   87390     if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
   87391     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
   87392                            0, sortOrder, 0);
   87393     if( p ){
   87394       p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
   87395       if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
   87396     }
   87397     pList = 0;
   87398   }
   87399 
   87400 primary_key_exit:
   87401   sqlite3ExprListDelete(pParse->db, pList);
   87402   return;
   87403 }
   87404 
   87405 /*
   87406 ** Add a new CHECK constraint to the table currently under construction.
   87407 */
   87408 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
   87409   Parse *pParse,    /* Parsing context */
   87410   Expr *pCheckExpr  /* The check expression */
   87411 ){
   87412 #ifndef SQLITE_OMIT_CHECK
   87413   Table *pTab = pParse->pNewTable;
   87414   sqlite3 *db = pParse->db;
   87415   if( pTab && !IN_DECLARE_VTAB
   87416    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
   87417   ){
   87418     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
   87419     if( pParse->constraintName.n ){
   87420       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
   87421     }
   87422   }else
   87423 #endif
   87424   {
   87425     sqlite3ExprDelete(pParse->db, pCheckExpr);
   87426   }
   87427 }
   87428 
   87429 /*
   87430 ** Set the collation function of the most recently parsed table column
   87431 ** to the CollSeq given.
   87432 */
   87433 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   87434   Table *p;
   87435   int i;
   87436   char *zColl;              /* Dequoted name of collation sequence */
   87437   sqlite3 *db;
   87438 
   87439   if( (p = pParse->pNewTable)==0 ) return;
   87440   i = p->nCol-1;
   87441   db = pParse->db;
   87442   zColl = sqlite3NameFromToken(db, pToken);
   87443   if( !zColl ) return;
   87444 
   87445   if( sqlite3LocateCollSeq(pParse, zColl) ){
   87446     Index *pIdx;
   87447     sqlite3DbFree(db, p->aCol[i].zColl);
   87448     p->aCol[i].zColl = zColl;
   87449 
   87450     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
   87451     ** then an index may have been created on this column before the
   87452     ** collation type was added. Correct this if it is the case.
   87453     */
   87454     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   87455       assert( pIdx->nKeyCol==1 );
   87456       if( pIdx->aiColumn[0]==i ){
   87457         pIdx->azColl[0] = p->aCol[i].zColl;
   87458       }
   87459     }
   87460   }else{
   87461     sqlite3DbFree(db, zColl);
   87462   }
   87463 }
   87464 
   87465 /*
   87466 ** This function returns the collation sequence for database native text
   87467 ** encoding identified by the string zName, length nName.
   87468 **
   87469 ** If the requested collation sequence is not available, or not available
   87470 ** in the database native encoding, the collation factory is invoked to
   87471 ** request it. If the collation factory does not supply such a sequence,
   87472 ** and the sequence is available in another text encoding, then that is
   87473 ** returned instead.
   87474 **
   87475 ** If no versions of the requested collations sequence are available, or
   87476 ** another error occurs, NULL is returned and an error message written into
   87477 ** pParse.
   87478 **
   87479 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
   87480 ** invokes the collation factory if the named collation cannot be found
   87481 ** and generates an error message.
   87482 **
   87483 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
   87484 */
   87485 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
   87486   sqlite3 *db = pParse->db;
   87487   u8 enc = ENC(db);
   87488   u8 initbusy = db->init.busy;
   87489   CollSeq *pColl;
   87490 
   87491   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
   87492   if( !initbusy && (!pColl || !pColl->xCmp) ){
   87493     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
   87494   }
   87495 
   87496   return pColl;
   87497 }
   87498 
   87499 
   87500 /*
   87501 ** Generate code that will increment the schema cookie.
   87502 **
   87503 ** The schema cookie is used to determine when the schema for the
   87504 ** database changes.  After each schema change, the cookie value
   87505 ** changes.  When a process first reads the schema it records the
   87506 ** cookie.  Thereafter, whenever it goes to access the database,
   87507 ** it checks the cookie to make sure the schema has not changed
   87508 ** since it was last read.
   87509 **
   87510 ** This plan is not completely bullet-proof.  It is possible for
   87511 ** the schema to change multiple times and for the cookie to be
   87512 ** set back to prior value.  But schema changes are infrequent
   87513 ** and the probability of hitting the same cookie value is only
   87514 ** 1 chance in 2^32.  So we're safe enough.
   87515 */
   87516 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
   87517   int r1 = sqlite3GetTempReg(pParse);
   87518   sqlite3 *db = pParse->db;
   87519   Vdbe *v = pParse->pVdbe;
   87520   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   87521   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
   87522   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
   87523   sqlite3ReleaseTempReg(pParse, r1);
   87524 }
   87525 
   87526 /*
   87527 ** Measure the number of characters needed to output the given
   87528 ** identifier.  The number returned includes any quotes used
   87529 ** but does not include the null terminator.
   87530 **
   87531 ** The estimate is conservative.  It might be larger that what is
   87532 ** really needed.
   87533 */
   87534 static int identLength(const char *z){
   87535   int n;
   87536   for(n=0; *z; n++, z++){
   87537     if( *z=='"' ){ n++; }
   87538   }
   87539   return n + 2;
   87540 }
   87541 
   87542 /*
   87543 ** The first parameter is a pointer to an output buffer. The second
   87544 ** parameter is a pointer to an integer that contains the offset at
   87545 ** which to write into the output buffer. This function copies the
   87546 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
   87547 ** to the specified offset in the buffer and updates *pIdx to refer
   87548 ** to the first byte after the last byte written before returning.
   87549 **
   87550 ** If the string zSignedIdent consists entirely of alpha-numeric
   87551 ** characters, does not begin with a digit and is not an SQL keyword,
   87552 ** then it is copied to the output buffer exactly as it is. Otherwise,
   87553 ** it is quoted using double-quotes.
   87554 */
   87555 static void identPut(char *z, int *pIdx, char *zSignedIdent){
   87556   unsigned char *zIdent = (unsigned char*)zSignedIdent;
   87557   int i, j, needQuote;
   87558   i = *pIdx;
   87559 
   87560   for(j=0; zIdent[j]; j++){
   87561     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
   87562   }
   87563   needQuote = sqlite3Isdigit(zIdent[0])
   87564             || sqlite3KeywordCode(zIdent, j)!=TK_ID
   87565             || zIdent[j]!=0
   87566             || j==0;
   87567 
   87568   if( needQuote ) z[i++] = '"';
   87569   for(j=0; zIdent[j]; j++){
   87570     z[i++] = zIdent[j];
   87571     if( zIdent[j]=='"' ) z[i++] = '"';
   87572   }
   87573   if( needQuote ) z[i++] = '"';
   87574   z[i] = 0;
   87575   *pIdx = i;
   87576 }
   87577 
   87578 /*
   87579 ** Generate a CREATE TABLE statement appropriate for the given
   87580 ** table.  Memory to hold the text of the statement is obtained
   87581 ** from sqliteMalloc() and must be freed by the calling function.
   87582 */
   87583 static char *createTableStmt(sqlite3 *db, Table *p){
   87584   int i, k, n;
   87585   char *zStmt;
   87586   char *zSep, *zSep2, *zEnd;
   87587   Column *pCol;
   87588   n = 0;
   87589   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
   87590     n += identLength(pCol->zName) + 5;
   87591   }
   87592   n += identLength(p->zName);
   87593   if( n<50 ){
   87594     zSep = "";
   87595     zSep2 = ",";
   87596     zEnd = ")";
   87597   }else{
   87598     zSep = "\n  ";
   87599     zSep2 = ",\n  ";
   87600     zEnd = "\n)";
   87601   }
   87602   n += 35 + 6*p->nCol;
   87603   zStmt = sqlite3DbMallocRaw(0, n);
   87604   if( zStmt==0 ){
   87605     db->mallocFailed = 1;
   87606     return 0;
   87607   }
   87608   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
   87609   k = sqlite3Strlen30(zStmt);
   87610   identPut(zStmt, &k, p->zName);
   87611   zStmt[k++] = '(';
   87612   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
   87613     static const char * const azType[] = {
   87614         /* SQLITE_AFF_TEXT    */ " TEXT",
   87615         /* SQLITE_AFF_NONE    */ "",
   87616         /* SQLITE_AFF_NUMERIC */ " NUM",
   87617         /* SQLITE_AFF_INTEGER */ " INT",
   87618         /* SQLITE_AFF_REAL    */ " REAL"
   87619     };
   87620     int len;
   87621     const char *zType;
   87622 
   87623     sqlite3_snprintf(n-k, &zStmt[k], zSep);
   87624     k += sqlite3Strlen30(&zStmt[k]);
   87625     zSep = zSep2;
   87626     identPut(zStmt, &k, pCol->zName);
   87627     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
   87628     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
   87629     testcase( pCol->affinity==SQLITE_AFF_TEXT );
   87630     testcase( pCol->affinity==SQLITE_AFF_NONE );
   87631     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
   87632     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
   87633     testcase( pCol->affinity==SQLITE_AFF_REAL );
   87634 
   87635     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
   87636     len = sqlite3Strlen30(zType);
   87637     assert( pCol->affinity==SQLITE_AFF_NONE
   87638             || pCol->affinity==sqlite3AffinityType(zType, 0) );
   87639     memcpy(&zStmt[k], zType, len);
   87640     k += len;
   87641     assert( k<=n );
   87642   }
   87643   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
   87644   return zStmt;
   87645 }
   87646 
   87647 /*
   87648 ** Resize an Index object to hold N columns total.  Return SQLITE_OK
   87649 ** on success and SQLITE_NOMEM on an OOM error.
   87650 */
   87651 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
   87652   char *zExtra;
   87653   int nByte;
   87654   if( pIdx->nColumn>=N ) return SQLITE_OK;
   87655   assert( pIdx->isResized==0 );
   87656   nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
   87657   zExtra = sqlite3DbMallocZero(db, nByte);
   87658   if( zExtra==0 ) return SQLITE_NOMEM;
   87659   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
   87660   pIdx->azColl = (char**)zExtra;
   87661   zExtra += sizeof(char*)*N;
   87662   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
   87663   pIdx->aiColumn = (i16*)zExtra;
   87664   zExtra += sizeof(i16)*N;
   87665   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
   87666   pIdx->aSortOrder = (u8*)zExtra;
   87667   pIdx->nColumn = N;
   87668   pIdx->isResized = 1;
   87669   return SQLITE_OK;
   87670 }
   87671 
   87672 /*
   87673 ** Estimate the total row width for a table.
   87674 */
   87675 static void estimateTableWidth(Table *pTab){
   87676   unsigned wTable = 0;
   87677   const Column *pTabCol;
   87678   int i;
   87679   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
   87680     wTable += pTabCol->szEst;
   87681   }
   87682   if( pTab->iPKey<0 ) wTable++;
   87683   pTab->szTabRow = sqlite3LogEst(wTable*4);
   87684 }
   87685 
   87686 /*
   87687 ** Estimate the average size of a row for an index.
   87688 */
   87689 static void estimateIndexWidth(Index *pIdx){
   87690   unsigned wIndex = 0;
   87691   int i;
   87692   const Column *aCol = pIdx->pTable->aCol;
   87693   for(i=0; i<pIdx->nColumn; i++){
   87694     i16 x = pIdx->aiColumn[i];
   87695     assert( x<pIdx->pTable->nCol );
   87696     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
   87697   }
   87698   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
   87699 }
   87700 
   87701 /* Return true if value x is found any of the first nCol entries of aiCol[]
   87702 */
   87703 static int hasColumn(const i16 *aiCol, int nCol, int x){
   87704   while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
   87705   return 0;
   87706 }
   87707 
   87708 /*
   87709 ** This routine runs at the end of parsing a CREATE TABLE statement that
   87710 ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
   87711 ** internal schema data structures and the generated VDBE code so that they
   87712 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
   87713 ** Changes include:
   87714 **
   87715 **     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
   87716 **          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
   87717 **          data storage is a covering index btree.
   87718 **     (2)  Bypass the creation of the sqlite_master table entry
   87719 **          for the PRIMARY KEY as the the primary key index is now
   87720 **          identified by the sqlite_master table entry of the table itself.
   87721 **     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
   87722 **          schema to the rootpage from the main table.
   87723 **     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
   87724 **     (5)  Add all table columns to the PRIMARY KEY Index object
   87725 **          so that the PRIMARY KEY is a covering index.  The surplus
   87726 **          columns are part of KeyInfo.nXField and are not used for
   87727 **          sorting or lookup or uniqueness checks.
   87728 **     (6)  Replace the rowid tail on all automatically generated UNIQUE
   87729 **          indices with the PRIMARY KEY columns.
   87730 */
   87731 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
   87732   Index *pIdx;
   87733   Index *pPk;
   87734   int nPk;
   87735   int i, j;
   87736   sqlite3 *db = pParse->db;
   87737   Vdbe *v = pParse->pVdbe;
   87738 
   87739   /* Convert the OP_CreateTable opcode that would normally create the
   87740   ** root-page for the table into a OP_CreateIndex opcode.  The index
   87741   ** created will become the PRIMARY KEY index.
   87742   */
   87743   if( pParse->addrCrTab ){
   87744     assert( v );
   87745     sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
   87746   }
   87747 
   87748   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
   87749   ** table entry.
   87750   */
   87751   if( pParse->addrSkipPK ){
   87752     assert( v );
   87753     sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
   87754   }
   87755 
   87756   /* Locate the PRIMARY KEY index.  Or, if this table was originally
   87757   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
   87758   */
   87759   if( pTab->iPKey>=0 ){
   87760     ExprList *pList;
   87761     pList = sqlite3ExprListAppend(pParse, 0, 0);
   87762     if( pList==0 ) return;
   87763     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
   87764                                         pTab->aCol[pTab->iPKey].zName);
   87765     pList->a[0].sortOrder = pParse->iPkSortOrder;
   87766     assert( pParse->pNewTable==pTab );
   87767     pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
   87768     if( pPk==0 ) return;
   87769     pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
   87770     pTab->iPKey = -1;
   87771   }else{
   87772     pPk = sqlite3PrimaryKeyIndex(pTab);
   87773   }
   87774   pPk->isCovering = 1;
   87775   assert( pPk!=0 );
   87776   nPk = pPk->nKeyCol;
   87777 
   87778   /* Make sure every column of the PRIMARY KEY is NOT NULL */
   87779   for(i=0; i<nPk; i++){
   87780     pTab->aCol[pPk->aiColumn[i]].notNull = 1;
   87781   }
   87782   pPk->uniqNotNull = 1;
   87783 
   87784   /* The root page of the PRIMARY KEY is the table root page */
   87785   pPk->tnum = pTab->tnum;
   87786 
   87787   /* Update the in-memory representation of all UNIQUE indices by converting
   87788   ** the final rowid column into one or more columns of the PRIMARY KEY.
   87789   */
   87790   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   87791     int n;
   87792     if( IsPrimaryKeyIndex(pIdx) ) continue;
   87793     for(i=n=0; i<nPk; i++){
   87794       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
   87795     }
   87796     if( n==0 ){
   87797       /* This index is a superset of the primary key */
   87798       pIdx->nColumn = pIdx->nKeyCol;
   87799       continue;
   87800     }
   87801     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
   87802     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
   87803       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
   87804         pIdx->aiColumn[j] = pPk->aiColumn[i];
   87805         pIdx->azColl[j] = pPk->azColl[i];
   87806         j++;
   87807       }
   87808     }
   87809     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
   87810     assert( pIdx->nColumn>=j );
   87811   }
   87812 
   87813   /* Add all table columns to the PRIMARY KEY index
   87814   */
   87815   if( nPk<pTab->nCol ){
   87816     if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
   87817     for(i=0, j=nPk; i<pTab->nCol; i++){
   87818       if( !hasColumn(pPk->aiColumn, j, i) ){
   87819         assert( j<pPk->nColumn );
   87820         pPk->aiColumn[j] = i;
   87821         pPk->azColl[j] = "BINARY";
   87822         j++;
   87823       }
   87824     }
   87825     assert( pPk->nColumn==j );
   87826     assert( pTab->nCol==j );
   87827   }else{
   87828     pPk->nColumn = pTab->nCol;
   87829   }
   87830 }
   87831 
   87832 /*
   87833 ** This routine is called to report the final ")" that terminates
   87834 ** a CREATE TABLE statement.
   87835 **
   87836 ** The table structure that other action routines have been building
   87837 ** is added to the internal hash tables, assuming no errors have
   87838 ** occurred.
   87839 **
   87840 ** An entry for the table is made in the master table on disk, unless
   87841 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
   87842 ** it means we are reading the sqlite_master table because we just
   87843 ** connected to the database or because the sqlite_master table has
   87844 ** recently changed, so the entry for this table already exists in
   87845 ** the sqlite_master table.  We do not want to create it again.
   87846 **
   87847 ** If the pSelect argument is not NULL, it means that this routine
   87848 ** was called to create a table generated from a
   87849 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
   87850 ** the new table will match the result set of the SELECT.
   87851 */
   87852 SQLITE_PRIVATE void sqlite3EndTable(
   87853   Parse *pParse,          /* Parse context */
   87854   Token *pCons,           /* The ',' token after the last column defn. */
   87855   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
   87856   u8 tabOpts,             /* Extra table options. Usually 0. */
   87857   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
   87858 ){
   87859   Table *p;                 /* The new table */
   87860   sqlite3 *db = pParse->db; /* The database connection */
   87861   int iDb;                  /* Database in which the table lives */
   87862   Index *pIdx;              /* An implied index of the table */
   87863 
   87864   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
   87865     return;
   87866   }
   87867   p = pParse->pNewTable;
   87868   if( p==0 ) return;
   87869 
   87870   assert( !db->init.busy || !pSelect );
   87871 
   87872   /* If the db->init.busy is 1 it means we are reading the SQL off the
   87873   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
   87874   ** So do not write to the disk again.  Extract the root page number
   87875   ** for the table from the db->init.newTnum field.  (The page number
   87876   ** should have been put there by the sqliteOpenCb routine.)
   87877   */
   87878   if( db->init.busy ){
   87879     p->tnum = db->init.newTnum;
   87880   }
   87881 
   87882   /* Special processing for WITHOUT ROWID Tables */
   87883   if( tabOpts & TF_WithoutRowid ){
   87884     if( (p->tabFlags & TF_Autoincrement) ){
   87885       sqlite3ErrorMsg(pParse,
   87886           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
   87887       return;
   87888     }
   87889     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
   87890       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
   87891     }else{
   87892       p->tabFlags |= TF_WithoutRowid;
   87893       convertToWithoutRowidTable(pParse, p);
   87894     }
   87895   }
   87896 
   87897   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   87898 
   87899 #ifndef SQLITE_OMIT_CHECK
   87900   /* Resolve names in all CHECK constraint expressions.
   87901   */
   87902   if( p->pCheck ){
   87903     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
   87904   }
   87905 #endif /* !defined(SQLITE_OMIT_CHECK) */
   87906 
   87907   /* Estimate the average row size for the table and for all implied indices */
   87908   estimateTableWidth(p);
   87909   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   87910     estimateIndexWidth(pIdx);
   87911   }
   87912 
   87913   /* If not initializing, then create a record for the new table
   87914   ** in the SQLITE_MASTER table of the database.
   87915   **
   87916   ** If this is a TEMPORARY table, write the entry into the auxiliary
   87917   ** file instead of into the main database file.
   87918   */
   87919   if( !db->init.busy ){
   87920     int n;
   87921     Vdbe *v;
   87922     char *zType;    /* "view" or "table" */
   87923     char *zType2;   /* "VIEW" or "TABLE" */
   87924     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
   87925 
   87926     v = sqlite3GetVdbe(pParse);
   87927     if( NEVER(v==0) ) return;
   87928 
   87929     sqlite3VdbeAddOp1(v, OP_Close, 0);
   87930 
   87931     /*
   87932     ** Initialize zType for the new view or table.
   87933     */
   87934     if( p->pSelect==0 ){
   87935       /* A regular table */
   87936       zType = "table";
   87937       zType2 = "TABLE";
   87938 #ifndef SQLITE_OMIT_VIEW
   87939     }else{
   87940       /* A view */
   87941       zType = "view";
   87942       zType2 = "VIEW";
   87943 #endif
   87944     }
   87945 
   87946     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
   87947     ** statement to populate the new table. The root-page number for the
   87948     ** new table is in register pParse->regRoot.
   87949     **
   87950     ** Once the SELECT has been coded by sqlite3Select(), it is in a
   87951     ** suitable state to query for the column names and types to be used
   87952     ** by the new table.
   87953     **
   87954     ** A shared-cache write-lock is not required to write to the new table,
   87955     ** as a schema-lock must have already been obtained to create it. Since
   87956     ** a schema-lock excludes all other database users, the write-lock would
   87957     ** be redundant.
   87958     */
   87959     if( pSelect ){
   87960       SelectDest dest;
   87961       Table *pSelTab;
   87962 
   87963       assert(pParse->nTab==1);
   87964       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
   87965       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
   87966       pParse->nTab = 2;
   87967       sqlite3SelectDestInit(&dest, SRT_Table, 1);
   87968       sqlite3Select(pParse, pSelect, &dest);
   87969       sqlite3VdbeAddOp1(v, OP_Close, 1);
   87970       if( pParse->nErr==0 ){
   87971         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
   87972         if( pSelTab==0 ) return;
   87973         assert( p->aCol==0 );
   87974         p->nCol = pSelTab->nCol;
   87975         p->aCol = pSelTab->aCol;
   87976         pSelTab->nCol = 0;
   87977         pSelTab->aCol = 0;
   87978         sqlite3DeleteTable(db, pSelTab);
   87979       }
   87980     }
   87981 
   87982     /* Compute the complete text of the CREATE statement */
   87983     if( pSelect ){
   87984       zStmt = createTableStmt(db, p);
   87985     }else{
   87986       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
   87987       n = (int)(pEnd2->z - pParse->sNameToken.z);
   87988       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
   87989       zStmt = sqlite3MPrintf(db,
   87990           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
   87991       );
   87992     }
   87993 
   87994     /* A slot for the record has already been allocated in the
   87995     ** SQLITE_MASTER table.  We just need to update that slot with all
   87996     ** the information we've collected.
   87997     */
   87998     sqlite3NestedParse(pParse,
   87999       "UPDATE %Q.%s "
   88000          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
   88001        "WHERE rowid=#%d",
   88002       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   88003       zType,
   88004       p->zName,
   88005       p->zName,
   88006       pParse->regRoot,
   88007       zStmt,
   88008       pParse->regRowid
   88009     );
   88010     sqlite3DbFree(db, zStmt);
   88011     sqlite3ChangeCookie(pParse, iDb);
   88012 
   88013 #ifndef SQLITE_OMIT_AUTOINCREMENT
   88014     /* Check to see if we need to create an sqlite_sequence table for
   88015     ** keeping track of autoincrement keys.
   88016     */
   88017     if( p->tabFlags & TF_Autoincrement ){
   88018       Db *pDb = &db->aDb[iDb];
   88019       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   88020       if( pDb->pSchema->pSeqTab==0 ){
   88021         sqlite3NestedParse(pParse,
   88022           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
   88023           pDb->zName
   88024         );
   88025       }
   88026     }
   88027 #endif
   88028 
   88029     /* Reparse everything to update our internal data structures */
   88030     sqlite3VdbeAddParseSchemaOp(v, iDb,
   88031            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
   88032   }
   88033 
   88034 
   88035   /* Add the table to the in-memory representation of the database.
   88036   */
   88037   if( db->init.busy ){
   88038     Table *pOld;
   88039     Schema *pSchema = p->pSchema;
   88040     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   88041     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
   88042                              sqlite3Strlen30(p->zName),p);
   88043     if( pOld ){
   88044       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
   88045       db->mallocFailed = 1;
   88046       return;
   88047     }
   88048     pParse->pNewTable = 0;
   88049     db->flags |= SQLITE_InternChanges;
   88050 
   88051 #ifndef SQLITE_OMIT_ALTERTABLE
   88052     if( !p->pSelect ){
   88053       const char *zName = (const char *)pParse->sNameToken.z;
   88054       int nName;
   88055       assert( !pSelect && pCons && pEnd );
   88056       if( pCons->z==0 ){
   88057         pCons = pEnd;
   88058       }
   88059       nName = (int)((const char *)pCons->z - zName);
   88060       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
   88061     }
   88062 #endif
   88063   }
   88064 }
   88065 
   88066 #ifndef SQLITE_OMIT_VIEW
   88067 /*
   88068 ** The parser calls this routine in order to create a new VIEW
   88069 */
   88070 SQLITE_PRIVATE void sqlite3CreateView(
   88071   Parse *pParse,     /* The parsing context */
   88072   Token *pBegin,     /* The CREATE token that begins the statement */
   88073   Token *pName1,     /* The token that holds the name of the view */
   88074   Token *pName2,     /* The token that holds the name of the view */
   88075   Select *pSelect,   /* A SELECT statement that will become the new view */
   88076   int isTemp,        /* TRUE for a TEMPORARY view */
   88077   int noErr          /* Suppress error messages if VIEW already exists */
   88078 ){
   88079   Table *p;
   88080   int n;
   88081   const char *z;
   88082   Token sEnd;
   88083   DbFixer sFix;
   88084   Token *pName = 0;
   88085   int iDb;
   88086   sqlite3 *db = pParse->db;
   88087 
   88088   if( pParse->nVar>0 ){
   88089     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
   88090     sqlite3SelectDelete(db, pSelect);
   88091     return;
   88092   }
   88093   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
   88094   p = pParse->pNewTable;
   88095   if( p==0 || pParse->nErr ){
   88096     sqlite3SelectDelete(db, pSelect);
   88097     return;
   88098   }
   88099   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   88100   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   88101   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
   88102   if( sqlite3FixSelect(&sFix, pSelect) ){
   88103     sqlite3SelectDelete(db, pSelect);
   88104     return;
   88105   }
   88106 
   88107   /* Make a copy of the entire SELECT statement that defines the view.
   88108   ** This will force all the Expr.token.z values to be dynamically
   88109   ** allocated rather than point to the input string - which means that
   88110   ** they will persist after the current sqlite3_exec() call returns.
   88111   */
   88112   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   88113   sqlite3SelectDelete(db, pSelect);
   88114   if( db->mallocFailed ){
   88115     return;
   88116   }
   88117   if( !db->init.busy ){
   88118     sqlite3ViewGetColumnNames(pParse, p);
   88119   }
   88120 
   88121   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
   88122   ** the end.
   88123   */
   88124   sEnd = pParse->sLastToken;
   88125   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
   88126     sEnd.z += sEnd.n;
   88127   }
   88128   sEnd.n = 0;
   88129   n = (int)(sEnd.z - pBegin->z);
   88130   z = pBegin->z;
   88131   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
   88132   sEnd.z = &z[n-1];
   88133   sEnd.n = 1;
   88134 
   88135   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
   88136   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
   88137   return;
   88138 }
   88139 #endif /* SQLITE_OMIT_VIEW */
   88140 
   88141 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   88142 /*
   88143 ** The Table structure pTable is really a VIEW.  Fill in the names of
   88144 ** the columns of the view in the pTable structure.  Return the number
   88145 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
   88146 */
   88147 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   88148   Table *pSelTab;   /* A fake table from which we get the result set */
   88149   Select *pSel;     /* Copy of the SELECT that implements the view */
   88150   int nErr = 0;     /* Number of errors encountered */
   88151   int n;            /* Temporarily holds the number of cursors assigned */
   88152   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
   88153   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   88154 
   88155   assert( pTable );
   88156 
   88157 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88158   if( sqlite3VtabCallConnect(pParse, pTable) ){
   88159     return SQLITE_ERROR;
   88160   }
   88161   if( IsVirtual(pTable) ) return 0;
   88162 #endif
   88163 
   88164 #ifndef SQLITE_OMIT_VIEW
   88165   /* A positive nCol means the columns names for this view are
   88166   ** already known.
   88167   */
   88168   if( pTable->nCol>0 ) return 0;
   88169 
   88170   /* A negative nCol is a special marker meaning that we are currently
   88171   ** trying to compute the column names.  If we enter this routine with
   88172   ** a negative nCol, it means two or more views form a loop, like this:
   88173   **
   88174   **     CREATE VIEW one AS SELECT * FROM two;
   88175   **     CREATE VIEW two AS SELECT * FROM one;
   88176   **
   88177   ** Actually, the error above is now caught prior to reaching this point.
   88178   ** But the following test is still important as it does come up
   88179   ** in the following:
   88180   **
   88181   **     CREATE TABLE main.ex1(a);
   88182   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
   88183   **     SELECT * FROM temp.ex1;
   88184   */
   88185   if( pTable->nCol<0 ){
   88186     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
   88187     return 1;
   88188   }
   88189   assert( pTable->nCol>=0 );
   88190 
   88191   /* If we get this far, it means we need to compute the table names.
   88192   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
   88193   ** "*" elements in the results set of the view and will assign cursors
   88194   ** to the elements of the FROM clause.  But we do not want these changes
   88195   ** to be permanent.  So the computation is done on a copy of the SELECT
   88196   ** statement that defines the view.
   88197   */
   88198   assert( pTable->pSelect );
   88199   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
   88200   if( pSel ){
   88201     u8 enableLookaside = db->lookaside.bEnabled;
   88202     n = pParse->nTab;
   88203     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
   88204     pTable->nCol = -1;
   88205     db->lookaside.bEnabled = 0;
   88206 #ifndef SQLITE_OMIT_AUTHORIZATION
   88207     xAuth = db->xAuth;
   88208     db->xAuth = 0;
   88209     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   88210     db->xAuth = xAuth;
   88211 #else
   88212     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   88213 #endif
   88214     db->lookaside.bEnabled = enableLookaside;
   88215     pParse->nTab = n;
   88216     if( pSelTab ){
   88217       assert( pTable->aCol==0 );
   88218       pTable->nCol = pSelTab->nCol;
   88219       pTable->aCol = pSelTab->aCol;
   88220       pSelTab->nCol = 0;
   88221       pSelTab->aCol = 0;
   88222       sqlite3DeleteTable(db, pSelTab);
   88223       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
   88224       pTable->pSchema->schemaFlags |= DB_UnresetViews;
   88225     }else{
   88226       pTable->nCol = 0;
   88227       nErr++;
   88228     }
   88229     sqlite3SelectDelete(db, pSel);
   88230   } else {
   88231     nErr++;
   88232   }
   88233 #endif /* SQLITE_OMIT_VIEW */
   88234   return nErr;
   88235 }
   88236 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
   88237 
   88238 #ifndef SQLITE_OMIT_VIEW
   88239 /*
   88240 ** Clear the column names from every VIEW in database idx.
   88241 */
   88242 static void sqliteViewResetAll(sqlite3 *db, int idx){
   88243   HashElem *i;
   88244   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
   88245   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
   88246   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
   88247     Table *pTab = sqliteHashData(i);
   88248     if( pTab->pSelect ){
   88249       sqliteDeleteColumnNames(db, pTab);
   88250       pTab->aCol = 0;
   88251       pTab->nCol = 0;
   88252     }
   88253   }
   88254   DbClearProperty(db, idx, DB_UnresetViews);
   88255 }
   88256 #else
   88257 # define sqliteViewResetAll(A,B)
   88258 #endif /* SQLITE_OMIT_VIEW */
   88259 
   88260 /*
   88261 ** This function is called by the VDBE to adjust the internal schema
   88262 ** used by SQLite when the btree layer moves a table root page. The
   88263 ** root-page of a table or index in database iDb has changed from iFrom
   88264 ** to iTo.
   88265 **
   88266 ** Ticket #1728:  The symbol table might still contain information
   88267 ** on tables and/or indices that are the process of being deleted.
   88268 ** If you are unlucky, one of those deleted indices or tables might
   88269 ** have the same rootpage number as the real table or index that is
   88270 ** being moved.  So we cannot stop searching after the first match
   88271 ** because the first match might be for one of the deleted indices
   88272 ** or tables and not the table/index that is actually being moved.
   88273 ** We must continue looping until all tables and indices with
   88274 ** rootpage==iFrom have been converted to have a rootpage of iTo
   88275 ** in order to be certain that we got the right one.
   88276 */
   88277 #ifndef SQLITE_OMIT_AUTOVACUUM
   88278 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
   88279   HashElem *pElem;
   88280   Hash *pHash;
   88281   Db *pDb;
   88282 
   88283   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   88284   pDb = &db->aDb[iDb];
   88285   pHash = &pDb->pSchema->tblHash;
   88286   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   88287     Table *pTab = sqliteHashData(pElem);
   88288     if( pTab->tnum==iFrom ){
   88289       pTab->tnum = iTo;
   88290     }
   88291   }
   88292   pHash = &pDb->pSchema->idxHash;
   88293   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   88294     Index *pIdx = sqliteHashData(pElem);
   88295     if( pIdx->tnum==iFrom ){
   88296       pIdx->tnum = iTo;
   88297     }
   88298   }
   88299 }
   88300 #endif
   88301 
   88302 /*
   88303 ** Write code to erase the table with root-page iTable from database iDb.
   88304 ** Also write code to modify the sqlite_master table and internal schema
   88305 ** if a root-page of another table is moved by the btree-layer whilst
   88306 ** erasing iTable (this can happen with an auto-vacuum database).
   88307 */
   88308 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   88309   Vdbe *v = sqlite3GetVdbe(pParse);
   88310   int r1 = sqlite3GetTempReg(pParse);
   88311   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
   88312   sqlite3MayAbort(pParse);
   88313 #ifndef SQLITE_OMIT_AUTOVACUUM
   88314   /* OP_Destroy stores an in integer r1. If this integer
   88315   ** is non-zero, then it is the root page number of a table moved to
   88316   ** location iTable. The following code modifies the sqlite_master table to
   88317   ** reflect this.
   88318   **
   88319   ** The "#NNN" in the SQL is a special constant that means whatever value
   88320   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
   88321   ** token for additional information.
   88322   */
   88323   sqlite3NestedParse(pParse,
   88324      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
   88325      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
   88326 #endif
   88327   sqlite3ReleaseTempReg(pParse, r1);
   88328 }
   88329 
   88330 /*
   88331 ** Write VDBE code to erase table pTab and all associated indices on disk.
   88332 ** Code to update the sqlite_master tables and internal schema definitions
   88333 ** in case a root-page belonging to another table is moved by the btree layer
   88334 ** is also added (this can happen with an auto-vacuum database).
   88335 */
   88336 static void destroyTable(Parse *pParse, Table *pTab){
   88337 #ifdef SQLITE_OMIT_AUTOVACUUM
   88338   Index *pIdx;
   88339   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   88340   destroyRootPage(pParse, pTab->tnum, iDb);
   88341   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   88342     destroyRootPage(pParse, pIdx->tnum, iDb);
   88343   }
   88344 #else
   88345   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
   88346   ** is not defined), then it is important to call OP_Destroy on the
   88347   ** table and index root-pages in order, starting with the numerically
   88348   ** largest root-page number. This guarantees that none of the root-pages
   88349   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
   88350   ** following were coded:
   88351   **
   88352   ** OP_Destroy 4 0
   88353   ** ...
   88354   ** OP_Destroy 5 0
   88355   **
   88356   ** and root page 5 happened to be the largest root-page number in the
   88357   ** database, then root page 5 would be moved to page 4 by the
   88358   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
   88359   ** a free-list page.
   88360   */
   88361   int iTab = pTab->tnum;
   88362   int iDestroyed = 0;
   88363 
   88364   while( 1 ){
   88365     Index *pIdx;
   88366     int iLargest = 0;
   88367 
   88368     if( iDestroyed==0 || iTab<iDestroyed ){
   88369       iLargest = iTab;
   88370     }
   88371     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   88372       int iIdx = pIdx->tnum;
   88373       assert( pIdx->pSchema==pTab->pSchema );
   88374       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
   88375         iLargest = iIdx;
   88376       }
   88377     }
   88378     if( iLargest==0 ){
   88379       return;
   88380     }else{
   88381       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   88382       assert( iDb>=0 && iDb<pParse->db->nDb );
   88383       destroyRootPage(pParse, iLargest, iDb);
   88384       iDestroyed = iLargest;
   88385     }
   88386   }
   88387 #endif
   88388 }
   88389 
   88390 /*
   88391 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
   88392 ** after a DROP INDEX or DROP TABLE command.
   88393 */
   88394 static void sqlite3ClearStatTables(
   88395   Parse *pParse,         /* The parsing context */
   88396   int iDb,               /* The database number */
   88397   const char *zType,     /* "idx" or "tbl" */
   88398   const char *zName      /* Name of index or table */
   88399 ){
   88400   int i;
   88401   const char *zDbName = pParse->db->aDb[iDb].zName;
   88402   for(i=1; i<=4; i++){
   88403     char zTab[24];
   88404     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
   88405     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
   88406       sqlite3NestedParse(pParse,
   88407         "DELETE FROM %Q.%s WHERE %s=%Q",
   88408         zDbName, zTab, zType, zName
   88409       );
   88410     }
   88411   }
   88412 }
   88413 
   88414 /*
   88415 ** Generate code to drop a table.
   88416 */
   88417 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
   88418   Vdbe *v;
   88419   sqlite3 *db = pParse->db;
   88420   Trigger *pTrigger;
   88421   Db *pDb = &db->aDb[iDb];
   88422 
   88423   v = sqlite3GetVdbe(pParse);
   88424   assert( v!=0 );
   88425   sqlite3BeginWriteOperation(pParse, 1, iDb);
   88426 
   88427 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88428   if( IsVirtual(pTab) ){
   88429     sqlite3VdbeAddOp0(v, OP_VBegin);
   88430   }
   88431 #endif
   88432 
   88433   /* Drop all triggers associated with the table being dropped. Code
   88434   ** is generated to remove entries from sqlite_master and/or
   88435   ** sqlite_temp_master if required.
   88436   */
   88437   pTrigger = sqlite3TriggerList(pParse, pTab);
   88438   while( pTrigger ){
   88439     assert( pTrigger->pSchema==pTab->pSchema ||
   88440         pTrigger->pSchema==db->aDb[1].pSchema );
   88441     sqlite3DropTriggerPtr(pParse, pTrigger);
   88442     pTrigger = pTrigger->pNext;
   88443   }
   88444 
   88445 #ifndef SQLITE_OMIT_AUTOINCREMENT
   88446   /* Remove any entries of the sqlite_sequence table associated with
   88447   ** the table being dropped. This is done before the table is dropped
   88448   ** at the btree level, in case the sqlite_sequence table needs to
   88449   ** move as a result of the drop (can happen in auto-vacuum mode).
   88450   */
   88451   if( pTab->tabFlags & TF_Autoincrement ){
   88452     sqlite3NestedParse(pParse,
   88453       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
   88454       pDb->zName, pTab->zName
   88455     );
   88456   }
   88457 #endif
   88458 
   88459   /* Drop all SQLITE_MASTER table and index entries that refer to the
   88460   ** table. The program name loops through the master table and deletes
   88461   ** every row that refers to a table of the same name as the one being
   88462   ** dropped. Triggers are handled separately because a trigger can be
   88463   ** created in the temp database that refers to a table in another
   88464   ** database.
   88465   */
   88466   sqlite3NestedParse(pParse,
   88467       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
   88468       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
   88469   if( !isView && !IsVirtual(pTab) ){
   88470     destroyTable(pParse, pTab);
   88471   }
   88472 
   88473   /* Remove the table entry from SQLite's internal schema and modify
   88474   ** the schema cookie.
   88475   */
   88476   if( IsVirtual(pTab) ){
   88477     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
   88478   }
   88479   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   88480   sqlite3ChangeCookie(pParse, iDb);
   88481   sqliteViewResetAll(db, iDb);
   88482 }
   88483 
   88484 /*
   88485 ** This routine is called to do the work of a DROP TABLE statement.
   88486 ** pName is the name of the table to be dropped.
   88487 */
   88488 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
   88489   Table *pTab;
   88490   Vdbe *v;
   88491   sqlite3 *db = pParse->db;
   88492   int iDb;
   88493 
   88494   if( db->mallocFailed ){
   88495     goto exit_drop_table;
   88496   }
   88497   assert( pParse->nErr==0 );
   88498   assert( pName->nSrc==1 );
   88499   if( noErr ) db->suppressErr++;
   88500   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
   88501   if( noErr ) db->suppressErr--;
   88502 
   88503   if( pTab==0 ){
   88504     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   88505     goto exit_drop_table;
   88506   }
   88507   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   88508   assert( iDb>=0 && iDb<db->nDb );
   88509 
   88510   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
   88511   ** it is initialized.
   88512   */
   88513   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
   88514     goto exit_drop_table;
   88515   }
   88516 #ifndef SQLITE_OMIT_AUTHORIZATION
   88517   {
   88518     int code;
   88519     const char *zTab = SCHEMA_TABLE(iDb);
   88520     const char *zDb = db->aDb[iDb].zName;
   88521     const char *zArg2 = 0;
   88522     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
   88523       goto exit_drop_table;
   88524     }
   88525     if( isView ){
   88526       if( !OMIT_TEMPDB && iDb==1 ){
   88527         code = SQLITE_DROP_TEMP_VIEW;
   88528       }else{
   88529         code = SQLITE_DROP_VIEW;
   88530       }
   88531 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88532     }else if( IsVirtual(pTab) ){
   88533       code = SQLITE_DROP_VTABLE;
   88534       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
   88535 #endif
   88536     }else{
   88537       if( !OMIT_TEMPDB && iDb==1 ){
   88538         code = SQLITE_DROP_TEMP_TABLE;
   88539       }else{
   88540         code = SQLITE_DROP_TABLE;
   88541       }
   88542     }
   88543     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
   88544       goto exit_drop_table;
   88545     }
   88546     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
   88547       goto exit_drop_table;
   88548     }
   88549   }
   88550 #endif
   88551   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   88552     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
   88553     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
   88554     goto exit_drop_table;
   88555   }
   88556 
   88557 #ifndef SQLITE_OMIT_VIEW
   88558   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
   88559   ** on a table.
   88560   */
   88561   if( isView && pTab->pSelect==0 ){
   88562     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
   88563     goto exit_drop_table;
   88564   }
   88565   if( !isView && pTab->pSelect ){
   88566     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
   88567     goto exit_drop_table;
   88568   }
   88569 #endif
   88570 
   88571   /* Generate code to remove the table from the master table
   88572   ** on disk.
   88573   */
   88574   v = sqlite3GetVdbe(pParse);
   88575   if( v ){
   88576     sqlite3BeginWriteOperation(pParse, 1, iDb);
   88577     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
   88578     sqlite3FkDropTable(pParse, pName, pTab);
   88579     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
   88580   }
   88581 
   88582 exit_drop_table:
   88583   sqlite3SrcListDelete(db, pName);
   88584 }
   88585 
   88586 /*
   88587 ** This routine is called to create a new foreign key on the table
   88588 ** currently under construction.  pFromCol determines which columns
   88589 ** in the current table point to the foreign key.  If pFromCol==0 then
   88590 ** connect the key to the last column inserted.  pTo is the name of
   88591 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
   88592 ** of tables in the parent pTo table.  flags contains all
   88593 ** information about the conflict resolution algorithms specified
   88594 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
   88595 **
   88596 ** An FKey structure is created and added to the table currently
   88597 ** under construction in the pParse->pNewTable field.
   88598 **
   88599 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
   88600 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
   88601 */
   88602 SQLITE_PRIVATE void sqlite3CreateForeignKey(
   88603   Parse *pParse,       /* Parsing context */
   88604   ExprList *pFromCol,  /* Columns in this table that point to other table */
   88605   Token *pTo,          /* Name of the other table */
   88606   ExprList *pToCol,    /* Columns in the other table */
   88607   int flags            /* Conflict resolution algorithms. */
   88608 ){
   88609   sqlite3 *db = pParse->db;
   88610 #ifndef SQLITE_OMIT_FOREIGN_KEY
   88611   FKey *pFKey = 0;
   88612   FKey *pNextTo;
   88613   Table *p = pParse->pNewTable;
   88614   int nByte;
   88615   int i;
   88616   int nCol;
   88617   char *z;
   88618 
   88619   assert( pTo!=0 );
   88620   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
   88621   if( pFromCol==0 ){
   88622     int iCol = p->nCol-1;
   88623     if( NEVER(iCol<0) ) goto fk_end;
   88624     if( pToCol && pToCol->nExpr!=1 ){
   88625       sqlite3ErrorMsg(pParse, "foreign key on %s"
   88626          " should reference only one column of table %T",
   88627          p->aCol[iCol].zName, pTo);
   88628       goto fk_end;
   88629     }
   88630     nCol = 1;
   88631   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
   88632     sqlite3ErrorMsg(pParse,
   88633         "number of columns in foreign key does not match the number of "
   88634         "columns in the referenced table");
   88635     goto fk_end;
   88636   }else{
   88637     nCol = pFromCol->nExpr;
   88638   }
   88639   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
   88640   if( pToCol ){
   88641     for(i=0; i<pToCol->nExpr; i++){
   88642       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
   88643     }
   88644   }
   88645   pFKey = sqlite3DbMallocZero(db, nByte );
   88646   if( pFKey==0 ){
   88647     goto fk_end;
   88648   }
   88649   pFKey->pFrom = p;
   88650   pFKey->pNextFrom = p->pFKey;
   88651   z = (char*)&pFKey->aCol[nCol];
   88652   pFKey->zTo = z;
   88653   memcpy(z, pTo->z, pTo->n);
   88654   z[pTo->n] = 0;
   88655   sqlite3Dequote(z);
   88656   z += pTo->n+1;
   88657   pFKey->nCol = nCol;
   88658   if( pFromCol==0 ){
   88659     pFKey->aCol[0].iFrom = p->nCol-1;
   88660   }else{
   88661     for(i=0; i<nCol; i++){
   88662       int j;
   88663       for(j=0; j<p->nCol; j++){
   88664         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
   88665           pFKey->aCol[i].iFrom = j;
   88666           break;
   88667         }
   88668       }
   88669       if( j>=p->nCol ){
   88670         sqlite3ErrorMsg(pParse,
   88671           "unknown column \"%s\" in foreign key definition",
   88672           pFromCol->a[i].zName);
   88673         goto fk_end;
   88674       }
   88675     }
   88676   }
   88677   if( pToCol ){
   88678     for(i=0; i<nCol; i++){
   88679       int n = sqlite3Strlen30(pToCol->a[i].zName);
   88680       pFKey->aCol[i].zCol = z;
   88681       memcpy(z, pToCol->a[i].zName, n);
   88682       z[n] = 0;
   88683       z += n+1;
   88684     }
   88685   }
   88686   pFKey->isDeferred = 0;
   88687   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
   88688   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
   88689 
   88690   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   88691   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
   88692       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
   88693   );
   88694   if( pNextTo==pFKey ){
   88695     db->mallocFailed = 1;
   88696     goto fk_end;
   88697   }
   88698   if( pNextTo ){
   88699     assert( pNextTo->pPrevTo==0 );
   88700     pFKey->pNextTo = pNextTo;
   88701     pNextTo->pPrevTo = pFKey;
   88702   }
   88703 
   88704   /* Link the foreign key to the table as the last step.
   88705   */
   88706   p->pFKey = pFKey;
   88707   pFKey = 0;
   88708 
   88709 fk_end:
   88710   sqlite3DbFree(db, pFKey);
   88711 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   88712   sqlite3ExprListDelete(db, pFromCol);
   88713   sqlite3ExprListDelete(db, pToCol);
   88714 }
   88715 
   88716 /*
   88717 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
   88718 ** clause is seen as part of a foreign key definition.  The isDeferred
   88719 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
   88720 ** The behavior of the most recently created foreign key is adjusted
   88721 ** accordingly.
   88722 */
   88723 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
   88724 #ifndef SQLITE_OMIT_FOREIGN_KEY
   88725   Table *pTab;
   88726   FKey *pFKey;
   88727   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
   88728   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
   88729   pFKey->isDeferred = (u8)isDeferred;
   88730 #endif
   88731 }
   88732 
   88733 /*
   88734 ** Generate code that will erase and refill index *pIdx.  This is
   88735 ** used to initialize a newly created index or to recompute the
   88736 ** content of an index in response to a REINDEX command.
   88737 **
   88738 ** if memRootPage is not negative, it means that the index is newly
   88739 ** created.  The register specified by memRootPage contains the
   88740 ** root page number of the index.  If memRootPage is negative, then
   88741 ** the index already exists and must be cleared before being refilled and
   88742 ** the root page number of the index is taken from pIndex->tnum.
   88743 */
   88744 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   88745   Table *pTab = pIndex->pTable;  /* The table that is indexed */
   88746   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
   88747   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
   88748   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
   88749   int addr1;                     /* Address of top of loop */
   88750   int addr2;                     /* Address to jump to for next iteration */
   88751   int tnum;                      /* Root page of index */
   88752   int iPartIdxLabel;             /* Jump to this label to skip a row */
   88753   Vdbe *v;                       /* Generate code into this virtual machine */
   88754   KeyInfo *pKey;                 /* KeyInfo for index */
   88755   int regRecord;                 /* Register holding assemblied index record */
   88756   sqlite3 *db = pParse->db;      /* The database connection */
   88757   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   88758 
   88759 #ifndef SQLITE_OMIT_AUTHORIZATION
   88760   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
   88761       db->aDb[iDb].zName ) ){
   88762     return;
   88763   }
   88764 #endif
   88765 
   88766   /* Require a write-lock on the table to perform this operation */
   88767   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   88768 
   88769   v = sqlite3GetVdbe(pParse);
   88770   if( v==0 ) return;
   88771   if( memRootPage>=0 ){
   88772     tnum = memRootPage;
   88773   }else{
   88774     tnum = pIndex->tnum;
   88775   }
   88776   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
   88777 
   88778   /* Open the sorter cursor if we are to use one. */
   88779   iSorter = pParse->nTab++;
   88780   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
   88781                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
   88782 
   88783   /* Open the table. Loop through all rows of the table, inserting index
   88784   ** records into the sorter. */
   88785   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   88786   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
   88787   regRecord = sqlite3GetTempReg(pParse);
   88788 
   88789   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
   88790   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
   88791   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
   88792   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
   88793   sqlite3VdbeJumpHere(v, addr1);
   88794   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
   88795   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
   88796                     (char *)pKey, P4_KEYINFO);
   88797   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
   88798 
   88799   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
   88800   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
   88801   if( IsUniqueIndex(pIndex) && pKey!=0 ){
   88802     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
   88803     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
   88804     addr2 = sqlite3VdbeCurrentAddr(v);
   88805     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
   88806                          pIndex->nKeyCol); VdbeCoverage(v);
   88807     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
   88808   }else{
   88809     addr2 = sqlite3VdbeCurrentAddr(v);
   88810   }
   88811   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
   88812   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
   88813   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   88814   sqlite3ReleaseTempReg(pParse, regRecord);
   88815   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
   88816   sqlite3VdbeJumpHere(v, addr1);
   88817 
   88818   sqlite3VdbeAddOp1(v, OP_Close, iTab);
   88819   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
   88820   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
   88821 }
   88822 
   88823 /*
   88824 ** Allocate heap space to hold an Index object with nCol columns.
   88825 **
   88826 ** Increase the allocation size to provide an extra nExtra bytes
   88827 ** of 8-byte aligned space after the Index object and return a
   88828 ** pointer to this extra space in *ppExtra.
   88829 */
   88830 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
   88831   sqlite3 *db,         /* Database connection */
   88832   i16 nCol,            /* Total number of columns in the index */
   88833   int nExtra,          /* Number of bytes of extra space to alloc */
   88834   char **ppExtra       /* Pointer to the "extra" space */
   88835 ){
   88836   Index *p;            /* Allocated index object */
   88837   int nByte;           /* Bytes of space for Index object + arrays */
   88838 
   88839   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
   88840           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
   88841           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
   88842                  sizeof(i16)*nCol +            /* Index.aiColumn   */
   88843                  sizeof(u8)*nCol);             /* Index.aSortOrder */
   88844   p = sqlite3DbMallocZero(db, nByte + nExtra);
   88845   if( p ){
   88846     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
   88847     p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
   88848     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
   88849     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
   88850     p->aSortOrder = (u8*)pExtra;
   88851     p->nColumn = nCol;
   88852     p->nKeyCol = nCol - 1;
   88853     *ppExtra = ((char*)p) + nByte;
   88854   }
   88855   return p;
   88856 }
   88857 
   88858 /*
   88859 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
   88860 ** and pTblList is the name of the table that is to be indexed.  Both will
   88861 ** be NULL for a primary key or an index that is created to satisfy a
   88862 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
   88863 ** as the table to be indexed.  pParse->pNewTable is a table that is
   88864 ** currently being constructed by a CREATE TABLE statement.
   88865 **
   88866 ** pList is a list of columns to be indexed.  pList will be NULL if this
   88867 ** is a primary key or unique-constraint on the most recent column added
   88868 ** to the table currently under construction.
   88869 **
   88870 ** If the index is created successfully, return a pointer to the new Index
   88871 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
   88872 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
   88873 */
   88874 SQLITE_PRIVATE Index *sqlite3CreateIndex(
   88875   Parse *pParse,     /* All information about this parse */
   88876   Token *pName1,     /* First part of index name. May be NULL */
   88877   Token *pName2,     /* Second part of index name. May be NULL */
   88878   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
   88879   ExprList *pList,   /* A list of columns to be indexed */
   88880   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   88881   Token *pStart,     /* The CREATE token that begins this statement */
   88882   Expr *pPIWhere,    /* WHERE clause for partial indices */
   88883   int sortOrder,     /* Sort order of primary key when pList==NULL */
   88884   int ifNotExist     /* Omit error if index already exists */
   88885 ){
   88886   Index *pRet = 0;     /* Pointer to return */
   88887   Table *pTab = 0;     /* Table to be indexed */
   88888   Index *pIndex = 0;   /* The index to be created */
   88889   char *zName = 0;     /* Name of the index */
   88890   int nName;           /* Number of characters in zName */
   88891   int i, j;
   88892   DbFixer sFix;        /* For assigning database names to pTable */
   88893   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
   88894   sqlite3 *db = pParse->db;
   88895   Db *pDb;             /* The specific table containing the indexed database */
   88896   int iDb;             /* Index of the database that is being written */
   88897   Token *pName = 0;    /* Unqualified name of the index to create */
   88898   struct ExprList_item *pListItem; /* For looping over pList */
   88899   const Column *pTabCol;           /* A column in the table */
   88900   int nExtra = 0;                  /* Space allocated for zExtra[] */
   88901   int nExtraCol;                   /* Number of extra columns needed */
   88902   char *zExtra = 0;                /* Extra space after the Index object */
   88903   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
   88904 
   88905   assert( pParse->nErr==0 );      /* Never called with prior errors */
   88906   if( db->mallocFailed || IN_DECLARE_VTAB ){
   88907     goto exit_create_index;
   88908   }
   88909   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   88910     goto exit_create_index;
   88911   }
   88912 
   88913   /*
   88914   ** Find the table that is to be indexed.  Return early if not found.
   88915   */
   88916   if( pTblName!=0 ){
   88917 
   88918     /* Use the two-part index name to determine the database
   88919     ** to search for the table. 'Fix' the table name to this db
   88920     ** before looking up the table.
   88921     */
   88922     assert( pName1 && pName2 );
   88923     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   88924     if( iDb<0 ) goto exit_create_index;
   88925     assert( pName && pName->z );
   88926 
   88927 #ifndef SQLITE_OMIT_TEMPDB
   88928     /* If the index name was unqualified, check if the table
   88929     ** is a temp table. If so, set the database to 1. Do not do this
   88930     ** if initialising a database schema.
   88931     */
   88932     if( !db->init.busy ){
   88933       pTab = sqlite3SrcListLookup(pParse, pTblName);
   88934       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
   88935         iDb = 1;
   88936       }
   88937     }
   88938 #endif
   88939 
   88940     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
   88941     if( sqlite3FixSrcList(&sFix, pTblName) ){
   88942       /* Because the parser constructs pTblName from a single identifier,
   88943       ** sqlite3FixSrcList can never fail. */
   88944       assert(0);
   88945     }
   88946     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
   88947     assert( db->mallocFailed==0 || pTab==0 );
   88948     if( pTab==0 ) goto exit_create_index;
   88949     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
   88950       sqlite3ErrorMsg(pParse,
   88951            "cannot create a TEMP index on non-TEMP table \"%s\"",
   88952            pTab->zName);
   88953       goto exit_create_index;
   88954     }
   88955     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
   88956   }else{
   88957     assert( pName==0 );
   88958     assert( pStart==0 );
   88959     pTab = pParse->pNewTable;
   88960     if( !pTab ) goto exit_create_index;
   88961     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   88962   }
   88963   pDb = &db->aDb[iDb];
   88964 
   88965   assert( pTab!=0 );
   88966   assert( pParse->nErr==0 );
   88967   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   88968        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
   88969     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
   88970     goto exit_create_index;
   88971   }
   88972 #ifndef SQLITE_OMIT_VIEW
   88973   if( pTab->pSelect ){
   88974     sqlite3ErrorMsg(pParse, "views may not be indexed");
   88975     goto exit_create_index;
   88976   }
   88977 #endif
   88978 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88979   if( IsVirtual(pTab) ){
   88980     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
   88981     goto exit_create_index;
   88982   }
   88983 #endif
   88984 
   88985   /*
   88986   ** Find the name of the index.  Make sure there is not already another
   88987   ** index or table with the same name.
   88988   **
   88989   ** Exception:  If we are reading the names of permanent indices from the
   88990   ** sqlite_master table (because some other process changed the schema) and
   88991   ** one of the index names collides with the name of a temporary table or
   88992   ** index, then we will continue to process this index.
   88993   **
   88994   ** If pName==0 it means that we are
   88995   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
   88996   ** own name.
   88997   */
   88998   if( pName ){
   88999     zName = sqlite3NameFromToken(db, pName);
   89000     if( zName==0 ) goto exit_create_index;
   89001     assert( pName->z!=0 );
   89002     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   89003       goto exit_create_index;
   89004     }
   89005     if( !db->init.busy ){
   89006       if( sqlite3FindTable(db, zName, 0)!=0 ){
   89007         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
   89008         goto exit_create_index;
   89009       }
   89010     }
   89011     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
   89012       if( !ifNotExist ){
   89013         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
   89014       }else{
   89015         assert( !db->init.busy );
   89016         sqlite3CodeVerifySchema(pParse, iDb);
   89017       }
   89018       goto exit_create_index;
   89019     }
   89020   }else{
   89021     int n;
   89022     Index *pLoop;
   89023     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
   89024     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
   89025     if( zName==0 ){
   89026       goto exit_create_index;
   89027     }
   89028   }
   89029 
   89030   /* Check for authorization to create an index.
   89031   */
   89032 #ifndef SQLITE_OMIT_AUTHORIZATION
   89033   {
   89034     const char *zDb = pDb->zName;
   89035     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
   89036       goto exit_create_index;
   89037     }
   89038     i = SQLITE_CREATE_INDEX;
   89039     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
   89040     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
   89041       goto exit_create_index;
   89042     }
   89043   }
   89044 #endif
   89045 
   89046   /* If pList==0, it means this routine was called to make a primary
   89047   ** key out of the last column added to the table under construction.
   89048   ** So create a fake list to simulate this.
   89049   */
   89050   if( pList==0 ){
   89051     pList = sqlite3ExprListAppend(pParse, 0, 0);
   89052     if( pList==0 ) goto exit_create_index;
   89053     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
   89054                                         pTab->aCol[pTab->nCol-1].zName);
   89055     pList->a[0].sortOrder = (u8)sortOrder;
   89056   }
   89057 
   89058   /* Figure out how many bytes of space are required to store explicitly
   89059   ** specified collation sequence names.
   89060   */
   89061   for(i=0; i<pList->nExpr; i++){
   89062     Expr *pExpr = pList->a[i].pExpr;
   89063     if( pExpr ){
   89064       assert( pExpr->op==TK_COLLATE );
   89065       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
   89066     }
   89067   }
   89068 
   89069   /*
   89070   ** Allocate the index structure.
   89071   */
   89072   nName = sqlite3Strlen30(zName);
   89073   nExtraCol = pPk ? pPk->nKeyCol : 1;
   89074   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
   89075                                       nName + nExtra + 1, &zExtra);
   89076   if( db->mallocFailed ){
   89077     goto exit_create_index;
   89078   }
   89079   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
   89080   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
   89081   pIndex->zName = zExtra;
   89082   zExtra += nName + 1;
   89083   memcpy(pIndex->zName, zName, nName+1);
   89084   pIndex->pTable = pTab;
   89085   pIndex->onError = (u8)onError;
   89086   pIndex->uniqNotNull = onError!=OE_None;
   89087   pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
   89088   pIndex->pSchema = db->aDb[iDb].pSchema;
   89089   pIndex->nKeyCol = pList->nExpr;
   89090   if( pPIWhere ){
   89091     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
   89092     pIndex->pPartIdxWhere = pPIWhere;
   89093     pPIWhere = 0;
   89094   }
   89095   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   89096 
   89097   /* Check to see if we should honor DESC requests on index columns
   89098   */
   89099   if( pDb->pSchema->file_format>=4 ){
   89100     sortOrderMask = -1;   /* Honor DESC */
   89101   }else{
   89102     sortOrderMask = 0;    /* Ignore DESC */
   89103   }
   89104 
   89105   /* Scan the names of the columns of the table to be indexed and
   89106   ** load the column indices into the Index structure.  Report an error
   89107   ** if any column is not found.
   89108   **
   89109   ** TODO:  Add a test to make sure that the same column is not named
   89110   ** more than once within the same index.  Only the first instance of
   89111   ** the column will ever be used by the optimizer.  Note that using the
   89112   ** same column more than once cannot be an error because that would
   89113   ** break backwards compatibility - it needs to be a warning.
   89114   */
   89115   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
   89116     const char *zColName = pListItem->zName;
   89117     int requestedSortOrder;
   89118     char *zColl;                   /* Collation sequence name */
   89119 
   89120     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
   89121       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
   89122     }
   89123     if( j>=pTab->nCol ){
   89124       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
   89125         pTab->zName, zColName);
   89126       pParse->checkSchema = 1;
   89127       goto exit_create_index;
   89128     }
   89129     assert( pTab->nCol<=0x7fff && j<=0x7fff );
   89130     pIndex->aiColumn[i] = (i16)j;
   89131     if( pListItem->pExpr ){
   89132       int nColl;
   89133       assert( pListItem->pExpr->op==TK_COLLATE );
   89134       zColl = pListItem->pExpr->u.zToken;
   89135       nColl = sqlite3Strlen30(zColl) + 1;
   89136       assert( nExtra>=nColl );
   89137       memcpy(zExtra, zColl, nColl);
   89138       zColl = zExtra;
   89139       zExtra += nColl;
   89140       nExtra -= nColl;
   89141     }else{
   89142       zColl = pTab->aCol[j].zColl;
   89143       if( !zColl ) zColl = "BINARY";
   89144     }
   89145     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
   89146       goto exit_create_index;
   89147     }
   89148     pIndex->azColl[i] = zColl;
   89149     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
   89150     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
   89151     if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
   89152   }
   89153   if( pPk ){
   89154     for(j=0; j<pPk->nKeyCol; j++){
   89155       int x = pPk->aiColumn[j];
   89156       if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
   89157         pIndex->nColumn--;
   89158       }else{
   89159         pIndex->aiColumn[i] = x;
   89160         pIndex->azColl[i] = pPk->azColl[j];
   89161         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
   89162         i++;
   89163       }
   89164     }
   89165     assert( i==pIndex->nColumn );
   89166   }else{
   89167     pIndex->aiColumn[i] = -1;
   89168     pIndex->azColl[i] = "BINARY";
   89169   }
   89170   sqlite3DefaultRowEst(pIndex);
   89171   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
   89172 
   89173   if( pTab==pParse->pNewTable ){
   89174     /* This routine has been called to create an automatic index as a
   89175     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
   89176     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
   89177     ** i.e. one of:
   89178     **
   89179     ** CREATE TABLE t(x PRIMARY KEY, y);
   89180     ** CREATE TABLE t(x, y, UNIQUE(x, y));
   89181     **
   89182     ** Either way, check to see if the table already has such an index. If
   89183     ** so, don't bother creating this one. This only applies to
   89184     ** automatically created indices. Users can do as they wish with
   89185     ** explicit indices.
   89186     **
   89187     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
   89188     ** (and thus suppressing the second one) even if they have different
   89189     ** sort orders.
   89190     **
   89191     ** If there are different collating sequences or if the columns of
   89192     ** the constraint occur in different orders, then the constraints are
   89193     ** considered distinct and both result in separate indices.
   89194     */
   89195     Index *pIdx;
   89196     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   89197       int k;
   89198       assert( IsUniqueIndex(pIdx) );
   89199       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
   89200       assert( IsUniqueIndex(pIndex) );
   89201 
   89202       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
   89203       for(k=0; k<pIdx->nKeyCol; k++){
   89204         const char *z1;
   89205         const char *z2;
   89206         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
   89207         z1 = pIdx->azColl[k];
   89208         z2 = pIndex->azColl[k];
   89209         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
   89210       }
   89211       if( k==pIdx->nKeyCol ){
   89212         if( pIdx->onError!=pIndex->onError ){
   89213           /* This constraint creates the same index as a previous
   89214           ** constraint specified somewhere in the CREATE TABLE statement.
   89215           ** However the ON CONFLICT clauses are different. If both this
   89216           ** constraint and the previous equivalent constraint have explicit
   89217           ** ON CONFLICT clauses this is an error. Otherwise, use the
   89218           ** explicitly specified behavior for the index.
   89219           */
   89220           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
   89221             sqlite3ErrorMsg(pParse,
   89222                 "conflicting ON CONFLICT clauses specified", 0);
   89223           }
   89224           if( pIdx->onError==OE_Default ){
   89225             pIdx->onError = pIndex->onError;
   89226           }
   89227         }
   89228         goto exit_create_index;
   89229       }
   89230     }
   89231   }
   89232 
   89233   /* Link the new Index structure to its table and to the other
   89234   ** in-memory database structures.
   89235   */
   89236   if( db->init.busy ){
   89237     Index *p;
   89238     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   89239     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
   89240                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
   89241                           pIndex);
   89242     if( p ){
   89243       assert( p==pIndex );  /* Malloc must have failed */
   89244       db->mallocFailed = 1;
   89245       goto exit_create_index;
   89246     }
   89247     db->flags |= SQLITE_InternChanges;
   89248     if( pTblName!=0 ){
   89249       pIndex->tnum = db->init.newTnum;
   89250     }
   89251   }
   89252 
   89253   /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
   89254   ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
   89255   ** emit code to allocate the index rootpage on disk and make an entry for
   89256   ** the index in the sqlite_master table and populate the index with
   89257   ** content.  But, do not do this if we are simply reading the sqlite_master
   89258   ** table to parse the schema, or if this index is the PRIMARY KEY index
   89259   ** of a WITHOUT ROWID table.
   89260   **
   89261   ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
   89262   ** or UNIQUE index in a CREATE TABLE statement.  Since the table
   89263   ** has just been created, it contains no data and the index initialization
   89264   ** step can be skipped.
   89265   */
   89266   else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
   89267     Vdbe *v;
   89268     char *zStmt;
   89269     int iMem = ++pParse->nMem;
   89270 
   89271     v = sqlite3GetVdbe(pParse);
   89272     if( v==0 ) goto exit_create_index;
   89273 
   89274 
   89275     /* Create the rootpage for the index
   89276     */
   89277     sqlite3BeginWriteOperation(pParse, 1, iDb);
   89278     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
   89279 
   89280     /* Gather the complete text of the CREATE INDEX statement into
   89281     ** the zStmt variable
   89282     */
   89283     if( pStart ){
   89284       int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
   89285       if( pName->z[n-1]==';' ) n--;
   89286       /* A named index with an explicit CREATE INDEX statement */
   89287       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
   89288         onError==OE_None ? "" : " UNIQUE", n, pName->z);
   89289     }else{
   89290       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
   89291       /* zStmt = sqlite3MPrintf(""); */
   89292       zStmt = 0;
   89293     }
   89294 
   89295     /* Add an entry in sqlite_master for this index
   89296     */
   89297     sqlite3NestedParse(pParse,
   89298         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
   89299         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   89300         pIndex->zName,
   89301         pTab->zName,
   89302         iMem,
   89303         zStmt
   89304     );
   89305     sqlite3DbFree(db, zStmt);
   89306 
   89307     /* Fill the index with data and reparse the schema. Code an OP_Expire
   89308     ** to invalidate all pre-compiled statements.
   89309     */
   89310     if( pTblName ){
   89311       sqlite3RefillIndex(pParse, pIndex, iMem);
   89312       sqlite3ChangeCookie(pParse, iDb);
   89313       sqlite3VdbeAddParseSchemaOp(v, iDb,
   89314          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
   89315       sqlite3VdbeAddOp1(v, OP_Expire, 0);
   89316     }
   89317   }
   89318 
   89319   /* When adding an index to the list of indices for a table, make
   89320   ** sure all indices labeled OE_Replace come after all those labeled
   89321   ** OE_Ignore.  This is necessary for the correct constraint check
   89322   ** processing (in sqlite3GenerateConstraintChecks()) as part of
   89323   ** UPDATE and INSERT statements.
   89324   */
   89325   if( db->init.busy || pTblName==0 ){
   89326     if( onError!=OE_Replace || pTab->pIndex==0
   89327          || pTab->pIndex->onError==OE_Replace){
   89328       pIndex->pNext = pTab->pIndex;
   89329       pTab->pIndex = pIndex;
   89330     }else{
   89331       Index *pOther = pTab->pIndex;
   89332       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
   89333         pOther = pOther->pNext;
   89334       }
   89335       pIndex->pNext = pOther->pNext;
   89336       pOther->pNext = pIndex;
   89337     }
   89338     pRet = pIndex;
   89339     pIndex = 0;
   89340   }
   89341 
   89342   /* Clean up before exiting */
   89343 exit_create_index:
   89344   if( pIndex ) freeIndex(db, pIndex);
   89345   sqlite3ExprDelete(db, pPIWhere);
   89346   sqlite3ExprListDelete(db, pList);
   89347   sqlite3SrcListDelete(db, pTblName);
   89348   sqlite3DbFree(db, zName);
   89349   return pRet;
   89350 }
   89351 
   89352 /*
   89353 ** Fill the Index.aiRowEst[] array with default information - information
   89354 ** to be used when we have not run the ANALYZE command.
   89355 **
   89356 ** aiRowEst[0] is suppose to contain the number of elements in the index.
   89357 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
   89358 ** number of rows in the table that match any particular value of the
   89359 ** first column of the index.  aiRowEst[2] is an estimate of the number
   89360 ** of rows that match any particular combination of the first 2 columns
   89361 ** of the index.  And so forth.  It must always be the case that
   89362 *
   89363 **           aiRowEst[N]<=aiRowEst[N-1]
   89364 **           aiRowEst[N]>=1
   89365 **
   89366 ** Apart from that, we have little to go on besides intuition as to
   89367 ** how aiRowEst[] should be initialized.  The numbers generated here
   89368 ** are based on typical values found in actual indices.
   89369 */
   89370 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
   89371   /*                10,  9,  8,  7,  6 */
   89372   LogEst aVal[] = { 33, 32, 30, 28, 26 };
   89373   LogEst *a = pIdx->aiRowLogEst;
   89374   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
   89375   int i;
   89376 
   89377   /* Set the first entry (number of rows in the index) to the estimated
   89378   ** number of rows in the table. Or 10, if the estimated number of rows
   89379   ** in the table is less than that.  */
   89380   a[0] = pIdx->pTable->nRowLogEst;
   89381   if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
   89382 
   89383   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
   89384   ** 6 and each subsequent value (if any) is 5.  */
   89385   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
   89386   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
   89387     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
   89388   }
   89389 
   89390   assert( 0==sqlite3LogEst(1) );
   89391   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
   89392 }
   89393 
   89394 /*
   89395 ** This routine will drop an existing named index.  This routine
   89396 ** implements the DROP INDEX statement.
   89397 */
   89398 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
   89399   Index *pIndex;
   89400   Vdbe *v;
   89401   sqlite3 *db = pParse->db;
   89402   int iDb;
   89403 
   89404   assert( pParse->nErr==0 );   /* Never called with prior errors */
   89405   if( db->mallocFailed ){
   89406     goto exit_drop_index;
   89407   }
   89408   assert( pName->nSrc==1 );
   89409   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   89410     goto exit_drop_index;
   89411   }
   89412   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
   89413   if( pIndex==0 ){
   89414     if( !ifExists ){
   89415       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
   89416     }else{
   89417       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   89418     }
   89419     pParse->checkSchema = 1;
   89420     goto exit_drop_index;
   89421   }
   89422   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
   89423     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
   89424       "or PRIMARY KEY constraint cannot be dropped", 0);
   89425     goto exit_drop_index;
   89426   }
   89427   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   89428 #ifndef SQLITE_OMIT_AUTHORIZATION
   89429   {
   89430     int code = SQLITE_DROP_INDEX;
   89431     Table *pTab = pIndex->pTable;
   89432     const char *zDb = db->aDb[iDb].zName;
   89433     const char *zTab = SCHEMA_TABLE(iDb);
   89434     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   89435       goto exit_drop_index;
   89436     }
   89437     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
   89438     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
   89439       goto exit_drop_index;
   89440     }
   89441   }
   89442 #endif
   89443 
   89444   /* Generate code to remove the index and from the master table */
   89445   v = sqlite3GetVdbe(pParse);
   89446   if( v ){
   89447     sqlite3BeginWriteOperation(pParse, 1, iDb);
   89448     sqlite3NestedParse(pParse,
   89449        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
   89450        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
   89451     );
   89452     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
   89453     sqlite3ChangeCookie(pParse, iDb);
   89454     destroyRootPage(pParse, pIndex->tnum, iDb);
   89455     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
   89456   }
   89457 
   89458 exit_drop_index:
   89459   sqlite3SrcListDelete(db, pName);
   89460 }
   89461 
   89462 /*
   89463 ** pArray is a pointer to an array of objects. Each object in the
   89464 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
   89465 ** to extend the array so that there is space for a new object at the end.
   89466 **
   89467 ** When this function is called, *pnEntry contains the current size of
   89468 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
   89469 ** in total).
   89470 **
   89471 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
   89472 ** space allocated for the new object is zeroed, *pnEntry updated to
   89473 ** reflect the new size of the array and a pointer to the new allocation
   89474 ** returned. *pIdx is set to the index of the new array entry in this case.
   89475 **
   89476 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
   89477 ** unchanged and a copy of pArray returned.
   89478 */
   89479 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
   89480   sqlite3 *db,      /* Connection to notify of malloc failures */
   89481   void *pArray,     /* Array of objects.  Might be reallocated */
   89482   int szEntry,      /* Size of each object in the array */
   89483   int *pnEntry,     /* Number of objects currently in use */
   89484   int *pIdx         /* Write the index of a new slot here */
   89485 ){
   89486   char *z;
   89487   int n = *pnEntry;
   89488   if( (n & (n-1))==0 ){
   89489     int sz = (n==0) ? 1 : 2*n;
   89490     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
   89491     if( pNew==0 ){
   89492       *pIdx = -1;
   89493       return pArray;
   89494     }
   89495     pArray = pNew;
   89496   }
   89497   z = (char*)pArray;
   89498   memset(&z[n * szEntry], 0, szEntry);
   89499   *pIdx = n;
   89500   ++*pnEntry;
   89501   return pArray;
   89502 }
   89503 
   89504 /*
   89505 ** Append a new element to the given IdList.  Create a new IdList if
   89506 ** need be.
   89507 **
   89508 ** A new IdList is returned, or NULL if malloc() fails.
   89509 */
   89510 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
   89511   int i;
   89512   if( pList==0 ){
   89513     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
   89514     if( pList==0 ) return 0;
   89515   }
   89516   pList->a = sqlite3ArrayAllocate(
   89517       db,
   89518       pList->a,
   89519       sizeof(pList->a[0]),
   89520       &pList->nId,
   89521       &i
   89522   );
   89523   if( i<0 ){
   89524     sqlite3IdListDelete(db, pList);
   89525     return 0;
   89526   }
   89527   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
   89528   return pList;
   89529 }
   89530 
   89531 /*
   89532 ** Delete an IdList.
   89533 */
   89534 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
   89535   int i;
   89536   if( pList==0 ) return;
   89537   for(i=0; i<pList->nId; i++){
   89538     sqlite3DbFree(db, pList->a[i].zName);
   89539   }
   89540   sqlite3DbFree(db, pList->a);
   89541   sqlite3DbFree(db, pList);
   89542 }
   89543 
   89544 /*
   89545 ** Return the index in pList of the identifier named zId.  Return -1
   89546 ** if not found.
   89547 */
   89548 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
   89549   int i;
   89550   if( pList==0 ) return -1;
   89551   for(i=0; i<pList->nId; i++){
   89552     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
   89553   }
   89554   return -1;
   89555 }
   89556 
   89557 /*
   89558 ** Expand the space allocated for the given SrcList object by
   89559 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
   89560 ** New slots are zeroed.
   89561 **
   89562 ** For example, suppose a SrcList initially contains two entries: A,B.
   89563 ** To append 3 new entries onto the end, do this:
   89564 **
   89565 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
   89566 **
   89567 ** After the call above it would contain:  A, B, nil, nil, nil.
   89568 ** If the iStart argument had been 1 instead of 2, then the result
   89569 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
   89570 ** the iStart value would be 0.  The result then would
   89571 ** be: nil, nil, nil, A, B.
   89572 **
   89573 ** If a memory allocation fails the SrcList is unchanged.  The
   89574 ** db->mallocFailed flag will be set to true.
   89575 */
   89576 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
   89577   sqlite3 *db,       /* Database connection to notify of OOM errors */
   89578   SrcList *pSrc,     /* The SrcList to be enlarged */
   89579   int nExtra,        /* Number of new slots to add to pSrc->a[] */
   89580   int iStart         /* Index in pSrc->a[] of first new slot */
   89581 ){
   89582   int i;
   89583 
   89584   /* Sanity checking on calling parameters */
   89585   assert( iStart>=0 );
   89586   assert( nExtra>=1 );
   89587   assert( pSrc!=0 );
   89588   assert( iStart<=pSrc->nSrc );
   89589 
   89590   /* Allocate additional space if needed */
   89591   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
   89592     SrcList *pNew;
   89593     int nAlloc = pSrc->nSrc+nExtra;
   89594     int nGot;
   89595     pNew = sqlite3DbRealloc(db, pSrc,
   89596                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
   89597     if( pNew==0 ){
   89598       assert( db->mallocFailed );
   89599       return pSrc;
   89600     }
   89601     pSrc = pNew;
   89602     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
   89603     pSrc->nAlloc = nGot;
   89604   }
   89605 
   89606   /* Move existing slots that come after the newly inserted slots
   89607   ** out of the way */
   89608   for(i=pSrc->nSrc-1; i>=iStart; i--){
   89609     pSrc->a[i+nExtra] = pSrc->a[i];
   89610   }
   89611   pSrc->nSrc += nExtra;
   89612 
   89613   /* Zero the newly allocated slots */
   89614   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
   89615   for(i=iStart; i<iStart+nExtra; i++){
   89616     pSrc->a[i].iCursor = -1;
   89617   }
   89618 
   89619   /* Return a pointer to the enlarged SrcList */
   89620   return pSrc;
   89621 }
   89622 
   89623 
   89624 /*
   89625 ** Append a new table name to the given SrcList.  Create a new SrcList if
   89626 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
   89627 **
   89628 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
   89629 ** SrcList might be the same as the SrcList that was input or it might be
   89630 ** a new one.  If an OOM error does occurs, then the prior value of pList
   89631 ** that is input to this routine is automatically freed.
   89632 **
   89633 ** If pDatabase is not null, it means that the table has an optional
   89634 ** database name prefix.  Like this:  "database.table".  The pDatabase
   89635 ** points to the table name and the pTable points to the database name.
   89636 ** The SrcList.a[].zName field is filled with the table name which might
   89637 ** come from pTable (if pDatabase is NULL) or from pDatabase.
   89638 ** SrcList.a[].zDatabase is filled with the database name from pTable,
   89639 ** or with NULL if no database is specified.
   89640 **
   89641 ** In other words, if call like this:
   89642 **
   89643 **         sqlite3SrcListAppend(D,A,B,0);
   89644 **
   89645 ** Then B is a table name and the database name is unspecified.  If called
   89646 ** like this:
   89647 **
   89648 **         sqlite3SrcListAppend(D,A,B,C);
   89649 **
   89650 ** Then C is the table name and B is the database name.  If C is defined
   89651 ** then so is B.  In other words, we never have a case where:
   89652 **
   89653 **         sqlite3SrcListAppend(D,A,0,C);
   89654 **
   89655 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
   89656 ** before being added to the SrcList.
   89657 */
   89658 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
   89659   sqlite3 *db,        /* Connection to notify of malloc failures */
   89660   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
   89661   Token *pTable,      /* Table to append */
   89662   Token *pDatabase    /* Database of the table */
   89663 ){
   89664   struct SrcList_item *pItem;
   89665   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
   89666   if( pList==0 ){
   89667     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
   89668     if( pList==0 ) return 0;
   89669     pList->nAlloc = 1;
   89670   }
   89671   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
   89672   if( db->mallocFailed ){
   89673     sqlite3SrcListDelete(db, pList);
   89674     return 0;
   89675   }
   89676   pItem = &pList->a[pList->nSrc-1];
   89677   if( pDatabase && pDatabase->z==0 ){
   89678     pDatabase = 0;
   89679   }
   89680   if( pDatabase ){
   89681     Token *pTemp = pDatabase;
   89682     pDatabase = pTable;
   89683     pTable = pTemp;
   89684   }
   89685   pItem->zName = sqlite3NameFromToken(db, pTable);
   89686   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
   89687   return pList;
   89688 }
   89689 
   89690 /*
   89691 ** Assign VdbeCursor index numbers to all tables in a SrcList
   89692 */
   89693 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   89694   int i;
   89695   struct SrcList_item *pItem;
   89696   assert(pList || pParse->db->mallocFailed );
   89697   if( pList ){
   89698     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   89699       if( pItem->iCursor>=0 ) break;
   89700       pItem->iCursor = pParse->nTab++;
   89701       if( pItem->pSelect ){
   89702         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
   89703       }
   89704     }
   89705   }
   89706 }
   89707 
   89708 /*
   89709 ** Delete an entire SrcList including all its substructure.
   89710 */
   89711 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   89712   int i;
   89713   struct SrcList_item *pItem;
   89714   if( pList==0 ) return;
   89715   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
   89716     sqlite3DbFree(db, pItem->zDatabase);
   89717     sqlite3DbFree(db, pItem->zName);
   89718     sqlite3DbFree(db, pItem->zAlias);
   89719     sqlite3DbFree(db, pItem->zIndex);
   89720     sqlite3DeleteTable(db, pItem->pTab);
   89721     sqlite3SelectDelete(db, pItem->pSelect);
   89722     sqlite3ExprDelete(db, pItem->pOn);
   89723     sqlite3IdListDelete(db, pItem->pUsing);
   89724   }
   89725   sqlite3DbFree(db, pList);
   89726 }
   89727 
   89728 /*
   89729 ** This routine is called by the parser to add a new term to the
   89730 ** end of a growing FROM clause.  The "p" parameter is the part of
   89731 ** the FROM clause that has already been constructed.  "p" is NULL
   89732 ** if this is the first term of the FROM clause.  pTable and pDatabase
   89733 ** are the name of the table and database named in the FROM clause term.
   89734 ** pDatabase is NULL if the database name qualifier is missing - the
   89735 ** usual case.  If the term has a alias, then pAlias points to the
   89736 ** alias token.  If the term is a subquery, then pSubquery is the
   89737 ** SELECT statement that the subquery encodes.  The pTable and
   89738 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
   89739 ** parameters are the content of the ON and USING clauses.
   89740 **
   89741 ** Return a new SrcList which encodes is the FROM with the new
   89742 ** term added.
   89743 */
   89744 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   89745   Parse *pParse,          /* Parsing context */
   89746   SrcList *p,             /* The left part of the FROM clause already seen */
   89747   Token *pTable,          /* Name of the table to add to the FROM clause */
   89748   Token *pDatabase,       /* Name of the database containing pTable */
   89749   Token *pAlias,          /* The right-hand side of the AS subexpression */
   89750   Select *pSubquery,      /* A subquery used in place of a table name */
   89751   Expr *pOn,              /* The ON clause of a join */
   89752   IdList *pUsing          /* The USING clause of a join */
   89753 ){
   89754   struct SrcList_item *pItem;
   89755   sqlite3 *db = pParse->db;
   89756   if( !p && (pOn || pUsing) ){
   89757     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
   89758       (pOn ? "ON" : "USING")
   89759     );
   89760     goto append_from_error;
   89761   }
   89762   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
   89763   if( p==0 || NEVER(p->nSrc==0) ){
   89764     goto append_from_error;
   89765   }
   89766   pItem = &p->a[p->nSrc-1];
   89767   assert( pAlias!=0 );
   89768   if( pAlias->n ){
   89769     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
   89770   }
   89771   pItem->pSelect = pSubquery;
   89772   pItem->pOn = pOn;
   89773   pItem->pUsing = pUsing;
   89774   return p;
   89775 
   89776  append_from_error:
   89777   assert( p==0 );
   89778   sqlite3ExprDelete(db, pOn);
   89779   sqlite3IdListDelete(db, pUsing);
   89780   sqlite3SelectDelete(db, pSubquery);
   89781   return 0;
   89782 }
   89783 
   89784 /*
   89785 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
   89786 ** element of the source-list passed as the second argument.
   89787 */
   89788 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
   89789   assert( pIndexedBy!=0 );
   89790   if( p && ALWAYS(p->nSrc>0) ){
   89791     struct SrcList_item *pItem = &p->a[p->nSrc-1];
   89792     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
   89793     if( pIndexedBy->n==1 && !pIndexedBy->z ){
   89794       /* A "NOT INDEXED" clause was supplied. See parse.y
   89795       ** construct "indexed_opt" for details. */
   89796       pItem->notIndexed = 1;
   89797     }else{
   89798       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
   89799     }
   89800   }
   89801 }
   89802 
   89803 /*
   89804 ** When building up a FROM clause in the parser, the join operator
   89805 ** is initially attached to the left operand.  But the code generator
   89806 ** expects the join operator to be on the right operand.  This routine
   89807 ** Shifts all join operators from left to right for an entire FROM
   89808 ** clause.
   89809 **
   89810 ** Example: Suppose the join is like this:
   89811 **
   89812 **           A natural cross join B
   89813 **
   89814 ** The operator is "natural cross join".  The A and B operands are stored
   89815 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
   89816 ** operator with A.  This routine shifts that operator over to B.
   89817 */
   89818 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
   89819   if( p ){
   89820     int i;
   89821     assert( p->a || p->nSrc==0 );
   89822     for(i=p->nSrc-1; i>0; i--){
   89823       p->a[i].jointype = p->a[i-1].jointype;
   89824     }
   89825     p->a[0].jointype = 0;
   89826   }
   89827 }
   89828 
   89829 /*
   89830 ** Begin a transaction
   89831 */
   89832 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
   89833   sqlite3 *db;
   89834   Vdbe *v;
   89835   int i;
   89836 
   89837   assert( pParse!=0 );
   89838   db = pParse->db;
   89839   assert( db!=0 );
   89840 /*  if( db->aDb[0].pBt==0 ) return; */
   89841   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
   89842     return;
   89843   }
   89844   v = sqlite3GetVdbe(pParse);
   89845   if( !v ) return;
   89846   if( type!=TK_DEFERRED ){
   89847     for(i=0; i<db->nDb; i++){
   89848       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
   89849       sqlite3VdbeUsesBtree(v, i);
   89850     }
   89851   }
   89852   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
   89853 }
   89854 
   89855 /*
   89856 ** Commit a transaction
   89857 */
   89858 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
   89859   Vdbe *v;
   89860 
   89861   assert( pParse!=0 );
   89862   assert( pParse->db!=0 );
   89863   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
   89864     return;
   89865   }
   89866   v = sqlite3GetVdbe(pParse);
   89867   if( v ){
   89868     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
   89869   }
   89870 }
   89871 
   89872 /*
   89873 ** Rollback a transaction
   89874 */
   89875 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
   89876   Vdbe *v;
   89877 
   89878   assert( pParse!=0 );
   89879   assert( pParse->db!=0 );
   89880   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
   89881     return;
   89882   }
   89883   v = sqlite3GetVdbe(pParse);
   89884   if( v ){
   89885     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
   89886   }
   89887 }
   89888 
   89889 /*
   89890 ** This function is called by the parser when it parses a command to create,
   89891 ** release or rollback an SQL savepoint.
   89892 */
   89893 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
   89894   char *zName = sqlite3NameFromToken(pParse->db, pName);
   89895   if( zName ){
   89896     Vdbe *v = sqlite3GetVdbe(pParse);
   89897 #ifndef SQLITE_OMIT_AUTHORIZATION
   89898     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
   89899     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
   89900 #endif
   89901     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
   89902       sqlite3DbFree(pParse->db, zName);
   89903       return;
   89904     }
   89905     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
   89906   }
   89907 }
   89908 
   89909 /*
   89910 ** Make sure the TEMP database is open and available for use.  Return
   89911 ** the number of errors.  Leave any error messages in the pParse structure.
   89912 */
   89913 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
   89914   sqlite3 *db = pParse->db;
   89915   if( db->aDb[1].pBt==0 && !pParse->explain ){
   89916     int rc;
   89917     Btree *pBt;
   89918     static const int flags =
   89919           SQLITE_OPEN_READWRITE |
   89920           SQLITE_OPEN_CREATE |
   89921           SQLITE_OPEN_EXCLUSIVE |
   89922           SQLITE_OPEN_DELETEONCLOSE |
   89923           SQLITE_OPEN_TEMP_DB;
   89924 
   89925     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
   89926     if( rc!=SQLITE_OK ){
   89927       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
   89928         "file for storing temporary tables");
   89929       pParse->rc = rc;
   89930       return 1;
   89931     }
   89932     db->aDb[1].pBt = pBt;
   89933     assert( db->aDb[1].pSchema );
   89934     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
   89935       db->mallocFailed = 1;
   89936       return 1;
   89937     }
   89938   }
   89939   return 0;
   89940 }
   89941 
   89942 /*
   89943 ** Record the fact that the schema cookie will need to be verified
   89944 ** for database iDb.  The code to actually verify the schema cookie
   89945 ** will occur at the end of the top-level VDBE and will be generated
   89946 ** later, by sqlite3FinishCoding().
   89947 */
   89948 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
   89949   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   89950   sqlite3 *db = pToplevel->db;
   89951 
   89952   assert( iDb>=0 && iDb<db->nDb );
   89953   assert( db->aDb[iDb].pBt!=0 || iDb==1 );
   89954   assert( iDb<SQLITE_MAX_ATTACHED+2 );
   89955   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   89956   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
   89957     DbMaskSet(pToplevel->cookieMask, iDb);
   89958     pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
   89959     if( !OMIT_TEMPDB && iDb==1 ){
   89960       sqlite3OpenTempDatabase(pToplevel);
   89961     }
   89962   }
   89963 }
   89964 
   89965 /*
   89966 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
   89967 ** attached database. Otherwise, invoke it for the database named zDb only.
   89968 */
   89969 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
   89970   sqlite3 *db = pParse->db;
   89971   int i;
   89972   for(i=0; i<db->nDb; i++){
   89973     Db *pDb = &db->aDb[i];
   89974     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
   89975       sqlite3CodeVerifySchema(pParse, i);
   89976     }
   89977   }
   89978 }
   89979 
   89980 /*
   89981 ** Generate VDBE code that prepares for doing an operation that
   89982 ** might change the database.
   89983 **
   89984 ** This routine starts a new transaction if we are not already within
   89985 ** a transaction.  If we are already within a transaction, then a checkpoint
   89986 ** is set if the setStatement parameter is true.  A checkpoint should
   89987 ** be set for operations that might fail (due to a constraint) part of
   89988 ** the way through and which will need to undo some writes without having to
   89989 ** rollback the whole transaction.  For operations where all constraints
   89990 ** can be checked before any changes are made to the database, it is never
   89991 ** necessary to undo a write and the checkpoint should not be set.
   89992 */
   89993 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
   89994   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   89995   sqlite3CodeVerifySchema(pParse, iDb);
   89996   DbMaskSet(pToplevel->writeMask, iDb);
   89997   pToplevel->isMultiWrite |= setStatement;
   89998 }
   89999 
   90000 /*
   90001 ** Indicate that the statement currently under construction might write
   90002 ** more than one entry (example: deleting one row then inserting another,
   90003 ** inserting multiple rows in a table, or inserting a row and index entries.)
   90004 ** If an abort occurs after some of these writes have completed, then it will
   90005 ** be necessary to undo the completed writes.
   90006 */
   90007 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
   90008   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   90009   pToplevel->isMultiWrite = 1;
   90010 }
   90011 
   90012 /*
   90013 ** The code generator calls this routine if is discovers that it is
   90014 ** possible to abort a statement prior to completion.  In order to
   90015 ** perform this abort without corrupting the database, we need to make
   90016 ** sure that the statement is protected by a statement transaction.
   90017 **
   90018 ** Technically, we only need to set the mayAbort flag if the
   90019 ** isMultiWrite flag was previously set.  There is a time dependency
   90020 ** such that the abort must occur after the multiwrite.  This makes
   90021 ** some statements involving the REPLACE conflict resolution algorithm
   90022 ** go a little faster.  But taking advantage of this time dependency
   90023 ** makes it more difficult to prove that the code is correct (in
   90024 ** particular, it prevents us from writing an effective
   90025 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
   90026 ** to take the safe route and skip the optimization.
   90027 */
   90028 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
   90029   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   90030   pToplevel->mayAbort = 1;
   90031 }
   90032 
   90033 /*
   90034 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
   90035 ** error. The onError parameter determines which (if any) of the statement
   90036 ** and/or current transaction is rolled back.
   90037 */
   90038 SQLITE_PRIVATE void sqlite3HaltConstraint(
   90039   Parse *pParse,    /* Parsing context */
   90040   int errCode,      /* extended error code */
   90041   int onError,      /* Constraint type */
   90042   char *p4,         /* Error message */
   90043   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
   90044   u8 p5Errmsg       /* P5_ErrMsg type */
   90045 ){
   90046   Vdbe *v = sqlite3GetVdbe(pParse);
   90047   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
   90048   if( onError==OE_Abort ){
   90049     sqlite3MayAbort(pParse);
   90050   }
   90051   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
   90052   if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
   90053 }
   90054 
   90055 /*
   90056 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
   90057 */
   90058 SQLITE_PRIVATE void sqlite3UniqueConstraint(
   90059   Parse *pParse,    /* Parsing context */
   90060   int onError,      /* Constraint type */
   90061   Index *pIdx       /* The index that triggers the constraint */
   90062 ){
   90063   char *zErr;
   90064   int j;
   90065   StrAccum errMsg;
   90066   Table *pTab = pIdx->pTable;
   90067 
   90068   sqlite3StrAccumInit(&errMsg, 0, 0, 200);
   90069   errMsg.db = pParse->db;
   90070   for(j=0; j<pIdx->nKeyCol; j++){
   90071     char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
   90072     if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
   90073     sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
   90074     sqlite3StrAccumAppend(&errMsg, ".", 1);
   90075     sqlite3StrAccumAppendAll(&errMsg, zCol);
   90076   }
   90077   zErr = sqlite3StrAccumFinish(&errMsg);
   90078   sqlite3HaltConstraint(pParse,
   90079     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
   90080                             : SQLITE_CONSTRAINT_UNIQUE,
   90081     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
   90082 }
   90083 
   90084 
   90085 /*
   90086 ** Code an OP_Halt due to non-unique rowid.
   90087 */
   90088 SQLITE_PRIVATE void sqlite3RowidConstraint(
   90089   Parse *pParse,    /* Parsing context */
   90090   int onError,      /* Conflict resolution algorithm */
   90091   Table *pTab       /* The table with the non-unique rowid */
   90092 ){
   90093   char *zMsg;
   90094   int rc;
   90095   if( pTab->iPKey>=0 ){
   90096     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
   90097                           pTab->aCol[pTab->iPKey].zName);
   90098     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
   90099   }else{
   90100     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
   90101     rc = SQLITE_CONSTRAINT_ROWID;
   90102   }
   90103   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
   90104                         P5_ConstraintUnique);
   90105 }
   90106 
   90107 /*
   90108 ** Check to see if pIndex uses the collating sequence pColl.  Return
   90109 ** true if it does and false if it does not.
   90110 */
   90111 #ifndef SQLITE_OMIT_REINDEX
   90112 static int collationMatch(const char *zColl, Index *pIndex){
   90113   int i;
   90114   assert( zColl!=0 );
   90115   for(i=0; i<pIndex->nColumn; i++){
   90116     const char *z = pIndex->azColl[i];
   90117     assert( z!=0 || pIndex->aiColumn[i]<0 );
   90118     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
   90119       return 1;
   90120     }
   90121   }
   90122   return 0;
   90123 }
   90124 #endif
   90125 
   90126 /*
   90127 ** Recompute all indices of pTab that use the collating sequence pColl.
   90128 ** If pColl==0 then recompute all indices of pTab.
   90129 */
   90130 #ifndef SQLITE_OMIT_REINDEX
   90131 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
   90132   Index *pIndex;              /* An index associated with pTab */
   90133 
   90134   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   90135     if( zColl==0 || collationMatch(zColl, pIndex) ){
   90136       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   90137       sqlite3BeginWriteOperation(pParse, 0, iDb);
   90138       sqlite3RefillIndex(pParse, pIndex, -1);
   90139     }
   90140   }
   90141 }
   90142 #endif
   90143 
   90144 /*
   90145 ** Recompute all indices of all tables in all databases where the
   90146 ** indices use the collating sequence pColl.  If pColl==0 then recompute
   90147 ** all indices everywhere.
   90148 */
   90149 #ifndef SQLITE_OMIT_REINDEX
   90150 static void reindexDatabases(Parse *pParse, char const *zColl){
   90151   Db *pDb;                    /* A single database */
   90152   int iDb;                    /* The database index number */
   90153   sqlite3 *db = pParse->db;   /* The database connection */
   90154   HashElem *k;                /* For looping over tables in pDb */
   90155   Table *pTab;                /* A table in the database */
   90156 
   90157   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
   90158   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   90159     assert( pDb!=0 );
   90160     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   90161       pTab = (Table*)sqliteHashData(k);
   90162       reindexTable(pParse, pTab, zColl);
   90163     }
   90164   }
   90165 }
   90166 #endif
   90167 
   90168 /*
   90169 ** Generate code for the REINDEX command.
   90170 **
   90171 **        REINDEX                            -- 1
   90172 **        REINDEX  <collation>               -- 2
   90173 **        REINDEX  ?<database>.?<tablename>  -- 3
   90174 **        REINDEX  ?<database>.?<indexname>  -- 4
   90175 **
   90176 ** Form 1 causes all indices in all attached databases to be rebuilt.
   90177 ** Form 2 rebuilds all indices in all databases that use the named
   90178 ** collating function.  Forms 3 and 4 rebuild the named index or all
   90179 ** indices associated with the named table.
   90180 */
   90181 #ifndef SQLITE_OMIT_REINDEX
   90182 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
   90183   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
   90184   char *z;                    /* Name of a table or index */
   90185   const char *zDb;            /* Name of the database */
   90186   Table *pTab;                /* A table in the database */
   90187   Index *pIndex;              /* An index associated with pTab */
   90188   int iDb;                    /* The database index number */
   90189   sqlite3 *db = pParse->db;   /* The database connection */
   90190   Token *pObjName;            /* Name of the table or index to be reindexed */
   90191 
   90192   /* Read the database schema. If an error occurs, leave an error message
   90193   ** and code in pParse and return NULL. */
   90194   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   90195     return;
   90196   }
   90197 
   90198   if( pName1==0 ){
   90199     reindexDatabases(pParse, 0);
   90200     return;
   90201   }else if( NEVER(pName2==0) || pName2->z==0 ){
   90202     char *zColl;
   90203     assert( pName1->z );
   90204     zColl = sqlite3NameFromToken(pParse->db, pName1);
   90205     if( !zColl ) return;
   90206     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   90207     if( pColl ){
   90208       reindexDatabases(pParse, zColl);
   90209       sqlite3DbFree(db, zColl);
   90210       return;
   90211     }
   90212     sqlite3DbFree(db, zColl);
   90213   }
   90214   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
   90215   if( iDb<0 ) return;
   90216   z = sqlite3NameFromToken(db, pObjName);
   90217   if( z==0 ) return;
   90218   zDb = db->aDb[iDb].zName;
   90219   pTab = sqlite3FindTable(db, z, zDb);
   90220   if( pTab ){
   90221     reindexTable(pParse, pTab, 0);
   90222     sqlite3DbFree(db, z);
   90223     return;
   90224   }
   90225   pIndex = sqlite3FindIndex(db, z, zDb);
   90226   sqlite3DbFree(db, z);
   90227   if( pIndex ){
   90228     sqlite3BeginWriteOperation(pParse, 0, iDb);
   90229     sqlite3RefillIndex(pParse, pIndex, -1);
   90230     return;
   90231   }
   90232   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
   90233 }
   90234 #endif
   90235 
   90236 /*
   90237 ** Return a KeyInfo structure that is appropriate for the given Index.
   90238 **
   90239 ** The KeyInfo structure for an index is cached in the Index object.
   90240 ** So there might be multiple references to the returned pointer.  The
   90241 ** caller should not try to modify the KeyInfo object.
   90242 **
   90243 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
   90244 ** when it has finished using it.
   90245 */
   90246 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
   90247   if( pParse->nErr ) return 0;
   90248 #ifndef SQLITE_OMIT_SHARED_CACHE
   90249   if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
   90250     sqlite3KeyInfoUnref(pIdx->pKeyInfo);
   90251     pIdx->pKeyInfo = 0;
   90252   }
   90253 #endif
   90254   if( pIdx->pKeyInfo==0 ){
   90255     int i;
   90256     int nCol = pIdx->nColumn;
   90257     int nKey = pIdx->nKeyCol;
   90258     KeyInfo *pKey;
   90259     if( pIdx->uniqNotNull ){
   90260       pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
   90261     }else{
   90262       pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
   90263     }
   90264     if( pKey ){
   90265       assert( sqlite3KeyInfoIsWriteable(pKey) );
   90266       for(i=0; i<nCol; i++){
   90267         char *zColl = pIdx->azColl[i];
   90268         assert( zColl!=0 );
   90269         pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
   90270                           sqlite3LocateCollSeq(pParse, zColl);
   90271         pKey->aSortOrder[i] = pIdx->aSortOrder[i];
   90272       }
   90273       if( pParse->nErr ){
   90274         sqlite3KeyInfoUnref(pKey);
   90275       }else{
   90276         pIdx->pKeyInfo = pKey;
   90277       }
   90278     }
   90279   }
   90280   return sqlite3KeyInfoRef(pIdx->pKeyInfo);
   90281 }
   90282 
   90283 #ifndef SQLITE_OMIT_CTE
   90284 /*
   90285 ** This routine is invoked once per CTE by the parser while parsing a
   90286 ** WITH clause.
   90287 */
   90288 SQLITE_PRIVATE With *sqlite3WithAdd(
   90289   Parse *pParse,          /* Parsing context */
   90290   With *pWith,            /* Existing WITH clause, or NULL */
   90291   Token *pName,           /* Name of the common-table */
   90292   ExprList *pArglist,     /* Optional column name list for the table */
   90293   Select *pQuery          /* Query used to initialize the table */
   90294 ){
   90295   sqlite3 *db = pParse->db;
   90296   With *pNew;
   90297   char *zName;
   90298 
   90299   /* Check that the CTE name is unique within this WITH clause. If
   90300   ** not, store an error in the Parse structure. */
   90301   zName = sqlite3NameFromToken(pParse->db, pName);
   90302   if( zName && pWith ){
   90303     int i;
   90304     for(i=0; i<pWith->nCte; i++){
   90305       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
   90306         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
   90307       }
   90308     }
   90309   }
   90310 
   90311   if( pWith ){
   90312     int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
   90313     pNew = sqlite3DbRealloc(db, pWith, nByte);
   90314   }else{
   90315     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
   90316   }
   90317   assert( zName!=0 || pNew==0 );
   90318   assert( db->mallocFailed==0 || pNew==0 );
   90319 
   90320   if( pNew==0 ){
   90321     sqlite3ExprListDelete(db, pArglist);
   90322     sqlite3SelectDelete(db, pQuery);
   90323     sqlite3DbFree(db, zName);
   90324     pNew = pWith;
   90325   }else{
   90326     pNew->a[pNew->nCte].pSelect = pQuery;
   90327     pNew->a[pNew->nCte].pCols = pArglist;
   90328     pNew->a[pNew->nCte].zName = zName;
   90329     pNew->a[pNew->nCte].zErr = 0;
   90330     pNew->nCte++;
   90331   }
   90332 
   90333   return pNew;
   90334 }
   90335 
   90336 /*
   90337 ** Free the contents of the With object passed as the second argument.
   90338 */
   90339 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
   90340   if( pWith ){
   90341     int i;
   90342     for(i=0; i<pWith->nCte; i++){
   90343       struct Cte *pCte = &pWith->a[i];
   90344       sqlite3ExprListDelete(db, pCte->pCols);
   90345       sqlite3SelectDelete(db, pCte->pSelect);
   90346       sqlite3DbFree(db, pCte->zName);
   90347     }
   90348     sqlite3DbFree(db, pWith);
   90349   }
   90350 }
   90351 #endif /* !defined(SQLITE_OMIT_CTE) */
   90352 
   90353 /************** End of build.c ***********************************************/
   90354 /************** Begin file callback.c ****************************************/
   90355 /*
   90356 ** 2005 May 23
   90357 **
   90358 ** The author disclaims copyright to this source code.  In place of
   90359 ** a legal notice, here is a blessing:
   90360 **
   90361 **    May you do good and not evil.
   90362 **    May you find forgiveness for yourself and forgive others.
   90363 **    May you share freely, never taking more than you give.
   90364 **
   90365 *************************************************************************
   90366 **
   90367 ** This file contains functions used to access the internal hash tables
   90368 ** of user defined functions and collation sequences.
   90369 */
   90370 
   90371 
   90372 /*
   90373 ** Invoke the 'collation needed' callback to request a collation sequence
   90374 ** in the encoding enc of name zName, length nName.
   90375 */
   90376 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
   90377   assert( !db->xCollNeeded || !db->xCollNeeded16 );
   90378   if( db->xCollNeeded ){
   90379     char *zExternal = sqlite3DbStrDup(db, zName);
   90380     if( !zExternal ) return;
   90381     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
   90382     sqlite3DbFree(db, zExternal);
   90383   }
   90384 #ifndef SQLITE_OMIT_UTF16
   90385   if( db->xCollNeeded16 ){
   90386     char const *zExternal;
   90387     sqlite3_value *pTmp = sqlite3ValueNew(db);
   90388     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
   90389     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
   90390     if( zExternal ){
   90391       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
   90392     }
   90393     sqlite3ValueFree(pTmp);
   90394   }
   90395 #endif
   90396 }
   90397 
   90398 /*
   90399 ** This routine is called if the collation factory fails to deliver a
   90400 ** collation function in the best encoding but there may be other versions
   90401 ** of this collation function (for other text encodings) available. Use one
   90402 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
   90403 ** possible.
   90404 */
   90405 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
   90406   CollSeq *pColl2;
   90407   char *z = pColl->zName;
   90408   int i;
   90409   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
   90410   for(i=0; i<3; i++){
   90411     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
   90412     if( pColl2->xCmp!=0 ){
   90413       memcpy(pColl, pColl2, sizeof(CollSeq));
   90414       pColl->xDel = 0;         /* Do not copy the destructor */
   90415       return SQLITE_OK;
   90416     }
   90417   }
   90418   return SQLITE_ERROR;
   90419 }
   90420 
   90421 /*
   90422 ** This function is responsible for invoking the collation factory callback
   90423 ** or substituting a collation sequence of a different encoding when the
   90424 ** requested collation sequence is not available in the desired encoding.
   90425 **
   90426 ** If it is not NULL, then pColl must point to the database native encoding
   90427 ** collation sequence with name zName, length nName.
   90428 **
   90429 ** The return value is either the collation sequence to be used in database
   90430 ** db for collation type name zName, length nName, or NULL, if no collation
   90431 ** sequence can be found.  If no collation is found, leave an error message.
   90432 **
   90433 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
   90434 */
   90435 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
   90436   Parse *pParse,        /* Parsing context */
   90437   u8 enc,               /* The desired encoding for the collating sequence */
   90438   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
   90439   const char *zName     /* Collating sequence name */
   90440 ){
   90441   CollSeq *p;
   90442   sqlite3 *db = pParse->db;
   90443 
   90444   p = pColl;
   90445   if( !p ){
   90446     p = sqlite3FindCollSeq(db, enc, zName, 0);
   90447   }
   90448   if( !p || !p->xCmp ){
   90449     /* No collation sequence of this type for this encoding is registered.
   90450     ** Call the collation factory to see if it can supply us with one.
   90451     */
   90452     callCollNeeded(db, enc, zName);
   90453     p = sqlite3FindCollSeq(db, enc, zName, 0);
   90454   }
   90455   if( p && !p->xCmp && synthCollSeq(db, p) ){
   90456     p = 0;
   90457   }
   90458   assert( !p || p->xCmp );
   90459   if( p==0 ){
   90460     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   90461   }
   90462   return p;
   90463 }
   90464 
   90465 /*
   90466 ** This routine is called on a collation sequence before it is used to
   90467 ** check that it is defined. An undefined collation sequence exists when
   90468 ** a database is loaded that contains references to collation sequences
   90469 ** that have not been defined by sqlite3_create_collation() etc.
   90470 **
   90471 ** If required, this routine calls the 'collation needed' callback to
   90472 ** request a definition of the collating sequence. If this doesn't work,
   90473 ** an equivalent collating sequence that uses a text encoding different
   90474 ** from the main database is substituted, if one is available.
   90475 */
   90476 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
   90477   if( pColl ){
   90478     const char *zName = pColl->zName;
   90479     sqlite3 *db = pParse->db;
   90480     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
   90481     if( !p ){
   90482       return SQLITE_ERROR;
   90483     }
   90484     assert( p==pColl );
   90485   }
   90486   return SQLITE_OK;
   90487 }
   90488 
   90489 
   90490 
   90491 /*
   90492 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
   90493 ** specified by zName and nName is not found and parameter 'create' is
   90494 ** true, then create a new entry. Otherwise return NULL.
   90495 **
   90496 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
   90497 ** array of three CollSeq structures. The first is the collation sequence
   90498 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
   90499 **
   90500 ** Stored immediately after the three collation sequences is a copy of
   90501 ** the collation sequence name. A pointer to this string is stored in
   90502 ** each collation sequence structure.
   90503 */
   90504 static CollSeq *findCollSeqEntry(
   90505   sqlite3 *db,          /* Database connection */
   90506   const char *zName,    /* Name of the collating sequence */
   90507   int create            /* Create a new entry if true */
   90508 ){
   90509   CollSeq *pColl;
   90510   int nName = sqlite3Strlen30(zName);
   90511   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   90512 
   90513   if( 0==pColl && create ){
   90514     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
   90515     if( pColl ){
   90516       CollSeq *pDel = 0;
   90517       pColl[0].zName = (char*)&pColl[3];
   90518       pColl[0].enc = SQLITE_UTF8;
   90519       pColl[1].zName = (char*)&pColl[3];
   90520       pColl[1].enc = SQLITE_UTF16LE;
   90521       pColl[2].zName = (char*)&pColl[3];
   90522       pColl[2].enc = SQLITE_UTF16BE;
   90523       memcpy(pColl[0].zName, zName, nName);
   90524       pColl[0].zName[nName] = 0;
   90525       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
   90526 
   90527       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
   90528       ** return the pColl pointer to be deleted (because it wasn't added
   90529       ** to the hash table).
   90530       */
   90531       assert( pDel==0 || pDel==pColl );
   90532       if( pDel!=0 ){
   90533         db->mallocFailed = 1;
   90534         sqlite3DbFree(db, pDel);
   90535         pColl = 0;
   90536       }
   90537     }
   90538   }
   90539   return pColl;
   90540 }
   90541 
   90542 /*
   90543 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
   90544 ** Return the CollSeq* pointer for the collation sequence named zName
   90545 ** for the encoding 'enc' from the database 'db'.
   90546 **
   90547 ** If the entry specified is not found and 'create' is true, then create a
   90548 ** new entry.  Otherwise return NULL.
   90549 **
   90550 ** A separate function sqlite3LocateCollSeq() is a wrapper around
   90551 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
   90552 ** if necessary and generates an error message if the collating sequence
   90553 ** cannot be found.
   90554 **
   90555 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
   90556 */
   90557 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
   90558   sqlite3 *db,
   90559   u8 enc,
   90560   const char *zName,
   90561   int create
   90562 ){
   90563   CollSeq *pColl;
   90564   if( zName ){
   90565     pColl = findCollSeqEntry(db, zName, create);
   90566   }else{
   90567     pColl = db->pDfltColl;
   90568   }
   90569   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   90570   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
   90571   if( pColl ) pColl += enc-1;
   90572   return pColl;
   90573 }
   90574 
   90575 /* During the search for the best function definition, this procedure
   90576 ** is called to test how well the function passed as the first argument
   90577 ** matches the request for a function with nArg arguments in a system
   90578 ** that uses encoding enc. The value returned indicates how well the
   90579 ** request is matched. A higher value indicates a better match.
   90580 **
   90581 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
   90582 ** is also -1.  In other words, we are searching for a function that
   90583 ** takes a variable number of arguments.
   90584 **
   90585 ** If nArg is -2 that means that we are searching for any function
   90586 ** regardless of the number of arguments it uses, so return a positive
   90587 ** match score for any
   90588 **
   90589 ** The returned value is always between 0 and 6, as follows:
   90590 **
   90591 ** 0: Not a match.
   90592 ** 1: UTF8/16 conversion required and function takes any number of arguments.
   90593 ** 2: UTF16 byte order change required and function takes any number of args.
   90594 ** 3: encoding matches and function takes any number of arguments
   90595 ** 4: UTF8/16 conversion required - argument count matches exactly
   90596 ** 5: UTF16 byte order conversion required - argument count matches exactly
   90597 ** 6: Perfect match:  encoding and argument count match exactly.
   90598 **
   90599 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
   90600 ** a perfect match and any function with both xStep and xFunc NULL is
   90601 ** a non-match.
   90602 */
   90603 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
   90604 static int matchQuality(
   90605   FuncDef *p,     /* The function we are evaluating for match quality */
   90606   int nArg,       /* Desired number of arguments.  (-1)==any */
   90607   u8 enc          /* Desired text encoding */
   90608 ){
   90609   int match;
   90610 
   90611   /* nArg of -2 is a special case */
   90612   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
   90613 
   90614   /* Wrong number of arguments means "no match" */
   90615   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
   90616 
   90617   /* Give a better score to a function with a specific number of arguments
   90618   ** than to function that accepts any number of arguments. */
   90619   if( p->nArg==nArg ){
   90620     match = 4;
   90621   }else{
   90622     match = 1;
   90623   }
   90624 
   90625   /* Bonus points if the text encoding matches */
   90626   if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
   90627     match += 2;  /* Exact encoding match */
   90628   }else if( (enc & p->funcFlags & 2)!=0 ){
   90629     match += 1;  /* Both are UTF16, but with different byte orders */
   90630   }
   90631 
   90632   return match;
   90633 }
   90634 
   90635 /*
   90636 ** Search a FuncDefHash for a function with the given name.  Return
   90637 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
   90638 */
   90639 static FuncDef *functionSearch(
   90640   FuncDefHash *pHash,  /* Hash table to search */
   90641   int h,               /* Hash of the name */
   90642   const char *zFunc,   /* Name of function */
   90643   int nFunc            /* Number of bytes in zFunc */
   90644 ){
   90645   FuncDef *p;
   90646   for(p=pHash->a[h]; p; p=p->pHash){
   90647     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
   90648       return p;
   90649     }
   90650   }
   90651   return 0;
   90652 }
   90653 
   90654 /*
   90655 ** Insert a new FuncDef into a FuncDefHash hash table.
   90656 */
   90657 SQLITE_PRIVATE void sqlite3FuncDefInsert(
   90658   FuncDefHash *pHash,  /* The hash table into which to insert */
   90659   FuncDef *pDef        /* The function definition to insert */
   90660 ){
   90661   FuncDef *pOther;
   90662   int nName = sqlite3Strlen30(pDef->zName);
   90663   u8 c1 = (u8)pDef->zName[0];
   90664   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
   90665   pOther = functionSearch(pHash, h, pDef->zName, nName);
   90666   if( pOther ){
   90667     assert( pOther!=pDef && pOther->pNext!=pDef );
   90668     pDef->pNext = pOther->pNext;
   90669     pOther->pNext = pDef;
   90670   }else{
   90671     pDef->pNext = 0;
   90672     pDef->pHash = pHash->a[h];
   90673     pHash->a[h] = pDef;
   90674   }
   90675 }
   90676 
   90677 
   90678 
   90679 /*
   90680 ** Locate a user function given a name, a number of arguments and a flag
   90681 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
   90682 ** pointer to the FuncDef structure that defines that function, or return
   90683 ** NULL if the function does not exist.
   90684 **
   90685 ** If the createFlag argument is true, then a new (blank) FuncDef
   90686 ** structure is created and liked into the "db" structure if a
   90687 ** no matching function previously existed.
   90688 **
   90689 ** If nArg is -2, then the first valid function found is returned.  A
   90690 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
   90691 ** case is used to see if zName is a valid function name for some number
   90692 ** of arguments.  If nArg is -2, then createFlag must be 0.
   90693 **
   90694 ** If createFlag is false, then a function with the required name and
   90695 ** number of arguments may be returned even if the eTextRep flag does not
   90696 ** match that requested.
   90697 */
   90698 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   90699   sqlite3 *db,       /* An open database */
   90700   const char *zName, /* Name of the function.  Not null-terminated */
   90701   int nName,         /* Number of characters in the name */
   90702   int nArg,          /* Number of arguments.  -1 means any number */
   90703   u8 enc,            /* Preferred text encoding */
   90704   u8 createFlag      /* Create new entry if true and does not otherwise exist */
   90705 ){
   90706   FuncDef *p;         /* Iterator variable */
   90707   FuncDef *pBest = 0; /* Best match found so far */
   90708   int bestScore = 0;  /* Score of best match */
   90709   int h;              /* Hash value */
   90710 
   90711   assert( nArg>=(-2) );
   90712   assert( nArg>=(-1) || createFlag==0 );
   90713   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
   90714 
   90715   /* First search for a match amongst the application-defined functions.
   90716   */
   90717   p = functionSearch(&db->aFunc, h, zName, nName);
   90718   while( p ){
   90719     int score = matchQuality(p, nArg, enc);
   90720     if( score>bestScore ){
   90721       pBest = p;
   90722       bestScore = score;
   90723     }
   90724     p = p->pNext;
   90725   }
   90726 
   90727   /* If no match is found, search the built-in functions.
   90728   **
   90729   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
   90730   ** functions even if a prior app-defined function was found.  And give
   90731   ** priority to built-in functions.
   90732   **
   90733   ** Except, if createFlag is true, that means that we are trying to
   90734   ** install a new function.  Whatever FuncDef structure is returned it will
   90735   ** have fields overwritten with new information appropriate for the
   90736   ** new function.  But the FuncDefs for built-in functions are read-only.
   90737   ** So we must not search for built-ins when creating a new function.
   90738   */
   90739   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
   90740     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   90741     bestScore = 0;
   90742     p = functionSearch(pHash, h, zName, nName);
   90743     while( p ){
   90744       int score = matchQuality(p, nArg, enc);
   90745       if( score>bestScore ){
   90746         pBest = p;
   90747         bestScore = score;
   90748       }
   90749       p = p->pNext;
   90750     }
   90751   }
   90752 
   90753   /* If the createFlag parameter is true and the search did not reveal an
   90754   ** exact match for the name, number of arguments and encoding, then add a
   90755   ** new entry to the hash table and return it.
   90756   */
   90757   if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
   90758       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
   90759     pBest->zName = (char *)&pBest[1];
   90760     pBest->nArg = (u16)nArg;
   90761     pBest->funcFlags = enc;
   90762     memcpy(pBest->zName, zName, nName);
   90763     pBest->zName[nName] = 0;
   90764     sqlite3FuncDefInsert(&db->aFunc, pBest);
   90765   }
   90766 
   90767   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
   90768     return pBest;
   90769   }
   90770   return 0;
   90771 }
   90772 
   90773 /*
   90774 ** Free all resources held by the schema structure. The void* argument points
   90775 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
   90776 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
   90777 ** of the schema hash tables).
   90778 **
   90779 ** The Schema.cache_size variable is not cleared.
   90780 */
   90781 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
   90782   Hash temp1;
   90783   Hash temp2;
   90784   HashElem *pElem;
   90785   Schema *pSchema = (Schema *)p;
   90786 
   90787   temp1 = pSchema->tblHash;
   90788   temp2 = pSchema->trigHash;
   90789   sqlite3HashInit(&pSchema->trigHash);
   90790   sqlite3HashClear(&pSchema->idxHash);
   90791   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
   90792     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
   90793   }
   90794   sqlite3HashClear(&temp2);
   90795   sqlite3HashInit(&pSchema->tblHash);
   90796   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
   90797     Table *pTab = sqliteHashData(pElem);
   90798     sqlite3DeleteTable(0, pTab);
   90799   }
   90800   sqlite3HashClear(&temp1);
   90801   sqlite3HashClear(&pSchema->fkeyHash);
   90802   pSchema->pSeqTab = 0;
   90803   if( pSchema->schemaFlags & DB_SchemaLoaded ){
   90804     pSchema->iGeneration++;
   90805     pSchema->schemaFlags &= ~DB_SchemaLoaded;
   90806   }
   90807 }
   90808 
   90809 /*
   90810 ** Find and return the schema associated with a BTree.  Create
   90811 ** a new one if necessary.
   90812 */
   90813 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
   90814   Schema * p;
   90815   if( pBt ){
   90816     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
   90817   }else{
   90818     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
   90819   }
   90820   if( !p ){
   90821     db->mallocFailed = 1;
   90822   }else if ( 0==p->file_format ){
   90823     sqlite3HashInit(&p->tblHash);
   90824     sqlite3HashInit(&p->idxHash);
   90825     sqlite3HashInit(&p->trigHash);
   90826     sqlite3HashInit(&p->fkeyHash);
   90827     p->enc = SQLITE_UTF8;
   90828   }
   90829   return p;
   90830 }
   90831 
   90832 /************** End of callback.c ********************************************/
   90833 /************** Begin file delete.c ******************************************/
   90834 /*
   90835 ** 2001 September 15
   90836 **
   90837 ** The author disclaims copyright to this source code.  In place of
   90838 ** a legal notice, here is a blessing:
   90839 **
   90840 **    May you do good and not evil.
   90841 **    May you find forgiveness for yourself and forgive others.
   90842 **    May you share freely, never taking more than you give.
   90843 **
   90844 *************************************************************************
   90845 ** This file contains C code routines that are called by the parser
   90846 ** in order to generate code for DELETE FROM statements.
   90847 */
   90848 
   90849 /*
   90850 ** While a SrcList can in general represent multiple tables and subqueries
   90851 ** (as in the FROM clause of a SELECT statement) in this case it contains
   90852 ** the name of a single table, as one might find in an INSERT, DELETE,
   90853 ** or UPDATE statement.  Look up that table in the symbol table and
   90854 ** return a pointer.  Set an error message and return NULL if the table
   90855 ** name is not found or if any other error occurs.
   90856 **
   90857 ** The following fields are initialized appropriate in pSrc:
   90858 **
   90859 **    pSrc->a[0].pTab       Pointer to the Table object
   90860 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
   90861 **
   90862 */
   90863 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   90864   struct SrcList_item *pItem = pSrc->a;
   90865   Table *pTab;
   90866   assert( pItem && pSrc->nSrc==1 );
   90867   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
   90868   sqlite3DeleteTable(pParse->db, pItem->pTab);
   90869   pItem->pTab = pTab;
   90870   if( pTab ){
   90871     pTab->nRef++;
   90872   }
   90873   if( sqlite3IndexedByLookup(pParse, pItem) ){
   90874     pTab = 0;
   90875   }
   90876   return pTab;
   90877 }
   90878 
   90879 /*
   90880 ** Check to make sure the given table is writable.  If it is not
   90881 ** writable, generate an error message and return 1.  If it is
   90882 ** writable return 0;
   90883 */
   90884 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
   90885   /* A table is not writable under the following circumstances:
   90886   **
   90887   **   1) It is a virtual table and no implementation of the xUpdate method
   90888   **      has been provided, or
   90889   **   2) It is a system table (i.e. sqlite_master), this call is not
   90890   **      part of a nested parse and writable_schema pragma has not
   90891   **      been specified.
   90892   **
   90893   ** In either case leave an error message in pParse and return non-zero.
   90894   */
   90895   if( ( IsVirtual(pTab)
   90896      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
   90897    || ( (pTab->tabFlags & TF_Readonly)!=0
   90898      && (pParse->db->flags & SQLITE_WriteSchema)==0
   90899      && pParse->nested==0 )
   90900   ){
   90901     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
   90902     return 1;
   90903   }
   90904 
   90905 #ifndef SQLITE_OMIT_VIEW
   90906   if( !viewOk && pTab->pSelect ){
   90907     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
   90908     return 1;
   90909   }
   90910 #endif
   90911   return 0;
   90912 }
   90913 
   90914 
   90915 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   90916 /*
   90917 ** Evaluate a view and store its result in an ephemeral table.  The
   90918 ** pWhere argument is an optional WHERE clause that restricts the
   90919 ** set of rows in the view that are to be added to the ephemeral table.
   90920 */
   90921 SQLITE_PRIVATE void sqlite3MaterializeView(
   90922   Parse *pParse,       /* Parsing context */
   90923   Table *pView,        /* View definition */
   90924   Expr *pWhere,        /* Optional WHERE clause to be added */
   90925   int iCur             /* Cursor number for ephemerial table */
   90926 ){
   90927   SelectDest dest;
   90928   Select *pSel;
   90929   SrcList *pFrom;
   90930   sqlite3 *db = pParse->db;
   90931   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
   90932   pWhere = sqlite3ExprDup(db, pWhere, 0);
   90933   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
   90934   if( pFrom ){
   90935     assert( pFrom->nSrc==1 );
   90936     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
   90937     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   90938     assert( pFrom->a[0].pOn==0 );
   90939     assert( pFrom->a[0].pUsing==0 );
   90940   }
   90941   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
   90942   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   90943   sqlite3Select(pParse, pSel, &dest);
   90944   sqlite3SelectDelete(db, pSel);
   90945 }
   90946 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
   90947 
   90948 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   90949 /*
   90950 ** Generate an expression tree to implement the WHERE, ORDER BY,
   90951 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
   90952 **
   90953 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
   90954 **                            \__________________________/
   90955 **                               pLimitWhere (pInClause)
   90956 */
   90957 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   90958   Parse *pParse,               /* The parser context */
   90959   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
   90960   Expr *pWhere,                /* The WHERE clause.  May be null */
   90961   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
   90962   Expr *pLimit,                /* The LIMIT clause.  May be null */
   90963   Expr *pOffset,               /* The OFFSET clause.  May be null */
   90964   char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
   90965 ){
   90966   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
   90967   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
   90968   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
   90969   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
   90970   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
   90971   Select *pSelect = NULL;      /* Complete SELECT tree */
   90972 
   90973   /* Check that there isn't an ORDER BY without a LIMIT clause.
   90974   */
   90975   if( pOrderBy && (pLimit == 0) ) {
   90976     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
   90977     goto limit_where_cleanup_2;
   90978   }
   90979 
   90980   /* We only need to generate a select expression if there
   90981   ** is a limit/offset term to enforce.
   90982   */
   90983   if( pLimit == 0 ) {
   90984     /* if pLimit is null, pOffset will always be null as well. */
   90985     assert( pOffset == 0 );
   90986     return pWhere;
   90987   }
   90988 
   90989   /* Generate a select expression tree to enforce the limit/offset
   90990   ** term for the DELETE or UPDATE statement.  For example:
   90991   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   90992   ** becomes:
   90993   **   DELETE FROM table_a WHERE rowid IN (
   90994   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   90995   **   );
   90996   */
   90997 
   90998   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   90999   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
   91000   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
   91001   if( pEList == 0 ) goto limit_where_cleanup_2;
   91002 
   91003   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
   91004   ** and the SELECT subtree. */
   91005   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
   91006   if( pSelectSrc == 0 ) {
   91007     sqlite3ExprListDelete(pParse->db, pEList);
   91008     goto limit_where_cleanup_2;
   91009   }
   91010 
   91011   /* generate the SELECT expression tree. */
   91012   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
   91013                              pOrderBy,0,pLimit,pOffset);
   91014   if( pSelect == 0 ) return 0;
   91015 
   91016   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
   91017   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   91018   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
   91019   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
   91020   if( pInClause == 0 ) goto limit_where_cleanup_1;
   91021 
   91022   pInClause->x.pSelect = pSelect;
   91023   pInClause->flags |= EP_xIsSelect;
   91024   sqlite3ExprSetHeight(pParse, pInClause);
   91025   return pInClause;
   91026 
   91027   /* something went wrong. clean up anything allocated. */
   91028 limit_where_cleanup_1:
   91029   sqlite3SelectDelete(pParse->db, pSelect);
   91030   return 0;
   91031 
   91032 limit_where_cleanup_2:
   91033   sqlite3ExprDelete(pParse->db, pWhere);
   91034   sqlite3ExprListDelete(pParse->db, pOrderBy);
   91035   sqlite3ExprDelete(pParse->db, pLimit);
   91036   sqlite3ExprDelete(pParse->db, pOffset);
   91037   return 0;
   91038 }
   91039 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
   91040        /*      && !defined(SQLITE_OMIT_SUBQUERY) */
   91041 
   91042 /*
   91043 ** Generate code for a DELETE FROM statement.
   91044 **
   91045 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
   91046 **                 \________/       \________________/
   91047 **                  pTabList              pWhere
   91048 */
   91049 SQLITE_PRIVATE void sqlite3DeleteFrom(
   91050   Parse *pParse,         /* The parser context */
   91051   SrcList *pTabList,     /* The table from which we should delete things */
   91052   Expr *pWhere           /* The WHERE clause.  May be null */
   91053 ){
   91054   Vdbe *v;               /* The virtual database engine */
   91055   Table *pTab;           /* The table from which records will be deleted */
   91056   const char *zDb;       /* Name of database holding pTab */
   91057   int i;                 /* Loop counter */
   91058   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   91059   Index *pIdx;           /* For looping over indices of the table */
   91060   int iTabCur;           /* Cursor number for the table */
   91061   int iDataCur;          /* VDBE cursor for the canonical data source */
   91062   int iIdxCur;           /* Cursor number of the first index */
   91063   int nIdx;              /* Number of indices */
   91064   sqlite3 *db;           /* Main database structure */
   91065   AuthContext sContext;  /* Authorization context */
   91066   NameContext sNC;       /* Name context to resolve expressions in */
   91067   int iDb;               /* Database number */
   91068   int memCnt = -1;       /* Memory cell used for change counting */
   91069   int rcauth;            /* Value returned by authorization callback */
   91070   int okOnePass;         /* True for one-pass algorithm without the FIFO */
   91071   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
   91072   u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
   91073   Index *pPk;            /* The PRIMARY KEY index on the table */
   91074   int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
   91075   i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
   91076   int iKey;              /* Memory cell holding key of row to be deleted */
   91077   i16 nKey;              /* Number of memory cells in the row key */
   91078   int iEphCur = 0;       /* Ephemeral table holding all primary key values */
   91079   int iRowSet = 0;       /* Register for rowset of rows to delete */
   91080   int addrBypass = 0;    /* Address of jump over the delete logic */
   91081   int addrLoop = 0;      /* Top of the delete loop */
   91082   int addrDelete = 0;    /* Jump directly to the delete logic */
   91083   int addrEphOpen = 0;   /* Instruction to open the Ephermeral table */
   91084 
   91085 #ifndef SQLITE_OMIT_TRIGGER
   91086   int isView;                  /* True if attempting to delete from a view */
   91087   Trigger *pTrigger;           /* List of table triggers, if required */
   91088 #endif
   91089 
   91090   memset(&sContext, 0, sizeof(sContext));
   91091   db = pParse->db;
   91092   if( pParse->nErr || db->mallocFailed ){
   91093     goto delete_from_cleanup;
   91094   }
   91095   assert( pTabList->nSrc==1 );
   91096 
   91097   /* Locate the table which we want to delete.  This table has to be
   91098   ** put in an SrcList structure because some of the subroutines we
   91099   ** will be calling are designed to work with multiple tables and expect
   91100   ** an SrcList* parameter instead of just a Table* parameter.
   91101   */
   91102   pTab = sqlite3SrcListLookup(pParse, pTabList);
   91103   if( pTab==0 )  goto delete_from_cleanup;
   91104 
   91105   /* Figure out if we have any triggers and if the table being
   91106   ** deleted from is a view
   91107   */
   91108 #ifndef SQLITE_OMIT_TRIGGER
   91109   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   91110   isView = pTab->pSelect!=0;
   91111 #else
   91112 # define pTrigger 0
   91113 # define isView 0
   91114 #endif
   91115 #ifdef SQLITE_OMIT_VIEW
   91116 # undef isView
   91117 # define isView 0
   91118 #endif
   91119 
   91120   /* If pTab is really a view, make sure it has been initialized.
   91121   */
   91122   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   91123     goto delete_from_cleanup;
   91124   }
   91125 
   91126   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   91127     goto delete_from_cleanup;
   91128   }
   91129   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   91130   assert( iDb<db->nDb );
   91131   zDb = db->aDb[iDb].zName;
   91132   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
   91133   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   91134   if( rcauth==SQLITE_DENY ){
   91135     goto delete_from_cleanup;
   91136   }
   91137   assert(!isView || pTrigger);
   91138 
   91139   /* Assign cursor numbers to the table and all its indices.
   91140   */
   91141   assert( pTabList->nSrc==1 );
   91142   iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
   91143   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
   91144     pParse->nTab++;
   91145   }
   91146 
   91147   /* Start the view context
   91148   */
   91149   if( isView ){
   91150     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   91151   }
   91152 
   91153   /* Begin generating code.
   91154   */
   91155   v = sqlite3GetVdbe(pParse);
   91156   if( v==0 ){
   91157     goto delete_from_cleanup;
   91158   }
   91159   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   91160   sqlite3BeginWriteOperation(pParse, 1, iDb);
   91161 
   91162   /* If we are trying to delete from a view, realize that view into
   91163   ** a ephemeral table.
   91164   */
   91165 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   91166   if( isView ){
   91167     sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
   91168     iDataCur = iIdxCur = iTabCur;
   91169   }
   91170 #endif
   91171 
   91172   /* Resolve the column names in the WHERE clause.
   91173   */
   91174   memset(&sNC, 0, sizeof(sNC));
   91175   sNC.pParse = pParse;
   91176   sNC.pSrcList = pTabList;
   91177   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   91178     goto delete_from_cleanup;
   91179   }
   91180 
   91181   /* Initialize the counter of the number of rows deleted, if
   91182   ** we are counting rows.
   91183   */
   91184   if( db->flags & SQLITE_CountRows ){
   91185     memCnt = ++pParse->nMem;
   91186     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
   91187   }
   91188 
   91189 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   91190   /* Special case: A DELETE without a WHERE clause deletes everything.
   91191   ** It is easier just to erase the whole table. Prior to version 3.6.5,
   91192   ** this optimization caused the row change count (the value returned by
   91193   ** API function sqlite3_count_changes) to be set incorrectly.  */
   91194   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
   91195    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
   91196   ){
   91197     assert( !isView );
   91198     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   91199     if( HasRowid(pTab) ){
   91200       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
   91201                         pTab->zName, P4_STATIC);
   91202     }
   91203     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   91204       assert( pIdx->pSchema==pTab->pSchema );
   91205       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
   91206     }
   91207   }else
   91208 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   91209   {
   91210     if( HasRowid(pTab) ){
   91211       /* For a rowid table, initialize the RowSet to an empty set */
   91212       pPk = 0;
   91213       nPk = 1;
   91214       iRowSet = ++pParse->nMem;
   91215       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
   91216     }else{
   91217       /* For a WITHOUT ROWID table, create an ephermeral table used to
   91218       ** hold all primary keys for rows to be deleted. */
   91219       pPk = sqlite3PrimaryKeyIndex(pTab);
   91220       assert( pPk!=0 );
   91221       nPk = pPk->nKeyCol;
   91222       iPk = pParse->nMem+1;
   91223       pParse->nMem += nPk;
   91224       iEphCur = pParse->nTab++;
   91225       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
   91226       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   91227     }
   91228 
   91229     /* Construct a query to find the rowid or primary key for every row
   91230     ** to be deleted, based on the WHERE clause.
   91231     */
   91232     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
   91233                                WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
   91234                                iTabCur+1);
   91235     if( pWInfo==0 ) goto delete_from_cleanup;
   91236     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
   91237 
   91238     /* Keep track of the number of rows to be deleted */
   91239     if( db->flags & SQLITE_CountRows ){
   91240       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
   91241     }
   91242 
   91243     /* Extract the rowid or primary key for the current row */
   91244     if( pPk ){
   91245       for(i=0; i<nPk; i++){
   91246         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
   91247                                         pPk->aiColumn[i], iPk+i);
   91248       }
   91249       iKey = iPk;
   91250     }else{
   91251       iKey = pParse->nMem + 1;
   91252       iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
   91253       if( iKey>pParse->nMem ) pParse->nMem = iKey;
   91254     }
   91255 
   91256     if( okOnePass ){
   91257       /* For ONEPASS, no need to store the rowid/primary-key.  There is only
   91258       ** one, so just keep it in its register(s) and fall through to the
   91259       ** delete code.
   91260       */
   91261       nKey = nPk; /* OP_Found will use an unpacked key */
   91262       aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
   91263       if( aToOpen==0 ){
   91264         sqlite3WhereEnd(pWInfo);
   91265         goto delete_from_cleanup;
   91266       }
   91267       memset(aToOpen, 1, nIdx+1);
   91268       aToOpen[nIdx+1] = 0;
   91269       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
   91270       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
   91271       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
   91272       addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
   91273     }else if( pPk ){
   91274       /* Construct a composite key for the row to be deleted and remember it */
   91275       iKey = ++pParse->nMem;
   91276       nKey = 0;   /* Zero tells OP_Found to use a composite key */
   91277       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
   91278                         sqlite3IndexAffinityStr(v, pPk), nPk);
   91279       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
   91280     }else{
   91281       /* Get the rowid of the row to be deleted and remember it in the RowSet */
   91282       nKey = 1;  /* OP_Seek always uses a single rowid */
   91283       sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
   91284     }
   91285 
   91286     /* End of the WHERE loop */
   91287     sqlite3WhereEnd(pWInfo);
   91288     if( okOnePass ){
   91289       /* Bypass the delete logic below if the WHERE loop found zero rows */
   91290       addrBypass = sqlite3VdbeMakeLabel(v);
   91291       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
   91292       sqlite3VdbeJumpHere(v, addrDelete);
   91293     }
   91294 
   91295     /* Unless this is a view, open cursors for the table we are
   91296     ** deleting from and all its indices. If this is a view, then the
   91297     ** only effect this statement has is to fire the INSTEAD OF
   91298     ** triggers.
   91299     */
   91300     if( !isView ){
   91301       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
   91302                                  &iDataCur, &iIdxCur);
   91303       assert( pPk || iDataCur==iTabCur );
   91304       assert( pPk || iIdxCur==iDataCur+1 );
   91305     }
   91306 
   91307     /* Set up a loop over the rowids/primary-keys that were found in the
   91308     ** where-clause loop above.
   91309     */
   91310     if( okOnePass ){
   91311       /* Just one row.  Hence the top-of-loop is a no-op */
   91312       assert( nKey==nPk ); /* OP_Found will use an unpacked key */
   91313       if( aToOpen[iDataCur-iTabCur] ){
   91314         assert( pPk!=0 );
   91315         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
   91316         VdbeCoverage(v);
   91317       }
   91318     }else if( pPk ){
   91319       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
   91320       sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
   91321       assert( nKey==0 );  /* OP_Found will use a composite key */
   91322     }else{
   91323       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
   91324       VdbeCoverage(v);
   91325       assert( nKey==1 );
   91326     }
   91327 
   91328     /* Delete the row */
   91329 #ifndef SQLITE_OMIT_VIRTUALTABLE
   91330     if( IsVirtual(pTab) ){
   91331       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   91332       sqlite3VtabMakeWritable(pParse, pTab);
   91333       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
   91334       sqlite3VdbeChangeP5(v, OE_Abort);
   91335       sqlite3MayAbort(pParse);
   91336     }else
   91337 #endif
   91338     {
   91339       int count = (pParse->nested==0);    /* True to count changes */
   91340       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   91341                                iKey, nKey, count, OE_Default, okOnePass);
   91342     }
   91343 
   91344     /* End of the loop over all rowids/primary-keys. */
   91345     if( okOnePass ){
   91346       sqlite3VdbeResolveLabel(v, addrBypass);
   91347     }else if( pPk ){
   91348       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
   91349       sqlite3VdbeJumpHere(v, addrLoop);
   91350     }else{
   91351       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
   91352       sqlite3VdbeJumpHere(v, addrLoop);
   91353     }
   91354 
   91355     /* Close the cursors open on the table and its indexes. */
   91356     if( !isView && !IsVirtual(pTab) ){
   91357       if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
   91358       for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   91359         sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
   91360       }
   91361     }
   91362   } /* End non-truncate path */
   91363 
   91364   /* Update the sqlite_sequence table by storing the content of the
   91365   ** maximum rowid counter values recorded while inserting into
   91366   ** autoincrement tables.
   91367   */
   91368   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   91369     sqlite3AutoincrementEnd(pParse);
   91370   }
   91371 
   91372   /* Return the number of rows that were deleted. If this routine is
   91373   ** generating code because of a call to sqlite3NestedParse(), do not
   91374   ** invoke the callback function.
   91375   */
   91376   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   91377     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
   91378     sqlite3VdbeSetNumCols(v, 1);
   91379     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   91380   }
   91381 
   91382 delete_from_cleanup:
   91383   sqlite3AuthContextPop(&sContext);
   91384   sqlite3SrcListDelete(db, pTabList);
   91385   sqlite3ExprDelete(db, pWhere);
   91386   sqlite3DbFree(db, aToOpen);
   91387   return;
   91388 }
   91389 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   91390 ** thely may interfere with compilation of other functions in this file
   91391 ** (or in another file, if this file becomes part of the amalgamation).  */
   91392 #ifdef isView
   91393  #undef isView
   91394 #endif
   91395 #ifdef pTrigger
   91396  #undef pTrigger
   91397 #endif
   91398 
   91399 /*
   91400 ** This routine generates VDBE code that causes a single row of a
   91401 ** single table to be deleted.  Both the original table entry and
   91402 ** all indices are removed.
   91403 **
   91404 ** Preconditions:
   91405 **
   91406 **   1.  iDataCur is an open cursor on the btree that is the canonical data
   91407 **       store for the table.  (This will be either the table itself,
   91408 **       in the case of a rowid table, or the PRIMARY KEY index in the case
   91409 **       of a WITHOUT ROWID table.)
   91410 **
   91411 **   2.  Read/write cursors for all indices of pTab must be open as
   91412 **       cursor number iIdxCur+i for the i-th index.
   91413 **
   91414 **   3.  The primary key for the row to be deleted must be stored in a
   91415 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
   91416 **       that a search record formed from OP_MakeRecord is contained in the
   91417 **       single memory location iPk.
   91418 */
   91419 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   91420   Parse *pParse,     /* Parsing context */
   91421   Table *pTab,       /* Table containing the row to be deleted */
   91422   Trigger *pTrigger, /* List of triggers to (potentially) fire */
   91423   int iDataCur,      /* Cursor from which column data is extracted */
   91424   int iIdxCur,       /* First index cursor */
   91425   int iPk,           /* First memory cell containing the PRIMARY KEY */
   91426   i16 nPk,           /* Number of PRIMARY KEY memory cells */
   91427   u8 count,          /* If non-zero, increment the row change counter */
   91428   u8 onconf,         /* Default ON CONFLICT policy for triggers */
   91429   u8 bNoSeek         /* iDataCur is already pointing to the row to delete */
   91430 ){
   91431   Vdbe *v = pParse->pVdbe;        /* Vdbe */
   91432   int iOld = 0;                   /* First register in OLD.* array */
   91433   int iLabel;                     /* Label resolved to end of generated code */
   91434   u8 opSeek;                      /* Seek opcode */
   91435 
   91436   /* Vdbe is guaranteed to have been allocated by this stage. */
   91437   assert( v );
   91438   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
   91439                          iDataCur, iIdxCur, iPk, (int)nPk));
   91440 
   91441   /* Seek cursor iCur to the row to delete. If this row no longer exists
   91442   ** (this can happen if a trigger program has already deleted it), do
   91443   ** not attempt to delete it or fire any DELETE triggers.  */
   91444   iLabel = sqlite3VdbeMakeLabel(v);
   91445   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
   91446   if( !bNoSeek ){
   91447     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
   91448     VdbeCoverageIf(v, opSeek==OP_NotExists);
   91449     VdbeCoverageIf(v, opSeek==OP_NotFound);
   91450   }
   91451 
   91452   /* If there are any triggers to fire, allocate a range of registers to
   91453   ** use for the old.* references in the triggers.  */
   91454   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
   91455     u32 mask;                     /* Mask of OLD.* columns in use */
   91456     int iCol;                     /* Iterator used while populating OLD.* */
   91457     int addrStart;                /* Start of BEFORE trigger programs */
   91458 
   91459     /* TODO: Could use temporary registers here. Also could attempt to
   91460     ** avoid copying the contents of the rowid register.  */
   91461     mask = sqlite3TriggerColmask(
   91462         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
   91463     );
   91464     mask |= sqlite3FkOldmask(pParse, pTab);
   91465     iOld = pParse->nMem+1;
   91466     pParse->nMem += (1 + pTab->nCol);
   91467 
   91468     /* Populate the OLD.* pseudo-table register array. These values will be
   91469     ** used by any BEFORE and AFTER triggers that exist.  */
   91470     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
   91471     for(iCol=0; iCol<pTab->nCol; iCol++){
   91472       testcase( mask!=0xffffffff && iCol==31 );
   91473       testcase( mask!=0xffffffff && iCol==32 );
   91474       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
   91475         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
   91476       }
   91477     }
   91478 
   91479     /* Invoke BEFORE DELETE trigger programs. */
   91480     addrStart = sqlite3VdbeCurrentAddr(v);
   91481     sqlite3CodeRowTrigger(pParse, pTrigger,
   91482         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
   91483     );
   91484 
   91485     /* If any BEFORE triggers were coded, then seek the cursor to the
   91486     ** row to be deleted again. It may be that the BEFORE triggers moved
   91487     ** the cursor or of already deleted the row that the cursor was
   91488     ** pointing to.
   91489     */
   91490     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
   91491       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
   91492       VdbeCoverageIf(v, opSeek==OP_NotExists);
   91493       VdbeCoverageIf(v, opSeek==OP_NotFound);
   91494     }
   91495 
   91496     /* Do FK processing. This call checks that any FK constraints that
   91497     ** refer to this table (i.e. constraints attached to other tables)
   91498     ** are not violated by deleting this row.  */
   91499     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
   91500   }
   91501 
   91502   /* Delete the index and table entries. Skip this step if pTab is really
   91503   ** a view (in which case the only effect of the DELETE statement is to
   91504   ** fire the INSTEAD OF triggers).  */
   91505   if( pTab->pSelect==0 ){
   91506     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
   91507     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
   91508     if( count ){
   91509       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
   91510     }
   91511   }
   91512 
   91513   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   91514   ** handle rows (possibly in other tables) that refer via a foreign key
   91515   ** to the row just deleted. */
   91516   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
   91517 
   91518   /* Invoke AFTER DELETE trigger programs. */
   91519   sqlite3CodeRowTrigger(pParse, pTrigger,
   91520       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
   91521   );
   91522 
   91523   /* Jump here if the row had already been deleted before any BEFORE
   91524   ** trigger programs were invoked. Or if a trigger program throws a
   91525   ** RAISE(IGNORE) exception.  */
   91526   sqlite3VdbeResolveLabel(v, iLabel);
   91527   VdbeModuleComment((v, "END: GenRowDel()"));
   91528 }
   91529 
   91530 /*
   91531 ** This routine generates VDBE code that causes the deletion of all
   91532 ** index entries associated with a single row of a single table, pTab
   91533 **
   91534 ** Preconditions:
   91535 **
   91536 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
   91537 **       btree for the table pTab.  (This will be either the table itself
   91538 **       for rowid tables or to the primary key index for WITHOUT ROWID
   91539 **       tables.)
   91540 **
   91541 **   2.  Read/write cursors for all indices of pTab must be open as
   91542 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
   91543 **       index is the 0-th index.)
   91544 **
   91545 **   3.  The "iDataCur" cursor must be already be positioned on the row
   91546 **       that is to be deleted.
   91547 */
   91548 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
   91549   Parse *pParse,     /* Parsing and code generating context */
   91550   Table *pTab,       /* Table containing the row to be deleted */
   91551   int iDataCur,      /* Cursor of table holding data. */
   91552   int iIdxCur,       /* First index cursor */
   91553   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
   91554 ){
   91555   int i;             /* Index loop counter */
   91556   int r1 = -1;       /* Register holding an index key */
   91557   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
   91558   Index *pIdx;       /* Current index */
   91559   Index *pPrior = 0; /* Prior index */
   91560   Vdbe *v;           /* The prepared statement under construction */
   91561   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
   91562 
   91563   v = pParse->pVdbe;
   91564   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   91565   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   91566     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
   91567     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
   91568     if( pIdx==pPk ) continue;
   91569     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
   91570     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
   91571                                  &iPartIdxLabel, pPrior, r1);
   91572     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
   91573                       pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
   91574     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
   91575     pPrior = pIdx;
   91576   }
   91577 }
   91578 
   91579 /*
   91580 ** Generate code that will assemble an index key and stores it in register
   91581 ** regOut.  The key with be for index pIdx which is an index on pTab.
   91582 ** iCur is the index of a cursor open on the pTab table and pointing to
   91583 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
   91584 ** iCur must be the cursor of the PRIMARY KEY index.
   91585 **
   91586 ** Return a register number which is the first in a block of
   91587 ** registers that holds the elements of the index key.  The
   91588 ** block of registers has already been deallocated by the time
   91589 ** this routine returns.
   91590 **
   91591 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
   91592 ** to that label if pIdx is a partial index that should be skipped.
   91593 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
   91594 ** A partial index should be skipped if its WHERE clause evaluates
   91595 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
   91596 ** will be set to zero which is an empty label that is ignored by
   91597 ** sqlite3ResolvePartIdxLabel().
   91598 **
   91599 ** The pPrior and regPrior parameters are used to implement a cache to
   91600 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
   91601 ** a pointer to a different index for which an index key has just been
   91602 ** computed into register regPrior.  If the current pIdx index is generating
   91603 ** its key into the same sequence of registers and if pPrior and pIdx share
   91604 ** a column in common, then the register corresponding to that column already
   91605 ** holds the correct value and the loading of that register is skipped.
   91606 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
   91607 ** on a table with multiple indices, and especially with the ROWID or
   91608 ** PRIMARY KEY columns of the index.
   91609 */
   91610 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
   91611   Parse *pParse,       /* Parsing context */
   91612   Index *pIdx,         /* The index for which to generate a key */
   91613   int iDataCur,        /* Cursor number from which to take column data */
   91614   int regOut,          /* Put the new key into this register if not 0 */
   91615   int prefixOnly,      /* Compute only a unique prefix of the key */
   91616   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
   91617   Index *pPrior,       /* Previously generated index key */
   91618   int regPrior         /* Register holding previous generated key */
   91619 ){
   91620   Vdbe *v = pParse->pVdbe;
   91621   int j;
   91622   Table *pTab = pIdx->pTable;
   91623   int regBase;
   91624   int nCol;
   91625 
   91626   if( piPartIdxLabel ){
   91627     if( pIdx->pPartIdxWhere ){
   91628       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
   91629       pParse->iPartIdxTab = iDataCur;
   91630       sqlite3ExprCachePush(pParse);
   91631       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
   91632                          SQLITE_JUMPIFNULL);
   91633     }else{
   91634       *piPartIdxLabel = 0;
   91635     }
   91636   }
   91637   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
   91638   regBase = sqlite3GetTempRange(pParse, nCol);
   91639   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
   91640   for(j=0; j<nCol; j++){
   91641     if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
   91642     sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
   91643                                     regBase+j);
   91644     /* If the column affinity is REAL but the number is an integer, then it
   91645     ** might be stored in the table as an integer (using a compact
   91646     ** representation) then converted to REAL by an OP_RealAffinity opcode.
   91647     ** But we are getting ready to store this value back into an index, where
   91648     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
   91649     ** opcode if it is present */
   91650     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
   91651   }
   91652   if( regOut ){
   91653     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
   91654   }
   91655   sqlite3ReleaseTempRange(pParse, regBase, nCol);
   91656   return regBase;
   91657 }
   91658 
   91659 /*
   91660 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
   91661 ** because it was a partial index, then this routine should be called to
   91662 ** resolve that label.
   91663 */
   91664 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
   91665   if( iLabel ){
   91666     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
   91667     sqlite3ExprCachePop(pParse);
   91668   }
   91669 }
   91670 
   91671 /************** End of delete.c **********************************************/
   91672 /************** Begin file func.c ********************************************/
   91673 /*
   91674 ** 2002 February 23
   91675 **
   91676 ** The author disclaims copyright to this source code.  In place of
   91677 ** a legal notice, here is a blessing:
   91678 **
   91679 **    May you do good and not evil.
   91680 **    May you find forgiveness for yourself and forgive others.
   91681 **    May you share freely, never taking more than you give.
   91682 **
   91683 *************************************************************************
   91684 ** This file contains the C-language implementions for many of the SQL
   91685 ** functions of SQLite.  (Some function, and in particular the date and
   91686 ** time functions, are implemented separately.)
   91687 */
   91688 /* #include <stdlib.h> */
   91689 /* #include <assert.h> */
   91690 
   91691 /*
   91692 ** Return the collating function associated with a function.
   91693 */
   91694 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
   91695   return context->pColl;
   91696 }
   91697 
   91698 /*
   91699 ** Indicate that the accumulator load should be skipped on this
   91700 ** iteration of the aggregate loop.
   91701 */
   91702 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
   91703   context->skipFlag = 1;
   91704 }
   91705 
   91706 /*
   91707 ** Implementation of the non-aggregate min() and max() functions
   91708 */
   91709 static void minmaxFunc(
   91710   sqlite3_context *context,
   91711   int argc,
   91712   sqlite3_value **argv
   91713 ){
   91714   int i;
   91715   int mask;    /* 0 for min() or 0xffffffff for max() */
   91716   int iBest;
   91717   CollSeq *pColl;
   91718 
   91719   assert( argc>1 );
   91720   mask = sqlite3_user_data(context)==0 ? 0 : -1;
   91721   pColl = sqlite3GetFuncCollSeq(context);
   91722   assert( pColl );
   91723   assert( mask==-1 || mask==0 );
   91724   iBest = 0;
   91725   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   91726   for(i=1; i<argc; i++){
   91727     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
   91728     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
   91729       testcase( mask==0 );
   91730       iBest = i;
   91731     }
   91732   }
   91733   sqlite3_result_value(context, argv[iBest]);
   91734 }
   91735 
   91736 /*
   91737 ** Return the type of the argument.
   91738 */
   91739 static void typeofFunc(
   91740   sqlite3_context *context,
   91741   int NotUsed,
   91742   sqlite3_value **argv
   91743 ){
   91744   const char *z = 0;
   91745   UNUSED_PARAMETER(NotUsed);
   91746   switch( sqlite3_value_type(argv[0]) ){
   91747     case SQLITE_INTEGER: z = "integer"; break;
   91748     case SQLITE_TEXT:    z = "text";    break;
   91749     case SQLITE_FLOAT:   z = "real";    break;
   91750     case SQLITE_BLOB:    z = "blob";    break;
   91751     default:             z = "null";    break;
   91752   }
   91753   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
   91754 }
   91755 
   91756 
   91757 /*
   91758 ** Implementation of the length() function
   91759 */
   91760 static void lengthFunc(
   91761   sqlite3_context *context,
   91762   int argc,
   91763   sqlite3_value **argv
   91764 ){
   91765   int len;
   91766 
   91767   assert( argc==1 );
   91768   UNUSED_PARAMETER(argc);
   91769   switch( sqlite3_value_type(argv[0]) ){
   91770     case SQLITE_BLOB:
   91771     case SQLITE_INTEGER:
   91772     case SQLITE_FLOAT: {
   91773       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   91774       break;
   91775     }
   91776     case SQLITE_TEXT: {
   91777       const unsigned char *z = sqlite3_value_text(argv[0]);
   91778       if( z==0 ) return;
   91779       len = 0;
   91780       while( *z ){
   91781         len++;
   91782         SQLITE_SKIP_UTF8(z);
   91783       }
   91784       sqlite3_result_int(context, len);
   91785       break;
   91786     }
   91787     default: {
   91788       sqlite3_result_null(context);
   91789       break;
   91790     }
   91791   }
   91792 }
   91793 
   91794 /*
   91795 ** Implementation of the abs() function.
   91796 **
   91797 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
   91798 ** the numeric argument X.
   91799 */
   91800 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   91801   assert( argc==1 );
   91802   UNUSED_PARAMETER(argc);
   91803   switch( sqlite3_value_type(argv[0]) ){
   91804     case SQLITE_INTEGER: {
   91805       i64 iVal = sqlite3_value_int64(argv[0]);
   91806       if( iVal<0 ){
   91807         if( iVal==SMALLEST_INT64 ){
   91808           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
   91809           ** then abs(X) throws an integer overflow error since there is no
   91810           ** equivalent positive 64-bit two complement value. */
   91811           sqlite3_result_error(context, "integer overflow", -1);
   91812           return;
   91813         }
   91814         iVal = -iVal;
   91815       }
   91816       sqlite3_result_int64(context, iVal);
   91817       break;
   91818     }
   91819     case SQLITE_NULL: {
   91820       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
   91821       sqlite3_result_null(context);
   91822       break;
   91823     }
   91824     default: {
   91825       /* Because sqlite3_value_double() returns 0.0 if the argument is not
   91826       ** something that can be converted into a number, we have:
   91827       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
   91828       ** cannot be converted to a numeric value.
   91829       */
   91830       double rVal = sqlite3_value_double(argv[0]);
   91831       if( rVal<0 ) rVal = -rVal;
   91832       sqlite3_result_double(context, rVal);
   91833       break;
   91834     }
   91835   }
   91836 }
   91837 
   91838 /*
   91839 ** Implementation of the instr() function.
   91840 **
   91841 ** instr(haystack,needle) finds the first occurrence of needle
   91842 ** in haystack and returns the number of previous characters plus 1,
   91843 ** or 0 if needle does not occur within haystack.
   91844 **
   91845 ** If both haystack and needle are BLOBs, then the result is one more than
   91846 ** the number of bytes in haystack prior to the first occurrence of needle,
   91847 ** or 0 if needle never occurs in haystack.
   91848 */
   91849 static void instrFunc(
   91850   sqlite3_context *context,
   91851   int argc,
   91852   sqlite3_value **argv
   91853 ){
   91854   const unsigned char *zHaystack;
   91855   const unsigned char *zNeedle;
   91856   int nHaystack;
   91857   int nNeedle;
   91858   int typeHaystack, typeNeedle;
   91859   int N = 1;
   91860   int isText;
   91861 
   91862   UNUSED_PARAMETER(argc);
   91863   typeHaystack = sqlite3_value_type(argv[0]);
   91864   typeNeedle = sqlite3_value_type(argv[1]);
   91865   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
   91866   nHaystack = sqlite3_value_bytes(argv[0]);
   91867   nNeedle = sqlite3_value_bytes(argv[1]);
   91868   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
   91869     zHaystack = sqlite3_value_blob(argv[0]);
   91870     zNeedle = sqlite3_value_blob(argv[1]);
   91871     isText = 0;
   91872   }else{
   91873     zHaystack = sqlite3_value_text(argv[0]);
   91874     zNeedle = sqlite3_value_text(argv[1]);
   91875     isText = 1;
   91876   }
   91877   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
   91878     N++;
   91879     do{
   91880       nHaystack--;
   91881       zHaystack++;
   91882     }while( isText && (zHaystack[0]&0xc0)==0x80 );
   91883   }
   91884   if( nNeedle>nHaystack ) N = 0;
   91885   sqlite3_result_int(context, N);
   91886 }
   91887 
   91888 /*
   91889 ** Implementation of the printf() function.
   91890 */
   91891 static void printfFunc(
   91892   sqlite3_context *context,
   91893   int argc,
   91894   sqlite3_value **argv
   91895 ){
   91896   PrintfArguments x;
   91897   StrAccum str;
   91898   const char *zFormat;
   91899   int n;
   91900 
   91901   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   91902     x.nArg = argc-1;
   91903     x.nUsed = 0;
   91904     x.apArg = argv+1;
   91905     sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
   91906     str.db = sqlite3_context_db_handle(context);
   91907     sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
   91908     n = str.nChar;
   91909     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
   91910                         SQLITE_DYNAMIC);
   91911   }
   91912 }
   91913 
   91914 /*
   91915 ** Implementation of the substr() function.
   91916 **
   91917 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
   91918 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
   91919 ** of x.  If x is text, then we actually count UTF-8 characters.
   91920 ** If x is a blob, then we count bytes.
   91921 **
   91922 ** If p1 is negative, then we begin abs(p1) from the end of x[].
   91923 **
   91924 ** If p2 is negative, return the p2 characters preceding p1.
   91925 */
   91926 static void substrFunc(
   91927   sqlite3_context *context,
   91928   int argc,
   91929   sqlite3_value **argv
   91930 ){
   91931   const unsigned char *z;
   91932   const unsigned char *z2;
   91933   int len;
   91934   int p0type;
   91935   i64 p1, p2;
   91936   int negP2 = 0;
   91937 
   91938   assert( argc==3 || argc==2 );
   91939   if( sqlite3_value_type(argv[1])==SQLITE_NULL
   91940    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
   91941   ){
   91942     return;
   91943   }
   91944   p0type = sqlite3_value_type(argv[0]);
   91945   p1 = sqlite3_value_int(argv[1]);
   91946   if( p0type==SQLITE_BLOB ){
   91947     len = sqlite3_value_bytes(argv[0]);
   91948     z = sqlite3_value_blob(argv[0]);
   91949     if( z==0 ) return;
   91950     assert( len==sqlite3_value_bytes(argv[0]) );
   91951   }else{
   91952     z = sqlite3_value_text(argv[0]);
   91953     if( z==0 ) return;
   91954     len = 0;
   91955     if( p1<0 ){
   91956       for(z2=z; *z2; len++){
   91957         SQLITE_SKIP_UTF8(z2);
   91958       }
   91959     }
   91960   }
   91961   if( argc==3 ){
   91962     p2 = sqlite3_value_int(argv[2]);
   91963     if( p2<0 ){
   91964       p2 = -p2;
   91965       negP2 = 1;
   91966     }
   91967   }else{
   91968     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
   91969   }
   91970   if( p1<0 ){
   91971     p1 += len;
   91972     if( p1<0 ){
   91973       p2 += p1;
   91974       if( p2<0 ) p2 = 0;
   91975       p1 = 0;
   91976     }
   91977   }else if( p1>0 ){
   91978     p1--;
   91979   }else if( p2>0 ){
   91980     p2--;
   91981   }
   91982   if( negP2 ){
   91983     p1 -= p2;
   91984     if( p1<0 ){
   91985       p2 += p1;
   91986       p1 = 0;
   91987     }
   91988   }
   91989   assert( p1>=0 && p2>=0 );
   91990   if( p0type!=SQLITE_BLOB ){
   91991     while( *z && p1 ){
   91992       SQLITE_SKIP_UTF8(z);
   91993       p1--;
   91994     }
   91995     for(z2=z; *z2 && p2; p2--){
   91996       SQLITE_SKIP_UTF8(z2);
   91997     }
   91998     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
   91999   }else{
   92000     if( p1+p2>len ){
   92001       p2 = len-p1;
   92002       if( p2<0 ) p2 = 0;
   92003     }
   92004     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
   92005   }
   92006 }
   92007 
   92008 /*
   92009 ** Implementation of the round() function
   92010 */
   92011 #ifndef SQLITE_OMIT_FLOATING_POINT
   92012 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   92013   int n = 0;
   92014   double r;
   92015   char *zBuf;
   92016   assert( argc==1 || argc==2 );
   92017   if( argc==2 ){
   92018     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
   92019     n = sqlite3_value_int(argv[1]);
   92020     if( n>30 ) n = 30;
   92021     if( n<0 ) n = 0;
   92022   }
   92023   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   92024   r = sqlite3_value_double(argv[0]);
   92025   /* If Y==0 and X will fit in a 64-bit int,
   92026   ** handle the rounding directly,
   92027   ** otherwise use printf.
   92028   */
   92029   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
   92030     r = (double)((sqlite_int64)(r+0.5));
   92031   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
   92032     r = -(double)((sqlite_int64)((-r)+0.5));
   92033   }else{
   92034     zBuf = sqlite3_mprintf("%.*f",n,r);
   92035     if( zBuf==0 ){
   92036       sqlite3_result_error_nomem(context);
   92037       return;
   92038     }
   92039     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
   92040     sqlite3_free(zBuf);
   92041   }
   92042   sqlite3_result_double(context, r);
   92043 }
   92044 #endif
   92045 
   92046 /*
   92047 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
   92048 ** allocation fails, call sqlite3_result_error_nomem() to notify
   92049 ** the database handle that malloc() has failed and return NULL.
   92050 ** If nByte is larger than the maximum string or blob length, then
   92051 ** raise an SQLITE_TOOBIG exception and return NULL.
   92052 */
   92053 static void *contextMalloc(sqlite3_context *context, i64 nByte){
   92054   char *z;
   92055   sqlite3 *db = sqlite3_context_db_handle(context);
   92056   assert( nByte>0 );
   92057   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
   92058   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   92059   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   92060     sqlite3_result_error_toobig(context);
   92061     z = 0;
   92062   }else{
   92063     z = sqlite3Malloc((int)nByte);
   92064     if( !z ){
   92065       sqlite3_result_error_nomem(context);
   92066     }
   92067   }
   92068   return z;
   92069 }
   92070 
   92071 /*
   92072 ** Implementation of the upper() and lower() SQL functions.
   92073 */
   92074 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   92075   char *z1;
   92076   const char *z2;
   92077   int i, n;
   92078   UNUSED_PARAMETER(argc);
   92079   z2 = (char*)sqlite3_value_text(argv[0]);
   92080   n = sqlite3_value_bytes(argv[0]);
   92081   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   92082   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   92083   if( z2 ){
   92084     z1 = contextMalloc(context, ((i64)n)+1);
   92085     if( z1 ){
   92086       for(i=0; i<n; i++){
   92087         z1[i] = (char)sqlite3Toupper(z2[i]);
   92088       }
   92089       sqlite3_result_text(context, z1, n, sqlite3_free);
   92090     }
   92091   }
   92092 }
   92093 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   92094   char *z1;
   92095   const char *z2;
   92096   int i, n;
   92097   UNUSED_PARAMETER(argc);
   92098   z2 = (char*)sqlite3_value_text(argv[0]);
   92099   n = sqlite3_value_bytes(argv[0]);
   92100   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   92101   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   92102   if( z2 ){
   92103     z1 = contextMalloc(context, ((i64)n)+1);
   92104     if( z1 ){
   92105       for(i=0; i<n; i++){
   92106         z1[i] = sqlite3Tolower(z2[i]);
   92107       }
   92108       sqlite3_result_text(context, z1, n, sqlite3_free);
   92109     }
   92110   }
   92111 }
   92112 
   92113 /*
   92114 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
   92115 ** as VDBE code so that unused argument values do not have to be computed.
   92116 ** However, we still need some kind of function implementation for this
   92117 ** routines in the function table.  The noopFunc macro provides this.
   92118 ** noopFunc will never be called so it doesn't matter what the implementation
   92119 ** is.  We might as well use the "version()" function as a substitute.
   92120 */
   92121 #define noopFunc versionFunc   /* Substitute function - never called */
   92122 
   92123 /*
   92124 ** Implementation of random().  Return a random integer.
   92125 */
   92126 static void randomFunc(
   92127   sqlite3_context *context,
   92128   int NotUsed,
   92129   sqlite3_value **NotUsed2
   92130 ){
   92131   sqlite_int64 r;
   92132   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92133   sqlite3_randomness(sizeof(r), &r);
   92134   if( r<0 ){
   92135     /* We need to prevent a random number of 0x8000000000000000
   92136     ** (or -9223372036854775808) since when you do abs() of that
   92137     ** number of you get the same value back again.  To do this
   92138     ** in a way that is testable, mask the sign bit off of negative
   92139     ** values, resulting in a positive value.  Then take the
   92140     ** 2s complement of that positive value.  The end result can
   92141     ** therefore be no less than -9223372036854775807.
   92142     */
   92143     r = -(r & LARGEST_INT64);
   92144   }
   92145   sqlite3_result_int64(context, r);
   92146 }
   92147 
   92148 /*
   92149 ** Implementation of randomblob(N).  Return a random blob
   92150 ** that is N bytes long.
   92151 */
   92152 static void randomBlob(
   92153   sqlite3_context *context,
   92154   int argc,
   92155   sqlite3_value **argv
   92156 ){
   92157   int n;
   92158   unsigned char *p;
   92159   assert( argc==1 );
   92160   UNUSED_PARAMETER(argc);
   92161   n = sqlite3_value_int(argv[0]);
   92162   if( n<1 ){
   92163     n = 1;
   92164   }
   92165   p = contextMalloc(context, n);
   92166   if( p ){
   92167     sqlite3_randomness(n, p);
   92168     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   92169   }
   92170 }
   92171 
   92172 /*
   92173 ** Implementation of the last_insert_rowid() SQL function.  The return
   92174 ** value is the same as the sqlite3_last_insert_rowid() API function.
   92175 */
   92176 static void last_insert_rowid(
   92177   sqlite3_context *context,
   92178   int NotUsed,
   92179   sqlite3_value **NotUsed2
   92180 ){
   92181   sqlite3 *db = sqlite3_context_db_handle(context);
   92182   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92183   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
   92184   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
   92185   ** function. */
   92186   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
   92187 }
   92188 
   92189 /*
   92190 ** Implementation of the changes() SQL function.
   92191 **
   92192 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
   92193 ** around the sqlite3_changes() C/C++ function and hence follows the same
   92194 ** rules for counting changes.
   92195 */
   92196 static void changes(
   92197   sqlite3_context *context,
   92198   int NotUsed,
   92199   sqlite3_value **NotUsed2
   92200 ){
   92201   sqlite3 *db = sqlite3_context_db_handle(context);
   92202   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92203   sqlite3_result_int(context, sqlite3_changes(db));
   92204 }
   92205 
   92206 /*
   92207 ** Implementation of the total_changes() SQL function.  The return value is
   92208 ** the same as the sqlite3_total_changes() API function.
   92209 */
   92210 static void total_changes(
   92211   sqlite3_context *context,
   92212   int NotUsed,
   92213   sqlite3_value **NotUsed2
   92214 ){
   92215   sqlite3 *db = sqlite3_context_db_handle(context);
   92216   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92217   /* IMP: R-52756-41993 This function is a wrapper around the
   92218   ** sqlite3_total_changes() C/C++ interface. */
   92219   sqlite3_result_int(context, sqlite3_total_changes(db));
   92220 }
   92221 
   92222 /*
   92223 ** A structure defining how to do GLOB-style comparisons.
   92224 */
   92225 struct compareInfo {
   92226   u8 matchAll;
   92227   u8 matchOne;
   92228   u8 matchSet;
   92229   u8 noCase;
   92230 };
   92231 
   92232 /*
   92233 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
   92234 ** character is exactly one byte in size.  Also, all characters are
   92235 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
   92236 ** whereas only characters less than 0x80 do in ASCII.
   92237 */
   92238 #if defined(SQLITE_EBCDIC)
   92239 # define sqlite3Utf8Read(A)    (*((*A)++))
   92240 # define GlobUpperToLower(A)   A = sqlite3UpperToLower[A]
   92241 #else
   92242 # define GlobUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
   92243 #endif
   92244 
   92245 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   92246 /* The correct SQL-92 behavior is for the LIKE operator to ignore
   92247 ** case.  Thus  'a' LIKE 'A' would be true. */
   92248 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   92249 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   92250 ** is case sensitive causing 'a' LIKE 'A' to be false */
   92251 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   92252 
   92253 /*
   92254 ** Compare two UTF-8 strings for equality where the first string can
   92255 ** potentially be a "glob" expression.  Return true (1) if they
   92256 ** are the same and false (0) if they are different.
   92257 **
   92258 ** Globbing rules:
   92259 **
   92260 **      '*'       Matches any sequence of zero or more characters.
   92261 **
   92262 **      '?'       Matches exactly one character.
   92263 **
   92264 **     [...]      Matches one character from the enclosed list of
   92265 **                characters.
   92266 **
   92267 **     [^...]     Matches one character not in the enclosed list.
   92268 **
   92269 ** With the [...] and [^...] matching, a ']' character can be included
   92270 ** in the list by making it the first character after '[' or '^'.  A
   92271 ** range of characters can be specified using '-'.  Example:
   92272 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
   92273 ** it the last character in the list.
   92274 **
   92275 ** This routine is usually quick, but can be N**2 in the worst case.
   92276 **
   92277 ** Hints: to match '*' or '?', put them in "[]".  Like this:
   92278 **
   92279 **         abc[*]xyz        Matches "abc*xyz" only
   92280 */
   92281 static int patternCompare(
   92282   const u8 *zPattern,              /* The glob pattern */
   92283   const u8 *zString,               /* The string to compare against the glob */
   92284   const struct compareInfo *pInfo, /* Information about how to do the compare */
   92285   u32 esc                          /* The escape character */
   92286 ){
   92287   u32 c, c2;
   92288   int invert;
   92289   int seen;
   92290   u8 matchOne = pInfo->matchOne;
   92291   u8 matchAll = pInfo->matchAll;
   92292   u8 matchSet = pInfo->matchSet;
   92293   u8 noCase = pInfo->noCase;
   92294   int prevEscape = 0;     /* True if the previous character was 'escape' */
   92295 
   92296   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
   92297     if( c==matchAll && !prevEscape ){
   92298       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
   92299                || c == matchOne ){
   92300         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
   92301           return 0;
   92302         }
   92303       }
   92304       if( c==0 ){
   92305         return 1;
   92306       }else if( c==esc ){
   92307         c = sqlite3Utf8Read(&zPattern);
   92308         if( c==0 ){
   92309           return 0;
   92310         }
   92311       }else if( c==matchSet ){
   92312         assert( esc==0 );         /* This is GLOB, not LIKE */
   92313         assert( matchSet<0x80 );  /* '[' is a single-byte character */
   92314         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
   92315           SQLITE_SKIP_UTF8(zString);
   92316         }
   92317         return *zString!=0;
   92318       }
   92319       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
   92320         if( noCase ){
   92321           GlobUpperToLower(c2);
   92322           GlobUpperToLower(c);
   92323           while( c2 != 0 && c2 != c ){
   92324             c2 = sqlite3Utf8Read(&zString);
   92325             GlobUpperToLower(c2);
   92326           }
   92327         }else{
   92328           while( c2 != 0 && c2 != c ){
   92329             c2 = sqlite3Utf8Read(&zString);
   92330           }
   92331         }
   92332         if( c2==0 ) return 0;
   92333         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
   92334       }
   92335       return 0;
   92336     }else if( c==matchOne && !prevEscape ){
   92337       if( sqlite3Utf8Read(&zString)==0 ){
   92338         return 0;
   92339       }
   92340     }else if( c==matchSet ){
   92341       u32 prior_c = 0;
   92342       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
   92343       seen = 0;
   92344       invert = 0;
   92345       c = sqlite3Utf8Read(&zString);
   92346       if( c==0 ) return 0;
   92347       c2 = sqlite3Utf8Read(&zPattern);
   92348       if( c2=='^' ){
   92349         invert = 1;
   92350         c2 = sqlite3Utf8Read(&zPattern);
   92351       }
   92352       if( c2==']' ){
   92353         if( c==']' ) seen = 1;
   92354         c2 = sqlite3Utf8Read(&zPattern);
   92355       }
   92356       while( c2 && c2!=']' ){
   92357         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
   92358           c2 = sqlite3Utf8Read(&zPattern);
   92359           if( c>=prior_c && c<=c2 ) seen = 1;
   92360           prior_c = 0;
   92361         }else{
   92362           if( c==c2 ){
   92363             seen = 1;
   92364           }
   92365           prior_c = c2;
   92366         }
   92367         c2 = sqlite3Utf8Read(&zPattern);
   92368       }
   92369       if( c2==0 || (seen ^ invert)==0 ){
   92370         return 0;
   92371       }
   92372     }else if( esc==c && !prevEscape ){
   92373       prevEscape = 1;
   92374     }else{
   92375       c2 = sqlite3Utf8Read(&zString);
   92376       if( noCase ){
   92377         GlobUpperToLower(c);
   92378         GlobUpperToLower(c2);
   92379       }
   92380       if( c!=c2 ){
   92381         return 0;
   92382       }
   92383       prevEscape = 0;
   92384     }
   92385   }
   92386   return *zString==0;
   92387 }
   92388 
   92389 /*
   92390 ** The sqlite3_strglob() interface.
   92391 */
   92392 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
   92393   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
   92394 }
   92395 
   92396 /*
   92397 ** Count the number of times that the LIKE operator (or GLOB which is
   92398 ** just a variation of LIKE) gets called.  This is used for testing
   92399 ** only.
   92400 */
   92401 #ifdef SQLITE_TEST
   92402 SQLITE_API int sqlite3_like_count = 0;
   92403 #endif
   92404 
   92405 
   92406 /*
   92407 ** Implementation of the like() SQL function.  This function implements
   92408 ** the build-in LIKE operator.  The first argument to the function is the
   92409 ** pattern and the second argument is the string.  So, the SQL statements:
   92410 **
   92411 **       A LIKE B
   92412 **
   92413 ** is implemented as like(B,A).
   92414 **
   92415 ** This same function (with a different compareInfo structure) computes
   92416 ** the GLOB operator.
   92417 */
   92418 static void likeFunc(
   92419   sqlite3_context *context,
   92420   int argc,
   92421   sqlite3_value **argv
   92422 ){
   92423   const unsigned char *zA, *zB;
   92424   u32 escape = 0;
   92425   int nPat;
   92426   sqlite3 *db = sqlite3_context_db_handle(context);
   92427 
   92428   zB = sqlite3_value_text(argv[0]);
   92429   zA = sqlite3_value_text(argv[1]);
   92430 
   92431   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   92432   ** of deep recursion and N*N behavior in patternCompare().
   92433   */
   92434   nPat = sqlite3_value_bytes(argv[0]);
   92435   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
   92436   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
   92437   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
   92438     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   92439     return;
   92440   }
   92441   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
   92442 
   92443   if( argc==3 ){
   92444     /* The escape character string must consist of a single UTF-8 character.
   92445     ** Otherwise, return an error.
   92446     */
   92447     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   92448     if( zEsc==0 ) return;
   92449     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
   92450       sqlite3_result_error(context,
   92451           "ESCAPE expression must be a single character", -1);
   92452       return;
   92453     }
   92454     escape = sqlite3Utf8Read(&zEsc);
   92455   }
   92456   if( zA && zB ){
   92457     struct compareInfo *pInfo = sqlite3_user_data(context);
   92458 #ifdef SQLITE_TEST
   92459     sqlite3_like_count++;
   92460 #endif
   92461 
   92462     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
   92463   }
   92464 }
   92465 
   92466 /*
   92467 ** Implementation of the NULLIF(x,y) function.  The result is the first
   92468 ** argument if the arguments are different.  The result is NULL if the
   92469 ** arguments are equal to each other.
   92470 */
   92471 static void nullifFunc(
   92472   sqlite3_context *context,
   92473   int NotUsed,
   92474   sqlite3_value **argv
   92475 ){
   92476   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   92477   UNUSED_PARAMETER(NotUsed);
   92478   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
   92479     sqlite3_result_value(context, argv[0]);
   92480   }
   92481 }
   92482 
   92483 /*
   92484 ** Implementation of the sqlite_version() function.  The result is the version
   92485 ** of the SQLite library that is running.
   92486 */
   92487 static void versionFunc(
   92488   sqlite3_context *context,
   92489   int NotUsed,
   92490   sqlite3_value **NotUsed2
   92491 ){
   92492   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92493   /* IMP: R-48699-48617 This function is an SQL wrapper around the
   92494   ** sqlite3_libversion() C-interface. */
   92495   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
   92496 }
   92497 
   92498 /*
   92499 ** Implementation of the sqlite_source_id() function. The result is a string
   92500 ** that identifies the particular version of the source code used to build
   92501 ** SQLite.
   92502 */
   92503 static void sourceidFunc(
   92504   sqlite3_context *context,
   92505   int NotUsed,
   92506   sqlite3_value **NotUsed2
   92507 ){
   92508   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   92509   /* IMP: R-24470-31136 This function is an SQL wrapper around the
   92510   ** sqlite3_sourceid() C interface. */
   92511   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
   92512 }
   92513 
   92514 /*
   92515 ** Implementation of the sqlite_log() function.  This is a wrapper around
   92516 ** sqlite3_log().  The return value is NULL.  The function exists purely for
   92517 ** its side-effects.
   92518 */
   92519 static void errlogFunc(
   92520   sqlite3_context *context,
   92521   int argc,
   92522   sqlite3_value **argv
   92523 ){
   92524   UNUSED_PARAMETER(argc);
   92525   UNUSED_PARAMETER(context);
   92526   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
   92527 }
   92528 
   92529 /*
   92530 ** Implementation of the sqlite_compileoption_used() function.
   92531 ** The result is an integer that identifies if the compiler option
   92532 ** was used to build SQLite.
   92533 */
   92534 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   92535 static void compileoptionusedFunc(
   92536   sqlite3_context *context,
   92537   int argc,
   92538   sqlite3_value **argv
   92539 ){
   92540   const char *zOptName;
   92541   assert( argc==1 );
   92542   UNUSED_PARAMETER(argc);
   92543   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
   92544   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
   92545   ** function.
   92546   */
   92547   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   92548     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
   92549   }
   92550 }
   92551 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   92552 
   92553 /*
   92554 ** Implementation of the sqlite_compileoption_get() function.
   92555 ** The result is a string that identifies the compiler options
   92556 ** used to build SQLite.
   92557 */
   92558 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   92559 static void compileoptiongetFunc(
   92560   sqlite3_context *context,
   92561   int argc,
   92562   sqlite3_value **argv
   92563 ){
   92564   int n;
   92565   assert( argc==1 );
   92566   UNUSED_PARAMETER(argc);
   92567   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
   92568   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
   92569   */
   92570   n = sqlite3_value_int(argv[0]);
   92571   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
   92572 }
   92573 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   92574 
   92575 /* Array for converting from half-bytes (nybbles) into ASCII hex
   92576 ** digits. */
   92577 static const char hexdigits[] = {
   92578   '0', '1', '2', '3', '4', '5', '6', '7',
   92579   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
   92580 };
   92581 
   92582 /*
   92583 ** Implementation of the QUOTE() function.  This function takes a single
   92584 ** argument.  If the argument is numeric, the return value is the same as
   92585 ** the argument.  If the argument is NULL, the return value is the string
   92586 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
   92587 ** single-quote escapes.
   92588 */
   92589 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   92590   assert( argc==1 );
   92591   UNUSED_PARAMETER(argc);
   92592   switch( sqlite3_value_type(argv[0]) ){
   92593     case SQLITE_FLOAT: {
   92594       double r1, r2;
   92595       char zBuf[50];
   92596       r1 = sqlite3_value_double(argv[0]);
   92597       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
   92598       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
   92599       if( r1!=r2 ){
   92600         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
   92601       }
   92602       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   92603       break;
   92604     }
   92605     case SQLITE_INTEGER: {
   92606       sqlite3_result_value(context, argv[0]);
   92607       break;
   92608     }
   92609     case SQLITE_BLOB: {
   92610       char *zText = 0;
   92611       char const *zBlob = sqlite3_value_blob(argv[0]);
   92612       int nBlob = sqlite3_value_bytes(argv[0]);
   92613       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   92614       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
   92615       if( zText ){
   92616         int i;
   92617         for(i=0; i<nBlob; i++){
   92618           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   92619           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   92620         }
   92621         zText[(nBlob*2)+2] = '\'';
   92622         zText[(nBlob*2)+3] = '\0';
   92623         zText[0] = 'X';
   92624         zText[1] = '\'';
   92625         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   92626         sqlite3_free(zText);
   92627       }
   92628       break;
   92629     }
   92630     case SQLITE_TEXT: {
   92631       int i,j;
   92632       u64 n;
   92633       const unsigned char *zArg = sqlite3_value_text(argv[0]);
   92634       char *z;
   92635 
   92636       if( zArg==0 ) return;
   92637       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   92638       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
   92639       if( z ){
   92640         z[0] = '\'';
   92641         for(i=0, j=1; zArg[i]; i++){
   92642           z[j++] = zArg[i];
   92643           if( zArg[i]=='\'' ){
   92644             z[j++] = '\'';
   92645           }
   92646         }
   92647         z[j++] = '\'';
   92648         z[j] = 0;
   92649         sqlite3_result_text(context, z, j, sqlite3_free);
   92650       }
   92651       break;
   92652     }
   92653     default: {
   92654       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
   92655       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
   92656       break;
   92657     }
   92658   }
   92659 }
   92660 
   92661 /*
   92662 ** The unicode() function.  Return the integer unicode code-point value
   92663 ** for the first character of the input string.
   92664 */
   92665 static void unicodeFunc(
   92666   sqlite3_context *context,
   92667   int argc,
   92668   sqlite3_value **argv
   92669 ){
   92670   const unsigned char *z = sqlite3_value_text(argv[0]);
   92671   (void)argc;
   92672   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
   92673 }
   92674 
   92675 /*
   92676 ** The char() function takes zero or more arguments, each of which is
   92677 ** an integer.  It constructs a string where each character of the string
   92678 ** is the unicode character for the corresponding integer argument.
   92679 */
   92680 static void charFunc(
   92681   sqlite3_context *context,
   92682   int argc,
   92683   sqlite3_value **argv
   92684 ){
   92685   unsigned char *z, *zOut;
   92686   int i;
   92687   zOut = z = sqlite3_malloc( argc*4+1 );
   92688   if( z==0 ){
   92689     sqlite3_result_error_nomem(context);
   92690     return;
   92691   }
   92692   for(i=0; i<argc; i++){
   92693     sqlite3_int64 x;
   92694     unsigned c;
   92695     x = sqlite3_value_int64(argv[i]);
   92696     if( x<0 || x>0x10ffff ) x = 0xfffd;
   92697     c = (unsigned)(x & 0x1fffff);
   92698     if( c<0x00080 ){
   92699       *zOut++ = (u8)(c&0xFF);
   92700     }else if( c<0x00800 ){
   92701       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
   92702       *zOut++ = 0x80 + (u8)(c & 0x3F);
   92703     }else if( c<0x10000 ){
   92704       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
   92705       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
   92706       *zOut++ = 0x80 + (u8)(c & 0x3F);
   92707     }else{
   92708       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
   92709       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
   92710       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
   92711       *zOut++ = 0x80 + (u8)(c & 0x3F);
   92712     }                                                    \
   92713   }
   92714   sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
   92715 }
   92716 
   92717 /*
   92718 ** The hex() function.  Interpret the argument as a blob.  Return
   92719 ** a hexadecimal rendering as text.
   92720 */
   92721 static void hexFunc(
   92722   sqlite3_context *context,
   92723   int argc,
   92724   sqlite3_value **argv
   92725 ){
   92726   int i, n;
   92727   const unsigned char *pBlob;
   92728   char *zHex, *z;
   92729   assert( argc==1 );
   92730   UNUSED_PARAMETER(argc);
   92731   pBlob = sqlite3_value_blob(argv[0]);
   92732   n = sqlite3_value_bytes(argv[0]);
   92733   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   92734   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
   92735   if( zHex ){
   92736     for(i=0; i<n; i++, pBlob++){
   92737       unsigned char c = *pBlob;
   92738       *(z++) = hexdigits[(c>>4)&0xf];
   92739       *(z++) = hexdigits[c&0xf];
   92740     }
   92741     *z = 0;
   92742     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   92743   }
   92744 }
   92745 
   92746 /*
   92747 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   92748 */
   92749 static void zeroblobFunc(
   92750   sqlite3_context *context,
   92751   int argc,
   92752   sqlite3_value **argv
   92753 ){
   92754   i64 n;
   92755   sqlite3 *db = sqlite3_context_db_handle(context);
   92756   assert( argc==1 );
   92757   UNUSED_PARAMETER(argc);
   92758   n = sqlite3_value_int64(argv[0]);
   92759   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
   92760   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   92761   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   92762     sqlite3_result_error_toobig(context);
   92763   }else{
   92764     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
   92765   }
   92766 }
   92767 
   92768 /*
   92769 ** The replace() function.  Three arguments are all strings: call
   92770 ** them A, B, and C. The result is also a string which is derived
   92771 ** from A by replacing every occurrence of B with C.  The match
   92772 ** must be exact.  Collating sequences are not used.
   92773 */
   92774 static void replaceFunc(
   92775   sqlite3_context *context,
   92776   int argc,
   92777   sqlite3_value **argv
   92778 ){
   92779   const unsigned char *zStr;        /* The input string A */
   92780   const unsigned char *zPattern;    /* The pattern string B */
   92781   const unsigned char *zRep;        /* The replacement string C */
   92782   unsigned char *zOut;              /* The output */
   92783   int nStr;                /* Size of zStr */
   92784   int nPattern;            /* Size of zPattern */
   92785   int nRep;                /* Size of zRep */
   92786   i64 nOut;                /* Maximum size of zOut */
   92787   int loopLimit;           /* Last zStr[] that might match zPattern[] */
   92788   int i, j;                /* Loop counters */
   92789 
   92790   assert( argc==3 );
   92791   UNUSED_PARAMETER(argc);
   92792   zStr = sqlite3_value_text(argv[0]);
   92793   if( zStr==0 ) return;
   92794   nStr = sqlite3_value_bytes(argv[0]);
   92795   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
   92796   zPattern = sqlite3_value_text(argv[1]);
   92797   if( zPattern==0 ){
   92798     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
   92799             || sqlite3_context_db_handle(context)->mallocFailed );
   92800     return;
   92801   }
   92802   if( zPattern[0]==0 ){
   92803     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
   92804     sqlite3_result_value(context, argv[0]);
   92805     return;
   92806   }
   92807   nPattern = sqlite3_value_bytes(argv[1]);
   92808   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   92809   zRep = sqlite3_value_text(argv[2]);
   92810   if( zRep==0 ) return;
   92811   nRep = sqlite3_value_bytes(argv[2]);
   92812   assert( zRep==sqlite3_value_text(argv[2]) );
   92813   nOut = nStr + 1;
   92814   assert( nOut<SQLITE_MAX_LENGTH );
   92815   zOut = contextMalloc(context, (i64)nOut);
   92816   if( zOut==0 ){
   92817     return;
   92818   }
   92819   loopLimit = nStr - nPattern;
   92820   for(i=j=0; i<=loopLimit; i++){
   92821     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   92822       zOut[j++] = zStr[i];
   92823     }else{
   92824       u8 *zOld;
   92825       sqlite3 *db = sqlite3_context_db_handle(context);
   92826       nOut += nRep - nPattern;
   92827       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
   92828       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
   92829       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   92830         sqlite3_result_error_toobig(context);
   92831         sqlite3_free(zOut);
   92832         return;
   92833       }
   92834       zOld = zOut;
   92835       zOut = sqlite3_realloc(zOut, (int)nOut);
   92836       if( zOut==0 ){
   92837         sqlite3_result_error_nomem(context);
   92838         sqlite3_free(zOld);
   92839         return;
   92840       }
   92841       memcpy(&zOut[j], zRep, nRep);
   92842       j += nRep;
   92843       i += nPattern-1;
   92844     }
   92845   }
   92846   assert( j+nStr-i+1==nOut );
   92847   memcpy(&zOut[j], &zStr[i], nStr-i);
   92848   j += nStr - i;
   92849   assert( j<=nOut );
   92850   zOut[j] = 0;
   92851   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
   92852 }
   92853 
   92854 /*
   92855 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
   92856 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
   92857 */
   92858 static void trimFunc(
   92859   sqlite3_context *context,
   92860   int argc,
   92861   sqlite3_value **argv
   92862 ){
   92863   const unsigned char *zIn;         /* Input string */
   92864   const unsigned char *zCharSet;    /* Set of characters to trim */
   92865   int nIn;                          /* Number of bytes in input */
   92866   int flags;                        /* 1: trimleft  2: trimright  3: trim */
   92867   int i;                            /* Loop counter */
   92868   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
   92869   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
   92870   int nChar;                        /* Number of characters in zCharSet */
   92871 
   92872   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   92873     return;
   92874   }
   92875   zIn = sqlite3_value_text(argv[0]);
   92876   if( zIn==0 ) return;
   92877   nIn = sqlite3_value_bytes(argv[0]);
   92878   assert( zIn==sqlite3_value_text(argv[0]) );
   92879   if( argc==1 ){
   92880     static const unsigned char lenOne[] = { 1 };
   92881     static unsigned char * const azOne[] = { (u8*)" " };
   92882     nChar = 1;
   92883     aLen = (u8*)lenOne;
   92884     azChar = (unsigned char **)azOne;
   92885     zCharSet = 0;
   92886   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
   92887     return;
   92888   }else{
   92889     const unsigned char *z;
   92890     for(z=zCharSet, nChar=0; *z; nChar++){
   92891       SQLITE_SKIP_UTF8(z);
   92892     }
   92893     if( nChar>0 ){
   92894       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
   92895       if( azChar==0 ){
   92896         return;
   92897       }
   92898       aLen = (unsigned char*)&azChar[nChar];
   92899       for(z=zCharSet, nChar=0; *z; nChar++){
   92900         azChar[nChar] = (unsigned char *)z;
   92901         SQLITE_SKIP_UTF8(z);
   92902         aLen[nChar] = (u8)(z - azChar[nChar]);
   92903       }
   92904     }
   92905   }
   92906   if( nChar>0 ){
   92907     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
   92908     if( flags & 1 ){
   92909       while( nIn>0 ){
   92910         int len = 0;
   92911         for(i=0; i<nChar; i++){
   92912           len = aLen[i];
   92913           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
   92914         }
   92915         if( i>=nChar ) break;
   92916         zIn += len;
   92917         nIn -= len;
   92918       }
   92919     }
   92920     if( flags & 2 ){
   92921       while( nIn>0 ){
   92922         int len = 0;
   92923         for(i=0; i<nChar; i++){
   92924           len = aLen[i];
   92925           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
   92926         }
   92927         if( i>=nChar ) break;
   92928         nIn -= len;
   92929       }
   92930     }
   92931     if( zCharSet ){
   92932       sqlite3_free(azChar);
   92933     }
   92934   }
   92935   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
   92936 }
   92937 
   92938 
   92939 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
   92940 ** is only available if the SQLITE_SOUNDEX compile-time option is used
   92941 ** when SQLite is built.
   92942 */
   92943 #ifdef SQLITE_SOUNDEX
   92944 /*
   92945 ** Compute the soundex encoding of a word.
   92946 **
   92947 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
   92948 ** soundex encoding of the string X.
   92949 */
   92950 static void soundexFunc(
   92951   sqlite3_context *context,
   92952   int argc,
   92953   sqlite3_value **argv
   92954 ){
   92955   char zResult[8];
   92956   const u8 *zIn;
   92957   int i, j;
   92958   static const unsigned char iCode[] = {
   92959     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   92960     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   92961     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   92962     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   92963     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   92964     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   92965     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   92966     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   92967   };
   92968   assert( argc==1 );
   92969   zIn = (u8*)sqlite3_value_text(argv[0]);
   92970   if( zIn==0 ) zIn = (u8*)"";
   92971   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
   92972   if( zIn[i] ){
   92973     u8 prevcode = iCode[zIn[i]&0x7f];
   92974     zResult[0] = sqlite3Toupper(zIn[i]);
   92975     for(j=1; j<4 && zIn[i]; i++){
   92976       int code = iCode[zIn[i]&0x7f];
   92977       if( code>0 ){
   92978         if( code!=prevcode ){
   92979           prevcode = code;
   92980           zResult[j++] = code + '0';
   92981         }
   92982       }else{
   92983         prevcode = 0;
   92984       }
   92985     }
   92986     while( j<4 ){
   92987       zResult[j++] = '0';
   92988     }
   92989     zResult[j] = 0;
   92990     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
   92991   }else{
   92992     /* IMP: R-64894-50321 The string "?000" is returned if the argument
   92993     ** is NULL or contains no ASCII alphabetic characters. */
   92994     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
   92995   }
   92996 }
   92997 #endif /* SQLITE_SOUNDEX */
   92998 
   92999 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   93000 /*
   93001 ** A function that loads a shared-library extension then returns NULL.
   93002 */
   93003 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
   93004   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
   93005   const char *zProc;
   93006   sqlite3 *db = sqlite3_context_db_handle(context);
   93007   char *zErrMsg = 0;
   93008 
   93009   if( argc==2 ){
   93010     zProc = (const char *)sqlite3_value_text(argv[1]);
   93011   }else{
   93012     zProc = 0;
   93013   }
   93014   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
   93015     sqlite3_result_error(context, zErrMsg, -1);
   93016     sqlite3_free(zErrMsg);
   93017   }
   93018 }
   93019 #endif
   93020 
   93021 
   93022 /*
   93023 ** An instance of the following structure holds the context of a
   93024 ** sum() or avg() aggregate computation.
   93025 */
   93026 typedef struct SumCtx SumCtx;
   93027 struct SumCtx {
   93028   double rSum;      /* Floating point sum */
   93029   i64 iSum;         /* Integer sum */
   93030   i64 cnt;          /* Number of elements summed */
   93031   u8 overflow;      /* True if integer overflow seen */
   93032   u8 approx;        /* True if non-integer value was input to the sum */
   93033 };
   93034 
   93035 /*
   93036 ** Routines used to compute the sum, average, and total.
   93037 **
   93038 ** The SUM() function follows the (broken) SQL standard which means
   93039 ** that it returns NULL if it sums over no inputs.  TOTAL returns
   93040 ** 0.0 in that case.  In addition, TOTAL always returns a float where
   93041 ** SUM might return an integer if it never encounters a floating point
   93042 ** value.  TOTAL never fails, but SUM might through an exception if
   93043 ** it overflows an integer.
   93044 */
   93045 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   93046   SumCtx *p;
   93047   int type;
   93048   assert( argc==1 );
   93049   UNUSED_PARAMETER(argc);
   93050   p = sqlite3_aggregate_context(context, sizeof(*p));
   93051   type = sqlite3_value_numeric_type(argv[0]);
   93052   if( p && type!=SQLITE_NULL ){
   93053     p->cnt++;
   93054     if( type==SQLITE_INTEGER ){
   93055       i64 v = sqlite3_value_int64(argv[0]);
   93056       p->rSum += v;
   93057       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
   93058         p->overflow = 1;
   93059       }
   93060     }else{
   93061       p->rSum += sqlite3_value_double(argv[0]);
   93062       p->approx = 1;
   93063     }
   93064   }
   93065 }
   93066 static void sumFinalize(sqlite3_context *context){
   93067   SumCtx *p;
   93068   p = sqlite3_aggregate_context(context, 0);
   93069   if( p && p->cnt>0 ){
   93070     if( p->overflow ){
   93071       sqlite3_result_error(context,"integer overflow",-1);
   93072     }else if( p->approx ){
   93073       sqlite3_result_double(context, p->rSum);
   93074     }else{
   93075       sqlite3_result_int64(context, p->iSum);
   93076     }
   93077   }
   93078 }
   93079 static void avgFinalize(sqlite3_context *context){
   93080   SumCtx *p;
   93081   p = sqlite3_aggregate_context(context, 0);
   93082   if( p && p->cnt>0 ){
   93083     sqlite3_result_double(context, p->rSum/(double)p->cnt);
   93084   }
   93085 }
   93086 static void totalFinalize(sqlite3_context *context){
   93087   SumCtx *p;
   93088   p = sqlite3_aggregate_context(context, 0);
   93089   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   93090   sqlite3_result_double(context, p ? p->rSum : (double)0);
   93091 }
   93092 
   93093 /*
   93094 ** The following structure keeps track of state information for the
   93095 ** count() aggregate function.
   93096 */
   93097 typedef struct CountCtx CountCtx;
   93098 struct CountCtx {
   93099   i64 n;
   93100 };
   93101 
   93102 /*
   93103 ** Routines to implement the count() aggregate function.
   93104 */
   93105 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   93106   CountCtx *p;
   93107   p = sqlite3_aggregate_context(context, sizeof(*p));
   93108   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
   93109     p->n++;
   93110   }
   93111 
   93112 #ifndef SQLITE_OMIT_DEPRECATED
   93113   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
   93114   ** sure it still operates correctly, verify that its count agrees with our
   93115   ** internal count when using count(*) and when the total count can be
   93116   ** expressed as a 32-bit integer. */
   93117   assert( argc==1 || p==0 || p->n>0x7fffffff
   93118           || p->n==sqlite3_aggregate_count(context) );
   93119 #endif
   93120 }
   93121 static void countFinalize(sqlite3_context *context){
   93122   CountCtx *p;
   93123   p = sqlite3_aggregate_context(context, 0);
   93124   sqlite3_result_int64(context, p ? p->n : 0);
   93125 }
   93126 
   93127 /*
   93128 ** Routines to implement min() and max() aggregate functions.
   93129 */
   93130 static void minmaxStep(
   93131   sqlite3_context *context,
   93132   int NotUsed,
   93133   sqlite3_value **argv
   93134 ){
   93135   Mem *pArg  = (Mem *)argv[0];
   93136   Mem *pBest;
   93137   UNUSED_PARAMETER(NotUsed);
   93138 
   93139   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
   93140   if( !pBest ) return;
   93141 
   93142   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   93143     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
   93144   }else if( pBest->flags ){
   93145     int max;
   93146     int cmp;
   93147     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   93148     /* This step function is used for both the min() and max() aggregates,
   93149     ** the only difference between the two being that the sense of the
   93150     ** comparison is inverted. For the max() aggregate, the
   93151     ** sqlite3_user_data() function returns (void *)-1. For min() it
   93152     ** returns (void *)db, where db is the sqlite3* database pointer.
   93153     ** Therefore the next statement sets variable 'max' to 1 for the max()
   93154     ** aggregate, or 0 for min().
   93155     */
   93156     max = sqlite3_user_data(context)!=0;
   93157     cmp = sqlite3MemCompare(pBest, pArg, pColl);
   93158     if( (max && cmp<0) || (!max && cmp>0) ){
   93159       sqlite3VdbeMemCopy(pBest, pArg);
   93160     }else{
   93161       sqlite3SkipAccumulatorLoad(context);
   93162     }
   93163   }else{
   93164     sqlite3VdbeMemCopy(pBest, pArg);
   93165   }
   93166 }
   93167 static void minMaxFinalize(sqlite3_context *context){
   93168   sqlite3_value *pRes;
   93169   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
   93170   if( pRes ){
   93171     if( pRes->flags ){
   93172       sqlite3_result_value(context, pRes);
   93173     }
   93174     sqlite3VdbeMemRelease(pRes);
   93175   }
   93176 }
   93177 
   93178 /*
   93179 ** group_concat(EXPR, ?SEPARATOR?)
   93180 */
   93181 static void groupConcatStep(
   93182   sqlite3_context *context,
   93183   int argc,
   93184   sqlite3_value **argv
   93185 ){
   93186   const char *zVal;
   93187   StrAccum *pAccum;
   93188   const char *zSep;
   93189   int nVal, nSep;
   93190   assert( argc==1 || argc==2 );
   93191   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   93192   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
   93193 
   93194   if( pAccum ){
   93195     sqlite3 *db = sqlite3_context_db_handle(context);
   93196     int firstTerm = pAccum->useMalloc==0;
   93197     pAccum->useMalloc = 2;
   93198     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
   93199     if( !firstTerm ){
   93200       if( argc==2 ){
   93201         zSep = (char*)sqlite3_value_text(argv[1]);
   93202         nSep = sqlite3_value_bytes(argv[1]);
   93203       }else{
   93204         zSep = ",";
   93205         nSep = 1;
   93206       }
   93207       if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
   93208     }
   93209     zVal = (char*)sqlite3_value_text(argv[0]);
   93210     nVal = sqlite3_value_bytes(argv[0]);
   93211     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
   93212   }
   93213 }
   93214 static void groupConcatFinalize(sqlite3_context *context){
   93215   StrAccum *pAccum;
   93216   pAccum = sqlite3_aggregate_context(context, 0);
   93217   if( pAccum ){
   93218     if( pAccum->accError==STRACCUM_TOOBIG ){
   93219       sqlite3_result_error_toobig(context);
   93220     }else if( pAccum->accError==STRACCUM_NOMEM ){
   93221       sqlite3_result_error_nomem(context);
   93222     }else{
   93223       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
   93224                           sqlite3_free);
   93225     }
   93226   }
   93227 }
   93228 
   93229 /*
   93230 ** This routine does per-connection function registration.  Most
   93231 ** of the built-in functions above are part of the global function set.
   93232 ** This routine only deals with those that are not global.
   93233 */
   93234 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
   93235   int rc = sqlite3_overload_function(db, "MATCH", 2);
   93236   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   93237   if( rc==SQLITE_NOMEM ){
   93238     db->mallocFailed = 1;
   93239   }
   93240 }
   93241 
   93242 /*
   93243 ** Set the LIKEOPT flag on the 2-argument function with the given name.
   93244 */
   93245 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
   93246   FuncDef *pDef;
   93247   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
   93248                              2, SQLITE_UTF8, 0);
   93249   if( ALWAYS(pDef) ){
   93250     pDef->funcFlags |= flagVal;
   93251   }
   93252 }
   93253 
   93254 /*
   93255 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
   93256 ** parameter determines whether or not the LIKE operator is case
   93257 ** sensitive.  GLOB is always case sensitive.
   93258 */
   93259 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
   93260   struct compareInfo *pInfo;
   93261   if( caseSensitive ){
   93262     pInfo = (struct compareInfo*)&likeInfoAlt;
   93263   }else{
   93264     pInfo = (struct compareInfo*)&likeInfoNorm;
   93265   }
   93266   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   93267   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   93268   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
   93269       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
   93270   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
   93271   setLikeOptFlag(db, "like",
   93272       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
   93273 }
   93274 
   93275 /*
   93276 ** pExpr points to an expression which implements a function.  If
   93277 ** it is appropriate to apply the LIKE optimization to that function
   93278 ** then set aWc[0] through aWc[2] to the wildcard characters and
   93279 ** return TRUE.  If the function is not a LIKE-style function then
   93280 ** return FALSE.
   93281 */
   93282 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
   93283   FuncDef *pDef;
   93284   if( pExpr->op!=TK_FUNCTION
   93285    || !pExpr->x.pList
   93286    || pExpr->x.pList->nExpr!=2
   93287   ){
   93288     return 0;
   93289   }
   93290   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   93291   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
   93292                              sqlite3Strlen30(pExpr->u.zToken),
   93293                              2, SQLITE_UTF8, 0);
   93294   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
   93295     return 0;
   93296   }
   93297 
   93298   /* The memcpy() statement assumes that the wildcard characters are
   93299   ** the first three statements in the compareInfo structure.  The
   93300   ** asserts() that follow verify that assumption
   93301   */
   93302   memcpy(aWc, pDef->pUserData, 3);
   93303   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
   93304   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
   93305   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
   93306   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
   93307   return 1;
   93308 }
   93309 
   93310 /*
   93311 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
   93312 ** to the global function hash table.  This occurs at start-time (as
   93313 ** a consequence of calling sqlite3_initialize()).
   93314 **
   93315 ** After this routine runs
   93316 */
   93317 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
   93318   /*
   93319   ** The following array holds FuncDef structures for all of the functions
   93320   ** defined in this file.
   93321   **
   93322   ** The array cannot be constant since changes are made to the
   93323   ** FuncDef.pHash elements at start-time.  The elements of this array
   93324   ** are read-only after initialization is complete.
   93325   */
   93326   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
   93327     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
   93328     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
   93329     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
   93330     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
   93331     FUNCTION(trim,               1, 3, 0, trimFunc         ),
   93332     FUNCTION(trim,               2, 3, 0, trimFunc         ),
   93333     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
   93334     FUNCTION(min,                0, 0, 1, 0                ),
   93335     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
   93336     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
   93337     FUNCTION(max,                0, 1, 1, 0                ),
   93338     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
   93339     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
   93340     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
   93341     FUNCTION(instr,              2, 0, 0, instrFunc        ),
   93342     FUNCTION(substr,             2, 0, 0, substrFunc       ),
   93343     FUNCTION(substr,             3, 0, 0, substrFunc       ),
   93344     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
   93345     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
   93346     FUNCTION(char,              -1, 0, 0, charFunc         ),
   93347     FUNCTION(abs,                1, 0, 0, absFunc          ),
   93348 #ifndef SQLITE_OMIT_FLOATING_POINT
   93349     FUNCTION(round,              1, 0, 0, roundFunc        ),
   93350     FUNCTION(round,              2, 0, 0, roundFunc        ),
   93351 #endif
   93352     FUNCTION(upper,              1, 0, 0, upperFunc        ),
   93353     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
   93354     FUNCTION(coalesce,           1, 0, 0, 0                ),
   93355     FUNCTION(coalesce,           0, 0, 0, 0                ),
   93356     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
   93357     FUNCTION(hex,                1, 0, 0, hexFunc          ),
   93358     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
   93359     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   93360     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   93361     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   93362     VFUNCTION(random,            0, 0, 0, randomFunc       ),
   93363     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
   93364     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
   93365     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
   93366     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
   93367     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
   93368 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   93369     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
   93370     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
   93371 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   93372     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
   93373     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
   93374     VFUNCTION(changes,           0, 0, 0, changes          ),
   93375     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
   93376     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
   93377     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
   93378   #ifdef SQLITE_SOUNDEX
   93379     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
   93380   #endif
   93381   #ifndef SQLITE_OMIT_LOAD_EXTENSION
   93382     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
   93383     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
   93384   #endif
   93385     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
   93386     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
   93387     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
   93388  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
   93389     {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
   93390     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
   93391     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
   93392     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
   93393 
   93394     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   93395   #ifdef SQLITE_CASE_SENSITIVE_LIKE
   93396     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   93397     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   93398   #else
   93399     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
   93400     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
   93401   #endif
   93402   };
   93403 
   93404   int i;
   93405   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   93406   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
   93407 
   93408   for(i=0; i<ArraySize(aBuiltinFunc); i++){
   93409     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   93410   }
   93411   sqlite3RegisterDateTimeFunctions();
   93412 #ifndef SQLITE_OMIT_ALTERTABLE
   93413   sqlite3AlterFunctions();
   93414 #endif
   93415 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
   93416   sqlite3AnalyzeFunctions();
   93417 #endif
   93418 }
   93419 
   93420 /************** End of func.c ************************************************/
   93421 /************** Begin file fkey.c ********************************************/
   93422 /*
   93423 **
   93424 ** The author disclaims copyright to this source code.  In place of
   93425 ** a legal notice, here is a blessing:
   93426 **
   93427 **    May you do good and not evil.
   93428 **    May you find forgiveness for yourself and forgive others.
   93429 **    May you share freely, never taking more than you give.
   93430 **
   93431 *************************************************************************
   93432 ** This file contains code used by the compiler to add foreign key
   93433 ** support to compiled SQL statements.
   93434 */
   93435 
   93436 #ifndef SQLITE_OMIT_FOREIGN_KEY
   93437 #ifndef SQLITE_OMIT_TRIGGER
   93438 
   93439 /*
   93440 ** Deferred and Immediate FKs
   93441 ** --------------------------
   93442 **
   93443 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
   93444 ** If an immediate foreign key constraint is violated,
   93445 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
   93446 ** statement transaction rolled back. If a
   93447 ** deferred foreign key constraint is violated, no action is taken
   93448 ** immediately. However if the application attempts to commit the
   93449 ** transaction before fixing the constraint violation, the attempt fails.
   93450 **
   93451 ** Deferred constraints are implemented using a simple counter associated
   93452 ** with the database handle. The counter is set to zero each time a
   93453 ** database transaction is opened. Each time a statement is executed
   93454 ** that causes a foreign key violation, the counter is incremented. Each
   93455 ** time a statement is executed that removes an existing violation from
   93456 ** the database, the counter is decremented. When the transaction is
   93457 ** committed, the commit fails if the current value of the counter is
   93458 ** greater than zero. This scheme has two big drawbacks:
   93459 **
   93460 **   * When a commit fails due to a deferred foreign key constraint,
   93461 **     there is no way to tell which foreign constraint is not satisfied,
   93462 **     or which row it is not satisfied for.
   93463 **
   93464 **   * If the database contains foreign key violations when the
   93465 **     transaction is opened, this may cause the mechanism to malfunction.
   93466 **
   93467 ** Despite these problems, this approach is adopted as it seems simpler
   93468 ** than the alternatives.
   93469 **
   93470 ** INSERT operations:
   93471 **
   93472 **   I.1) For each FK for which the table is the child table, search
   93473 **        the parent table for a match. If none is found increment the
   93474 **        constraint counter.
   93475 **
   93476 **   I.2) For each FK for which the table is the parent table,
   93477 **        search the child table for rows that correspond to the new
   93478 **        row in the parent table. Decrement the counter for each row
   93479 **        found (as the constraint is now satisfied).
   93480 **
   93481 ** DELETE operations:
   93482 **
   93483 **   D.1) For each FK for which the table is the child table,
   93484 **        search the parent table for a row that corresponds to the
   93485 **        deleted row in the child table. If such a row is not found,
   93486 **        decrement the counter.
   93487 **
   93488 **   D.2) For each FK for which the table is the parent table, search
   93489 **        the child table for rows that correspond to the deleted row
   93490 **        in the parent table. For each found increment the counter.
   93491 **
   93492 ** UPDATE operations:
   93493 **
   93494 **   An UPDATE command requires that all 4 steps above are taken, but only
   93495 **   for FK constraints for which the affected columns are actually
   93496 **   modified (values must be compared at runtime).
   93497 **
   93498 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
   93499 ** This simplifies the implementation a bit.
   93500 **
   93501 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
   93502 ** resolution is considered to delete rows before the new row is inserted.
   93503 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
   93504 ** is thrown, even if the FK constraint would be satisfied after the new
   93505 ** row is inserted.
   93506 **
   93507 ** Immediate constraints are usually handled similarly. The only difference
   93508 ** is that the counter used is stored as part of each individual statement
   93509 ** object (struct Vdbe). If, after the statement has run, its immediate
   93510 ** constraint counter is greater than zero,
   93511 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
   93512 ** and the statement transaction is rolled back. An exception is an INSERT
   93513 ** statement that inserts a single row only (no triggers). In this case,
   93514 ** instead of using a counter, an exception is thrown immediately if the
   93515 ** INSERT violates a foreign key constraint. This is necessary as such
   93516 ** an INSERT does not open a statement transaction.
   93517 **
   93518 ** TODO: How should dropping a table be handled? How should renaming a
   93519 ** table be handled?
   93520 **
   93521 **
   93522 ** Query API Notes
   93523 ** ---------------
   93524 **
   93525 ** Before coding an UPDATE or DELETE row operation, the code-generator
   93526 ** for those two operations needs to know whether or not the operation
   93527 ** requires any FK processing and, if so, which columns of the original
   93528 ** row are required by the FK processing VDBE code (i.e. if FKs were
   93529 ** implemented using triggers, which of the old.* columns would be
   93530 ** accessed). No information is required by the code-generator before
   93531 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
   93532 ** generation code to query for this information are:
   93533 **
   93534 **   sqlite3FkRequired() - Test to see if FK processing is required.
   93535 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
   93536 **
   93537 **
   93538 ** Externally accessible module functions
   93539 ** --------------------------------------
   93540 **
   93541 **   sqlite3FkCheck()    - Check for foreign key violations.
   93542 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
   93543 **   sqlite3FkDelete()   - Delete an FKey structure.
   93544 */
   93545 
   93546 /*
   93547 ** VDBE Calling Convention
   93548 ** -----------------------
   93549 **
   93550 ** Example:
   93551 **
   93552 **   For the following INSERT statement:
   93553 **
   93554 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
   93555 **     INSERT INTO t1 VALUES(1, 2, 3.1);
   93556 **
   93557 **   Register (x):        2    (type integer)
   93558 **   Register (x+1):      1    (type integer)
   93559 **   Register (x+2):      NULL (type NULL)
   93560 **   Register (x+3):      3.1  (type real)
   93561 */
   93562 
   93563 /*
   93564 ** A foreign key constraint requires that the key columns in the parent
   93565 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
   93566 ** Given that pParent is the parent table for foreign key constraint pFKey,
   93567 ** search the schema for a unique index on the parent key columns.
   93568 **
   93569 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
   93570 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
   93571 ** is set to point to the unique index.
   93572 **
   93573 ** If the parent key consists of a single column (the foreign key constraint
   93574 ** is not a composite foreign key), output variable *paiCol is set to NULL.
   93575 ** Otherwise, it is set to point to an allocated array of size N, where
   93576 ** N is the number of columns in the parent key. The first element of the
   93577 ** array is the index of the child table column that is mapped by the FK
   93578 ** constraint to the parent table column stored in the left-most column
   93579 ** of index *ppIdx. The second element of the array is the index of the
   93580 ** child table column that corresponds to the second left-most column of
   93581 ** *ppIdx, and so on.
   93582 **
   93583 ** If the required index cannot be found, either because:
   93584 **
   93585 **   1) The named parent key columns do not exist, or
   93586 **
   93587 **   2) The named parent key columns do exist, but are not subject to a
   93588 **      UNIQUE or PRIMARY KEY constraint, or
   93589 **
   93590 **   3) No parent key columns were provided explicitly as part of the
   93591 **      foreign key definition, and the parent table does not have a
   93592 **      PRIMARY KEY, or
   93593 **
   93594 **   4) No parent key columns were provided explicitly as part of the
   93595 **      foreign key definition, and the PRIMARY KEY of the parent table
   93596 **      consists of a a different number of columns to the child key in
   93597 **      the child table.
   93598 **
   93599 ** then non-zero is returned, and a "foreign key mismatch" error loaded
   93600 ** into pParse. If an OOM error occurs, non-zero is returned and the
   93601 ** pParse->db->mallocFailed flag is set.
   93602 */
   93603 SQLITE_PRIVATE int sqlite3FkLocateIndex(
   93604   Parse *pParse,                  /* Parse context to store any error in */
   93605   Table *pParent,                 /* Parent table of FK constraint pFKey */
   93606   FKey *pFKey,                    /* Foreign key to find index for */
   93607   Index **ppIdx,                  /* OUT: Unique index on parent table */
   93608   int **paiCol                    /* OUT: Map of index columns in pFKey */
   93609 ){
   93610   Index *pIdx = 0;                    /* Value to return via *ppIdx */
   93611   int *aiCol = 0;                     /* Value to return via *paiCol */
   93612   int nCol = pFKey->nCol;             /* Number of columns in parent key */
   93613   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
   93614 
   93615   /* The caller is responsible for zeroing output parameters. */
   93616   assert( ppIdx && *ppIdx==0 );
   93617   assert( !paiCol || *paiCol==0 );
   93618   assert( pParse );
   93619 
   93620   /* If this is a non-composite (single column) foreign key, check if it
   93621   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
   93622   ** and *paiCol set to zero and return early.
   93623   **
   93624   ** Otherwise, for a composite foreign key (more than one column), allocate
   93625   ** space for the aiCol array (returned via output parameter *paiCol).
   93626   ** Non-composite foreign keys do not require the aiCol array.
   93627   */
   93628   if( nCol==1 ){
   93629     /* The FK maps to the IPK if any of the following are true:
   93630     **
   93631     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
   93632     **      mapped to the primary key of table pParent, or
   93633     **   2) The FK is explicitly mapped to a column declared as INTEGER
   93634     **      PRIMARY KEY.
   93635     */
   93636     if( pParent->iPKey>=0 ){
   93637       if( !zKey ) return 0;
   93638       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
   93639     }
   93640   }else if( paiCol ){
   93641     assert( nCol>1 );
   93642     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
   93643     if( !aiCol ) return 1;
   93644     *paiCol = aiCol;
   93645   }
   93646 
   93647   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
   93648     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
   93649       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
   93650       ** of columns. If each indexed column corresponds to a foreign key
   93651       ** column of pFKey, then this index is a winner.  */
   93652 
   93653       if( zKey==0 ){
   93654         /* If zKey is NULL, then this foreign key is implicitly mapped to
   93655         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
   93656         ** identified by the test.  */
   93657         if( IsPrimaryKeyIndex(pIdx) ){
   93658           if( aiCol ){
   93659             int i;
   93660             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
   93661           }
   93662           break;
   93663         }
   93664       }else{
   93665         /* If zKey is non-NULL, then this foreign key was declared to
   93666         ** map to an explicit list of columns in table pParent. Check if this
   93667         ** index matches those columns. Also, check that the index uses
   93668         ** the default collation sequences for each column. */
   93669         int i, j;
   93670         for(i=0; i<nCol; i++){
   93671           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
   93672           char *zDfltColl;                  /* Def. collation for column */
   93673           char *zIdxCol;                    /* Name of indexed column */
   93674 
   93675           /* If the index uses a collation sequence that is different from
   93676           ** the default collation sequence for the column, this index is
   93677           ** unusable. Bail out early in this case.  */
   93678           zDfltColl = pParent->aCol[iCol].zColl;
   93679           if( !zDfltColl ){
   93680             zDfltColl = "BINARY";
   93681           }
   93682           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
   93683 
   93684           zIdxCol = pParent->aCol[iCol].zName;
   93685           for(j=0; j<nCol; j++){
   93686             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
   93687               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
   93688               break;
   93689             }
   93690           }
   93691           if( j==nCol ) break;
   93692         }
   93693         if( i==nCol ) break;      /* pIdx is usable */
   93694       }
   93695     }
   93696   }
   93697 
   93698   if( !pIdx ){
   93699     if( !pParse->disableTriggers ){
   93700       sqlite3ErrorMsg(pParse,
   93701            "foreign key mismatch - \"%w\" referencing \"%w\"",
   93702            pFKey->pFrom->zName, pFKey->zTo);
   93703     }
   93704     sqlite3DbFree(pParse->db, aiCol);
   93705     return 1;
   93706   }
   93707 
   93708   *ppIdx = pIdx;
   93709   return 0;
   93710 }
   93711 
   93712 /*
   93713 ** This function is called when a row is inserted into or deleted from the
   93714 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
   93715 ** on the child table of pFKey, this function is invoked twice for each row
   93716 ** affected - once to "delete" the old row, and then again to "insert" the
   93717 ** new row.
   93718 **
   93719 ** Each time it is called, this function generates VDBE code to locate the
   93720 ** row in the parent table that corresponds to the row being inserted into
   93721 ** or deleted from the child table. If the parent row can be found, no
   93722 ** special action is taken. Otherwise, if the parent row can *not* be
   93723 ** found in the parent table:
   93724 **
   93725 **   Operation | FK type   | Action taken
   93726 **   --------------------------------------------------------------------------
   93727 **   INSERT      immediate   Increment the "immediate constraint counter".
   93728 **
   93729 **   DELETE      immediate   Decrement the "immediate constraint counter".
   93730 **
   93731 **   INSERT      deferred    Increment the "deferred constraint counter".
   93732 **
   93733 **   DELETE      deferred    Decrement the "deferred constraint counter".
   93734 **
   93735 ** These operations are identified in the comment at the top of this file
   93736 ** (fkey.c) as "I.1" and "D.1".
   93737 */
   93738 static void fkLookupParent(
   93739   Parse *pParse,        /* Parse context */
   93740   int iDb,              /* Index of database housing pTab */
   93741   Table *pTab,          /* Parent table of FK pFKey */
   93742   Index *pIdx,          /* Unique index on parent key columns in pTab */
   93743   FKey *pFKey,          /* Foreign key constraint */
   93744   int *aiCol,           /* Map from parent key columns to child table columns */
   93745   int regData,          /* Address of array containing child table row */
   93746   int nIncr,            /* Increment constraint counter by this */
   93747   int isIgnore          /* If true, pretend pTab contains all NULL values */
   93748 ){
   93749   int i;                                    /* Iterator variable */
   93750   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
   93751   int iCur = pParse->nTab - 1;              /* Cursor number to use */
   93752   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
   93753 
   93754   /* If nIncr is less than zero, then check at runtime if there are any
   93755   ** outstanding constraints to resolve. If there are not, there is no need
   93756   ** to check if deleting this row resolves any outstanding violations.
   93757   **
   93758   ** Check if any of the key columns in the child table row are NULL. If
   93759   ** any are, then the constraint is considered satisfied. No need to
   93760   ** search for a matching row in the parent table.  */
   93761   if( nIncr<0 ){
   93762     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
   93763     VdbeCoverage(v);
   93764   }
   93765   for(i=0; i<pFKey->nCol; i++){
   93766     int iReg = aiCol[i] + regData + 1;
   93767     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
   93768   }
   93769 
   93770   if( isIgnore==0 ){
   93771     if( pIdx==0 ){
   93772       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
   93773       ** column of the parent table (table pTab).  */
   93774       int iMustBeInt;               /* Address of MustBeInt instruction */
   93775       int regTemp = sqlite3GetTempReg(pParse);
   93776 
   93777       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
   93778       ** apply the affinity of the parent key). If this fails, then there
   93779       ** is no matching parent key. Before using MustBeInt, make a copy of
   93780       ** the value. Otherwise, the value inserted into the child key column
   93781       ** will have INTEGER affinity applied to it, which may not be correct.  */
   93782       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
   93783       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
   93784       VdbeCoverage(v);
   93785 
   93786       /* If the parent table is the same as the child table, and we are about
   93787       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   93788       ** then check if the row being inserted matches itself. If so, do not
   93789       ** increment the constraint-counter.  */
   93790       if( pTab==pFKey->pFrom && nIncr==1 ){
   93791         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
   93792         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   93793       }
   93794 
   93795       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   93796       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
   93797       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   93798       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   93799       sqlite3VdbeJumpHere(v, iMustBeInt);
   93800       sqlite3ReleaseTempReg(pParse, regTemp);
   93801     }else{
   93802       int nCol = pFKey->nCol;
   93803       int regTemp = sqlite3GetTempRange(pParse, nCol);
   93804       int regRec = sqlite3GetTempReg(pParse);
   93805 
   93806       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
   93807       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   93808       for(i=0; i<nCol; i++){
   93809         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
   93810       }
   93811 
   93812       /* If the parent table is the same as the child table, and we are about
   93813       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   93814       ** then check if the row being inserted matches itself. If so, do not
   93815       ** increment the constraint-counter.
   93816       **
   93817       ** If any of the parent-key values are NULL, then the row cannot match
   93818       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
   93819       ** of the parent-key values are NULL (at this point it is known that
   93820       ** none of the child key values are).
   93821       */
   93822       if( pTab==pFKey->pFrom && nIncr==1 ){
   93823         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
   93824         for(i=0; i<nCol; i++){
   93825           int iChild = aiCol[i]+1+regData;
   93826           int iParent = pIdx->aiColumn[i]+1+regData;
   93827           assert( aiCol[i]!=pTab->iPKey );
   93828           if( pIdx->aiColumn[i]==pTab->iPKey ){
   93829             /* The parent key is a composite key that includes the IPK column */
   93830             iParent = regData;
   93831           }
   93832           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
   93833           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   93834         }
   93835         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   93836       }
   93837 
   93838       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
   93839                         sqlite3IndexAffinityStr(v,pIdx), nCol);
   93840       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
   93841 
   93842       sqlite3ReleaseTempReg(pParse, regRec);
   93843       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
   93844     }
   93845   }
   93846 
   93847   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
   93848    && !pParse->pToplevel
   93849    && !pParse->isMultiWrite
   93850   ){
   93851     /* Special case: If this is an INSERT statement that will insert exactly
   93852     ** one row into the table, raise a constraint immediately instead of
   93853     ** incrementing a counter. This is necessary as the VM code is being
   93854     ** generated for will not open a statement transaction.  */
   93855     assert( nIncr==1 );
   93856     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
   93857         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
   93858   }else{
   93859     if( nIncr>0 && pFKey->isDeferred==0 ){
   93860       sqlite3ParseToplevel(pParse)->mayAbort = 1;
   93861     }
   93862     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   93863   }
   93864 
   93865   sqlite3VdbeResolveLabel(v, iOk);
   93866   sqlite3VdbeAddOp1(v, OP_Close, iCur);
   93867 }
   93868 
   93869 
   93870 /*
   93871 ** Return an Expr object that refers to a memory register corresponding
   93872 ** to column iCol of table pTab.
   93873 **
   93874 ** regBase is the first of an array of register that contains the data
   93875 ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
   93876 ** column.  regBase+2 holds the second column, and so forth.
   93877 */
   93878 static Expr *exprTableRegister(
   93879   Parse *pParse,     /* Parsing and code generating context */
   93880   Table *pTab,       /* The table whose content is at r[regBase]... */
   93881   int regBase,       /* Contents of table pTab */
   93882   i16 iCol           /* Which column of pTab is desired */
   93883 ){
   93884   Expr *pExpr;
   93885   Column *pCol;
   93886   const char *zColl;
   93887   sqlite3 *db = pParse->db;
   93888 
   93889   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
   93890   if( pExpr ){
   93891     if( iCol>=0 && iCol!=pTab->iPKey ){
   93892       pCol = &pTab->aCol[iCol];
   93893       pExpr->iTable = regBase + iCol + 1;
   93894       pExpr->affinity = pCol->affinity;
   93895       zColl = pCol->zColl;
   93896       if( zColl==0 ) zColl = db->pDfltColl->zName;
   93897       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
   93898     }else{
   93899       pExpr->iTable = regBase;
   93900       pExpr->affinity = SQLITE_AFF_INTEGER;
   93901     }
   93902   }
   93903   return pExpr;
   93904 }
   93905 
   93906 /*
   93907 ** Return an Expr object that refers to column iCol of table pTab which
   93908 ** has cursor iCur.
   93909 */
   93910 static Expr *exprTableColumn(
   93911   sqlite3 *db,      /* The database connection */
   93912   Table *pTab,      /* The table whose column is desired */
   93913   int iCursor,      /* The open cursor on the table */
   93914   i16 iCol          /* The column that is wanted */
   93915 ){
   93916   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
   93917   if( pExpr ){
   93918     pExpr->pTab = pTab;
   93919     pExpr->iTable = iCursor;
   93920     pExpr->iColumn = iCol;
   93921   }
   93922   return pExpr;
   93923 }
   93924 
   93925 /*
   93926 ** This function is called to generate code executed when a row is deleted
   93927 ** from the parent table of foreign key constraint pFKey and, if pFKey is
   93928 ** deferred, when a row is inserted into the same table. When generating
   93929 ** code for an SQL UPDATE operation, this function may be called twice -
   93930 ** once to "delete" the old row and once to "insert" the new row.
   93931 **
   93932 ** The code generated by this function scans through the rows in the child
   93933 ** table that correspond to the parent table row being deleted or inserted.
   93934 ** For each child row found, one of the following actions is taken:
   93935 **
   93936 **   Operation | FK type   | Action taken
   93937 **   --------------------------------------------------------------------------
   93938 **   DELETE      immediate   Increment the "immediate constraint counter".
   93939 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   93940 **                           throw a "FOREIGN KEY constraint failed" exception.
   93941 **
   93942 **   INSERT      immediate   Decrement the "immediate constraint counter".
   93943 **
   93944 **   DELETE      deferred    Increment the "deferred constraint counter".
   93945 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   93946 **                           throw a "FOREIGN KEY constraint failed" exception.
   93947 **
   93948 **   INSERT      deferred    Decrement the "deferred constraint counter".
   93949 **
   93950 ** These operations are identified in the comment at the top of this file
   93951 ** (fkey.c) as "I.2" and "D.2".
   93952 */
   93953 static void fkScanChildren(
   93954   Parse *pParse,                  /* Parse context */
   93955   SrcList *pSrc,                  /* The child table to be scanned */
   93956   Table *pTab,                    /* The parent table */
   93957   Index *pIdx,                    /* Index on parent covering the foreign key */
   93958   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
   93959   int *aiCol,                     /* Map from pIdx cols to child table cols */
   93960   int regData,                    /* Parent row data starts here */
   93961   int nIncr                       /* Amount to increment deferred counter by */
   93962 ){
   93963   sqlite3 *db = pParse->db;       /* Database handle */
   93964   int i;                          /* Iterator variable */
   93965   Expr *pWhere = 0;               /* WHERE clause to scan with */
   93966   NameContext sNameContext;       /* Context used to resolve WHERE clause */
   93967   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
   93968   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
   93969   Vdbe *v = sqlite3GetVdbe(pParse);
   93970 
   93971   assert( pIdx==0 || pIdx->pTable==pTab );
   93972   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
   93973   assert( pIdx!=0 || pFKey->nCol==1 );
   93974   assert( pIdx!=0 || HasRowid(pTab) );
   93975 
   93976   if( nIncr<0 ){
   93977     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
   93978     VdbeCoverage(v);
   93979   }
   93980 
   93981   /* Create an Expr object representing an SQL expression like:
   93982   **
   93983   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
   93984   **
   93985   ** The collation sequence used for the comparison should be that of
   93986   ** the parent key columns. The affinity of the parent key column should
   93987   ** be applied to each child key value before the comparison takes place.
   93988   */
   93989   for(i=0; i<pFKey->nCol; i++){
   93990     Expr *pLeft;                  /* Value from parent table row */
   93991     Expr *pRight;                 /* Column ref to child table */
   93992     Expr *pEq;                    /* Expression (pLeft = pRight) */
   93993     i16 iCol;                     /* Index of column in child table */
   93994     const char *zCol;             /* Name of column in child table */
   93995 
   93996     iCol = pIdx ? pIdx->aiColumn[i] : -1;
   93997     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
   93998     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   93999     assert( iCol>=0 );
   94000     zCol = pFKey->pFrom->aCol[iCol].zName;
   94001     pRight = sqlite3Expr(db, TK_ID, zCol);
   94002     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
   94003     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   94004   }
   94005 
   94006   /* If the child table is the same as the parent table, then add terms
   94007   ** to the WHERE clause that prevent this entry from being scanned.
   94008   ** The added WHERE clause terms are like this:
   94009   **
   94010   **     $current_rowid!=rowid
   94011   **     NOT( $current_a==a AND $current_b==b AND ... )
   94012   **
   94013   ** The first form is used for rowid tables.  The second form is used
   94014   ** for WITHOUT ROWID tables.  In the second form, the primary key is
   94015   ** (a,b,...)
   94016   */
   94017   if( pTab==pFKey->pFrom && nIncr>0 ){
   94018     Expr *pNe;                    /* Expression (pLeft != pRight) */
   94019     Expr *pLeft;                  /* Value from parent table row */
   94020     Expr *pRight;                 /* Column ref to child table */
   94021     if( HasRowid(pTab) ){
   94022       pLeft = exprTableRegister(pParse, pTab, regData, -1);
   94023       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
   94024       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
   94025     }else{
   94026       Expr *pEq, *pAll = 0;
   94027       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   94028       assert( pIdx!=0 );
   94029       for(i=0; i<pPk->nKeyCol; i++){
   94030         i16 iCol = pIdx->aiColumn[i];
   94031         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
   94032         pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
   94033         pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
   94034         pAll = sqlite3ExprAnd(db, pAll, pEq);
   94035       }
   94036       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
   94037     }
   94038     pWhere = sqlite3ExprAnd(db, pWhere, pNe);
   94039   }
   94040 
   94041   /* Resolve the references in the WHERE clause. */
   94042   memset(&sNameContext, 0, sizeof(NameContext));
   94043   sNameContext.pSrcList = pSrc;
   94044   sNameContext.pParse = pParse;
   94045   sqlite3ResolveExprNames(&sNameContext, pWhere);
   94046 
   94047   /* Create VDBE to loop through the entries in pSrc that match the WHERE
   94048   ** clause. If the constraint is not deferred, throw an exception for
   94049   ** each row found. Otherwise, for deferred constraints, increment the
   94050   ** deferred constraint counter by nIncr for each row selected.  */
   94051   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
   94052   if( nIncr>0 && pFKey->isDeferred==0 ){
   94053     sqlite3ParseToplevel(pParse)->mayAbort = 1;
   94054   }
   94055   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   94056   if( pWInfo ){
   94057     sqlite3WhereEnd(pWInfo);
   94058   }
   94059 
   94060   /* Clean up the WHERE clause constructed above. */
   94061   sqlite3ExprDelete(db, pWhere);
   94062   if( iFkIfZero ){
   94063     sqlite3VdbeJumpHere(v, iFkIfZero);
   94064   }
   94065 }
   94066 
   94067 /*
   94068 ** This function returns a linked list of FKey objects (connected by
   94069 ** FKey.pNextTo) holding all children of table pTab.  For example,
   94070 ** given the following schema:
   94071 **
   94072 **   CREATE TABLE t1(a PRIMARY KEY);
   94073 **   CREATE TABLE t2(b REFERENCES t1(a);
   94074 **
   94075 ** Calling this function with table "t1" as an argument returns a pointer
   94076 ** to the FKey structure representing the foreign key constraint on table
   94077 ** "t2". Calling this function with "t2" as the argument would return a
   94078 ** NULL pointer (as there are no FK constraints for which t2 is the parent
   94079 ** table).
   94080 */
   94081 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
   94082   int nName = sqlite3Strlen30(pTab->zName);
   94083   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
   94084 }
   94085 
   94086 /*
   94087 ** The second argument is a Trigger structure allocated by the
   94088 ** fkActionTrigger() routine. This function deletes the Trigger structure
   94089 ** and all of its sub-components.
   94090 **
   94091 ** The Trigger structure or any of its sub-components may be allocated from
   94092 ** the lookaside buffer belonging to database handle dbMem.
   94093 */
   94094 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
   94095   if( p ){
   94096     TriggerStep *pStep = p->step_list;
   94097     sqlite3ExprDelete(dbMem, pStep->pWhere);
   94098     sqlite3ExprListDelete(dbMem, pStep->pExprList);
   94099     sqlite3SelectDelete(dbMem, pStep->pSelect);
   94100     sqlite3ExprDelete(dbMem, p->pWhen);
   94101     sqlite3DbFree(dbMem, p);
   94102   }
   94103 }
   94104 
   94105 /*
   94106 ** This function is called to generate code that runs when table pTab is
   94107 ** being dropped from the database. The SrcList passed as the second argument
   94108 ** to this function contains a single entry guaranteed to resolve to
   94109 ** table pTab.
   94110 **
   94111 ** Normally, no code is required. However, if either
   94112 **
   94113 **   (a) The table is the parent table of a FK constraint, or
   94114 **   (b) The table is the child table of a deferred FK constraint and it is
   94115 **       determined at runtime that there are outstanding deferred FK
   94116 **       constraint violations in the database,
   94117 **
   94118 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
   94119 ** the table from the database. Triggers are disabled while running this
   94120 ** DELETE, but foreign key actions are not.
   94121 */
   94122 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
   94123   sqlite3 *db = pParse->db;
   94124   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
   94125     int iSkip = 0;
   94126     Vdbe *v = sqlite3GetVdbe(pParse);
   94127 
   94128     assert( v );                  /* VDBE has already been allocated */
   94129     if( sqlite3FkReferences(pTab)==0 ){
   94130       /* Search for a deferred foreign key constraint for which this table
   94131       ** is the child table. If one cannot be found, return without
   94132       ** generating any VDBE code. If one can be found, then jump over
   94133       ** the entire DELETE if there are no outstanding deferred constraints
   94134       ** when this statement is run.  */
   94135       FKey *p;
   94136       for(p=pTab->pFKey; p; p=p->pNextFrom){
   94137         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
   94138       }
   94139       if( !p ) return;
   94140       iSkip = sqlite3VdbeMakeLabel(v);
   94141       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
   94142     }
   94143 
   94144     pParse->disableTriggers = 1;
   94145     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
   94146     pParse->disableTriggers = 0;
   94147 
   94148     /* If the DELETE has generated immediate foreign key constraint
   94149     ** violations, halt the VDBE and return an error at this point, before
   94150     ** any modifications to the schema are made. This is because statement
   94151     ** transactions are not able to rollback schema changes.
   94152     **
   94153     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
   94154     ** the statement transaction will not be rolled back even if FK
   94155     ** constraints are violated.
   94156     */
   94157     if( (db->flags & SQLITE_DeferFKs)==0 ){
   94158       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
   94159       VdbeCoverage(v);
   94160       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
   94161           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
   94162     }
   94163 
   94164     if( iSkip ){
   94165       sqlite3VdbeResolveLabel(v, iSkip);
   94166     }
   94167   }
   94168 }
   94169 
   94170 
   94171 /*
   94172 ** The second argument points to an FKey object representing a foreign key
   94173 ** for which pTab is the child table. An UPDATE statement against pTab
   94174 ** is currently being processed. For each column of the table that is
   94175 ** actually updated, the corresponding element in the aChange[] array
   94176 ** is zero or greater (if a column is unmodified the corresponding element
   94177 ** is set to -1). If the rowid column is modified by the UPDATE statement
   94178 ** the bChngRowid argument is non-zero.
   94179 **
   94180 ** This function returns true if any of the columns that are part of the
   94181 ** child key for FK constraint *p are modified.
   94182 */
   94183 static int fkChildIsModified(
   94184   Table *pTab,                    /* Table being updated */
   94185   FKey *p,                        /* Foreign key for which pTab is the child */
   94186   int *aChange,                   /* Array indicating modified columns */
   94187   int bChngRowid                  /* True if rowid is modified by this update */
   94188 ){
   94189   int i;
   94190   for(i=0; i<p->nCol; i++){
   94191     int iChildKey = p->aCol[i].iFrom;
   94192     if( aChange[iChildKey]>=0 ) return 1;
   94193     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
   94194   }
   94195   return 0;
   94196 }
   94197 
   94198 /*
   94199 ** The second argument points to an FKey object representing a foreign key
   94200 ** for which pTab is the parent table. An UPDATE statement against pTab
   94201 ** is currently being processed. For each column of the table that is
   94202 ** actually updated, the corresponding element in the aChange[] array
   94203 ** is zero or greater (if a column is unmodified the corresponding element
   94204 ** is set to -1). If the rowid column is modified by the UPDATE statement
   94205 ** the bChngRowid argument is non-zero.
   94206 **
   94207 ** This function returns true if any of the columns that are part of the
   94208 ** parent key for FK constraint *p are modified.
   94209 */
   94210 static int fkParentIsModified(
   94211   Table *pTab,
   94212   FKey *p,
   94213   int *aChange,
   94214   int bChngRowid
   94215 ){
   94216   int i;
   94217   for(i=0; i<p->nCol; i++){
   94218     char *zKey = p->aCol[i].zCol;
   94219     int iKey;
   94220     for(iKey=0; iKey<pTab->nCol; iKey++){
   94221       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
   94222         Column *pCol = &pTab->aCol[iKey];
   94223         if( zKey ){
   94224           if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
   94225         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
   94226           return 1;
   94227         }
   94228       }
   94229     }
   94230   }
   94231   return 0;
   94232 }
   94233 
   94234 /*
   94235 ** This function is called when inserting, deleting or updating a row of
   94236 ** table pTab to generate VDBE code to perform foreign key constraint
   94237 ** processing for the operation.
   94238 **
   94239 ** For a DELETE operation, parameter regOld is passed the index of the
   94240 ** first register in an array of (pTab->nCol+1) registers containing the
   94241 ** rowid of the row being deleted, followed by each of the column values
   94242 ** of the row being deleted, from left to right. Parameter regNew is passed
   94243 ** zero in this case.
   94244 **
   94245 ** For an INSERT operation, regOld is passed zero and regNew is passed the
   94246 ** first register of an array of (pTab->nCol+1) registers containing the new
   94247 ** row data.
   94248 **
   94249 ** For an UPDATE operation, this function is called twice. Once before
   94250 ** the original record is deleted from the table using the calling convention
   94251 ** described for DELETE. Then again after the original record is deleted
   94252 ** but before the new record is inserted using the INSERT convention.
   94253 */
   94254 SQLITE_PRIVATE void sqlite3FkCheck(
   94255   Parse *pParse,                  /* Parse context */
   94256   Table *pTab,                    /* Row is being deleted from this table */
   94257   int regOld,                     /* Previous row data is stored here */
   94258   int regNew,                     /* New row data is stored here */
   94259   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
   94260   int bChngRowid                  /* True if rowid is UPDATEd */
   94261 ){
   94262   sqlite3 *db = pParse->db;       /* Database handle */
   94263   FKey *pFKey;                    /* Used to iterate through FKs */
   94264   int iDb;                        /* Index of database containing pTab */
   94265   const char *zDb;                /* Name of database containing pTab */
   94266   int isIgnoreErrors = pParse->disableTriggers;
   94267 
   94268   /* Exactly one of regOld and regNew should be non-zero. */
   94269   assert( (regOld==0)!=(regNew==0) );
   94270 
   94271   /* If foreign-keys are disabled, this function is a no-op. */
   94272   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
   94273 
   94274   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   94275   zDb = db->aDb[iDb].zName;
   94276 
   94277   /* Loop through all the foreign key constraints for which pTab is the
   94278   ** child table (the table that the foreign key definition is part of).  */
   94279   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   94280     Table *pTo;                   /* Parent table of foreign key pFKey */
   94281     Index *pIdx = 0;              /* Index on key columns in pTo */
   94282     int *aiFree = 0;
   94283     int *aiCol;
   94284     int iCol;
   94285     int i;
   94286     int isIgnore = 0;
   94287 
   94288     if( aChange
   94289      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
   94290      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
   94291     ){
   94292       continue;
   94293     }
   94294 
   94295     /* Find the parent table of this foreign key. Also find a unique index
   94296     ** on the parent key columns in the parent table. If either of these
   94297     ** schema items cannot be located, set an error in pParse and return
   94298     ** early.  */
   94299     if( pParse->disableTriggers ){
   94300       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
   94301     }else{
   94302       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
   94303     }
   94304     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
   94305       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
   94306       if( !isIgnoreErrors || db->mallocFailed ) return;
   94307       if( pTo==0 ){
   94308         /* If isIgnoreErrors is true, then a table is being dropped. In this
   94309         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
   94310         ** before actually dropping it in order to check FK constraints.
   94311         ** If the parent table of an FK constraint on the current table is
   94312         ** missing, behave as if it is empty. i.e. decrement the relevant
   94313         ** FK counter for each row of the current table with non-NULL keys.
   94314         */
   94315         Vdbe *v = sqlite3GetVdbe(pParse);
   94316         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
   94317         for(i=0; i<pFKey->nCol; i++){
   94318           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
   94319           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
   94320         }
   94321         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
   94322       }
   94323       continue;
   94324     }
   94325     assert( pFKey->nCol==1 || (aiFree && pIdx) );
   94326 
   94327     if( aiFree ){
   94328       aiCol = aiFree;
   94329     }else{
   94330       iCol = pFKey->aCol[0].iFrom;
   94331       aiCol = &iCol;
   94332     }
   94333     for(i=0; i<pFKey->nCol; i++){
   94334       if( aiCol[i]==pTab->iPKey ){
   94335         aiCol[i] = -1;
   94336       }
   94337 #ifndef SQLITE_OMIT_AUTHORIZATION
   94338       /* Request permission to read the parent key columns. If the
   94339       ** authorization callback returns SQLITE_IGNORE, behave as if any
   94340       ** values read from the parent table are NULL. */
   94341       if( db->xAuth ){
   94342         int rcauth;
   94343         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
   94344         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
   94345         isIgnore = (rcauth==SQLITE_IGNORE);
   94346       }
   94347 #endif
   94348     }
   94349 
   94350     /* Take a shared-cache advisory read-lock on the parent table. Allocate
   94351     ** a cursor to use to search the unique index on the parent key columns
   94352     ** in the parent table.  */
   94353     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
   94354     pParse->nTab++;
   94355 
   94356     if( regOld!=0 ){
   94357       /* A row is being removed from the child table. Search for the parent.
   94358       ** If the parent does not exist, removing the child row resolves an
   94359       ** outstanding foreign key constraint violation. */
   94360       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
   94361     }
   94362     if( regNew!=0 ){
   94363       /* A row is being added to the child table. If a parent row cannot
   94364       ** be found, adding the child row has violated the FK constraint. */
   94365       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
   94366     }
   94367 
   94368     sqlite3DbFree(db, aiFree);
   94369   }
   94370 
   94371   /* Loop through all the foreign key constraints that refer to this table.
   94372   ** (the "child" constraints) */
   94373   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   94374     Index *pIdx = 0;              /* Foreign key index for pFKey */
   94375     SrcList *pSrc;
   94376     int *aiCol = 0;
   94377 
   94378     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
   94379       continue;
   94380     }
   94381 
   94382     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
   94383      && !pParse->pToplevel && !pParse->isMultiWrite
   94384     ){
   94385       assert( regOld==0 && regNew!=0 );
   94386       /* Inserting a single row into a parent table cannot cause an immediate
   94387       ** foreign key violation. So do nothing in this case.  */
   94388       continue;
   94389     }
   94390 
   94391     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
   94392       if( !isIgnoreErrors || db->mallocFailed ) return;
   94393       continue;
   94394     }
   94395     assert( aiCol || pFKey->nCol==1 );
   94396 
   94397     /* Create a SrcList structure containing the child table.  We need the
   94398     ** child table as a SrcList for sqlite3WhereBegin() */
   94399     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   94400     if( pSrc ){
   94401       struct SrcList_item *pItem = pSrc->a;
   94402       pItem->pTab = pFKey->pFrom;
   94403       pItem->zName = pFKey->pFrom->zName;
   94404       pItem->pTab->nRef++;
   94405       pItem->iCursor = pParse->nTab++;
   94406 
   94407       if( regNew!=0 ){
   94408         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
   94409       }
   94410       if( regOld!=0 ){
   94411         /* If there is a RESTRICT action configured for the current operation
   94412         ** on the parent table of this FK, then throw an exception
   94413         ** immediately if the FK constraint is violated, even if this is a
   94414         ** deferred trigger. That's what RESTRICT means. To defer checking
   94415         ** the constraint, the FK should specify NO ACTION (represented
   94416         ** using OE_None). NO ACTION is the default.  */
   94417         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
   94418       }
   94419       pItem->zName = 0;
   94420       sqlite3SrcListDelete(db, pSrc);
   94421     }
   94422     sqlite3DbFree(db, aiCol);
   94423   }
   94424 }
   94425 
   94426 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
   94427 
   94428 /*
   94429 ** This function is called before generating code to update or delete a
   94430 ** row contained in table pTab.
   94431 */
   94432 SQLITE_PRIVATE u32 sqlite3FkOldmask(
   94433   Parse *pParse,                  /* Parse context */
   94434   Table *pTab                     /* Table being modified */
   94435 ){
   94436   u32 mask = 0;
   94437   if( pParse->db->flags&SQLITE_ForeignKeys ){
   94438     FKey *p;
   94439     int i;
   94440     for(p=pTab->pFKey; p; p=p->pNextFrom){
   94441       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
   94442     }
   94443     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   94444       Index *pIdx = 0;
   94445       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
   94446       if( pIdx ){
   94447         for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
   94448       }
   94449     }
   94450   }
   94451   return mask;
   94452 }
   94453 
   94454 
   94455 /*
   94456 ** This function is called before generating code to update or delete a
   94457 ** row contained in table pTab. If the operation is a DELETE, then
   94458 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
   94459 ** to an array of size N, where N is the number of columns in table pTab.
   94460 ** If the i'th column is not modified by the UPDATE, then the corresponding
   94461 ** entry in the aChange[] array is set to -1. If the column is modified,
   94462 ** the value is 0 or greater. Parameter chngRowid is set to true if the
   94463 ** UPDATE statement modifies the rowid fields of the table.
   94464 **
   94465 ** If any foreign key processing will be required, this function returns
   94466 ** true. If there is no foreign key related processing, this function
   94467 ** returns false.
   94468 */
   94469 SQLITE_PRIVATE int sqlite3FkRequired(
   94470   Parse *pParse,                  /* Parse context */
   94471   Table *pTab,                    /* Table being modified */
   94472   int *aChange,                   /* Non-NULL for UPDATE operations */
   94473   int chngRowid                   /* True for UPDATE that affects rowid */
   94474 ){
   94475   if( pParse->db->flags&SQLITE_ForeignKeys ){
   94476     if( !aChange ){
   94477       /* A DELETE operation. Foreign key processing is required if the
   94478       ** table in question is either the child or parent table for any
   94479       ** foreign key constraint.  */
   94480       return (sqlite3FkReferences(pTab) || pTab->pFKey);
   94481     }else{
   94482       /* This is an UPDATE. Foreign key processing is only required if the
   94483       ** operation modifies one or more child or parent key columns. */
   94484       FKey *p;
   94485 
   94486       /* Check if any child key columns are being modified. */
   94487       for(p=pTab->pFKey; p; p=p->pNextFrom){
   94488         if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
   94489       }
   94490 
   94491       /* Check if any parent key columns are being modified. */
   94492       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   94493         if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
   94494       }
   94495     }
   94496   }
   94497   return 0;
   94498 }
   94499 
   94500 /*
   94501 ** This function is called when an UPDATE or DELETE operation is being
   94502 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
   94503 ** If the current operation is an UPDATE, then the pChanges parameter is
   94504 ** passed a pointer to the list of columns being modified. If it is a
   94505 ** DELETE, pChanges is passed a NULL pointer.
   94506 **
   94507 ** It returns a pointer to a Trigger structure containing a trigger
   94508 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
   94509 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
   94510 ** returned (these actions require no special handling by the triggers
   94511 ** sub-system, code for them is created by fkScanChildren()).
   94512 **
   94513 ** For example, if pFKey is the foreign key and pTab is table "p" in
   94514 ** the following schema:
   94515 **
   94516 **   CREATE TABLE p(pk PRIMARY KEY);
   94517 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
   94518 **
   94519 ** then the returned trigger structure is equivalent to:
   94520 **
   94521 **   CREATE TRIGGER ... DELETE ON p BEGIN
   94522 **     DELETE FROM c WHERE ck = old.pk;
   94523 **   END;
   94524 **
   94525 ** The returned pointer is cached as part of the foreign key object. It
   94526 ** is eventually freed along with the rest of the foreign key object by
   94527 ** sqlite3FkDelete().
   94528 */
   94529 static Trigger *fkActionTrigger(
   94530   Parse *pParse,                  /* Parse context */
   94531   Table *pTab,                    /* Table being updated or deleted from */
   94532   FKey *pFKey,                    /* Foreign key to get action for */
   94533   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
   94534 ){
   94535   sqlite3 *db = pParse->db;       /* Database handle */
   94536   int action;                     /* One of OE_None, OE_Cascade etc. */
   94537   Trigger *pTrigger;              /* Trigger definition to return */
   94538   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
   94539 
   94540   action = pFKey->aAction[iAction];
   94541   pTrigger = pFKey->apTrigger[iAction];
   94542 
   94543   if( action!=OE_None && !pTrigger ){
   94544     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
   94545     char const *zFrom;            /* Name of child table */
   94546     int nFrom;                    /* Length in bytes of zFrom */
   94547     Index *pIdx = 0;              /* Parent key index for this FK */
   94548     int *aiCol = 0;               /* child table cols -> parent key cols */
   94549     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
   94550     Expr *pWhere = 0;             /* WHERE clause of trigger step */
   94551     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
   94552     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
   94553     int i;                        /* Iterator variable */
   94554     Expr *pWhen = 0;              /* WHEN clause for the trigger */
   94555 
   94556     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
   94557     assert( aiCol || pFKey->nCol==1 );
   94558 
   94559     for(i=0; i<pFKey->nCol; i++){
   94560       Token tOld = { "old", 3 };  /* Literal "old" token */
   94561       Token tNew = { "new", 3 };  /* Literal "new" token */
   94562       Token tFromCol;             /* Name of column in child table */
   94563       Token tToCol;               /* Name of column in parent table */
   94564       int iFromCol;               /* Idx of column in child table */
   94565       Expr *pEq;                  /* tFromCol = OLD.tToCol */
   94566 
   94567       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   94568       assert( iFromCol>=0 );
   94569       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
   94570       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
   94571 
   94572       tToCol.n = sqlite3Strlen30(tToCol.z);
   94573       tFromCol.n = sqlite3Strlen30(tFromCol.z);
   94574 
   94575       /* Create the expression "OLD.zToCol = zFromCol". It is important
   94576       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
   94577       ** that the affinity and collation sequence associated with the
   94578       ** parent table are used for the comparison. */
   94579       pEq = sqlite3PExpr(pParse, TK_EQ,
   94580           sqlite3PExpr(pParse, TK_DOT,
   94581             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   94582             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   94583           , 0),
   94584           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
   94585       , 0);
   94586       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   94587 
   94588       /* For ON UPDATE, construct the next term of the WHEN clause.
   94589       ** The final WHEN clause will be like this:
   94590       **
   94591       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
   94592       */
   94593       if( pChanges ){
   94594         pEq = sqlite3PExpr(pParse, TK_IS,
   94595             sqlite3PExpr(pParse, TK_DOT,
   94596               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   94597               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   94598               0),
   94599             sqlite3PExpr(pParse, TK_DOT,
   94600               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   94601               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   94602               0),
   94603             0);
   94604         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
   94605       }
   94606 
   94607       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
   94608         Expr *pNew;
   94609         if( action==OE_Cascade ){
   94610           pNew = sqlite3PExpr(pParse, TK_DOT,
   94611             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   94612             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   94613           , 0);
   94614         }else if( action==OE_SetDflt ){
   94615           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
   94616           if( pDflt ){
   94617             pNew = sqlite3ExprDup(db, pDflt, 0);
   94618           }else{
   94619             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   94620           }
   94621         }else{
   94622           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   94623         }
   94624         pList = sqlite3ExprListAppend(pParse, pList, pNew);
   94625         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
   94626       }
   94627     }
   94628     sqlite3DbFree(db, aiCol);
   94629 
   94630     zFrom = pFKey->pFrom->zName;
   94631     nFrom = sqlite3Strlen30(zFrom);
   94632 
   94633     if( action==OE_Restrict ){
   94634       Token tFrom;
   94635       Expr *pRaise;
   94636 
   94637       tFrom.z = zFrom;
   94638       tFrom.n = nFrom;
   94639       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
   94640       if( pRaise ){
   94641         pRaise->affinity = OE_Abort;
   94642       }
   94643       pSelect = sqlite3SelectNew(pParse,
   94644           sqlite3ExprListAppend(pParse, 0, pRaise),
   94645           sqlite3SrcListAppend(db, 0, &tFrom, 0),
   94646           pWhere,
   94647           0, 0, 0, 0, 0, 0
   94648       );
   94649       pWhere = 0;
   94650     }
   94651 
   94652     /* Disable lookaside memory allocation */
   94653     enableLookaside = db->lookaside.bEnabled;
   94654     db->lookaside.bEnabled = 0;
   94655 
   94656     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
   94657         sizeof(Trigger) +         /* struct Trigger */
   94658         sizeof(TriggerStep) +     /* Single step in trigger program */
   94659         nFrom + 1                 /* Space for pStep->target.z */
   94660     );
   94661     if( pTrigger ){
   94662       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
   94663       pStep->target.z = (char *)&pStep[1];
   94664       pStep->target.n = nFrom;
   94665       memcpy((char *)pStep->target.z, zFrom, nFrom);
   94666 
   94667       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   94668       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
   94669       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   94670       if( pWhen ){
   94671         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
   94672         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   94673       }
   94674     }
   94675 
   94676     /* Re-enable the lookaside buffer, if it was disabled earlier. */
   94677     db->lookaside.bEnabled = enableLookaside;
   94678 
   94679     sqlite3ExprDelete(db, pWhere);
   94680     sqlite3ExprDelete(db, pWhen);
   94681     sqlite3ExprListDelete(db, pList);
   94682     sqlite3SelectDelete(db, pSelect);
   94683     if( db->mallocFailed==1 ){
   94684       fkTriggerDelete(db, pTrigger);
   94685       return 0;
   94686     }
   94687     assert( pStep!=0 );
   94688 
   94689     switch( action ){
   94690       case OE_Restrict:
   94691         pStep->op = TK_SELECT;
   94692         break;
   94693       case OE_Cascade:
   94694         if( !pChanges ){
   94695           pStep->op = TK_DELETE;
   94696           break;
   94697         }
   94698       default:
   94699         pStep->op = TK_UPDATE;
   94700     }
   94701     pStep->pTrig = pTrigger;
   94702     pTrigger->pSchema = pTab->pSchema;
   94703     pTrigger->pTabSchema = pTab->pSchema;
   94704     pFKey->apTrigger[iAction] = pTrigger;
   94705     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
   94706   }
   94707 
   94708   return pTrigger;
   94709 }
   94710 
   94711 /*
   94712 ** This function is called when deleting or updating a row to implement
   94713 ** any required CASCADE, SET NULL or SET DEFAULT actions.
   94714 */
   94715 SQLITE_PRIVATE void sqlite3FkActions(
   94716   Parse *pParse,                  /* Parse context */
   94717   Table *pTab,                    /* Table being updated or deleted from */
   94718   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
   94719   int regOld,                     /* Address of array containing old row */
   94720   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
   94721   int bChngRowid                  /* True if rowid is UPDATEd */
   94722 ){
   94723   /* If foreign-key support is enabled, iterate through all FKs that
   94724   ** refer to table pTab. If there is an action associated with the FK
   94725   ** for this operation (either update or delete), invoke the associated
   94726   ** trigger sub-program.  */
   94727   if( pParse->db->flags&SQLITE_ForeignKeys ){
   94728     FKey *pFKey;                  /* Iterator variable */
   94729     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   94730       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
   94731         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
   94732         if( pAct ){
   94733           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
   94734         }
   94735       }
   94736     }
   94737   }
   94738 }
   94739 
   94740 #endif /* ifndef SQLITE_OMIT_TRIGGER */
   94741 
   94742 /*
   94743 ** Free all memory associated with foreign key definitions attached to
   94744 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
   94745 ** hash table.
   94746 */
   94747 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
   94748   FKey *pFKey;                    /* Iterator variable */
   94749   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
   94750 
   94751   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
   94752   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
   94753 
   94754     /* Remove the FK from the fkeyHash hash table. */
   94755     if( !db || db->pnBytesFreed==0 ){
   94756       if( pFKey->pPrevTo ){
   94757         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
   94758       }else{
   94759         void *p = (void *)pFKey->pNextTo;
   94760         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
   94761         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
   94762       }
   94763       if( pFKey->pNextTo ){
   94764         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
   94765       }
   94766     }
   94767 
   94768     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
   94769     ** classified as either immediate or deferred.
   94770     */
   94771     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
   94772 
   94773     /* Delete any triggers created to implement actions for this FK. */
   94774 #ifndef SQLITE_OMIT_TRIGGER
   94775     fkTriggerDelete(db, pFKey->apTrigger[0]);
   94776     fkTriggerDelete(db, pFKey->apTrigger[1]);
   94777 #endif
   94778 
   94779     pNext = pFKey->pNextFrom;
   94780     sqlite3DbFree(db, pFKey);
   94781   }
   94782 }
   94783 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
   94784 
   94785 /************** End of fkey.c ************************************************/
   94786 /************** Begin file insert.c ******************************************/
   94787 /*
   94788 ** 2001 September 15
   94789 **
   94790 ** The author disclaims copyright to this source code.  In place of
   94791 ** a legal notice, here is a blessing:
   94792 **
   94793 **    May you do good and not evil.
   94794 **    May you find forgiveness for yourself and forgive others.
   94795 **    May you share freely, never taking more than you give.
   94796 **
   94797 *************************************************************************
   94798 ** This file contains C code routines that are called by the parser
   94799 ** to handle INSERT statements in SQLite.
   94800 */
   94801 
   94802 /*
   94803 ** Generate code that will
   94804 **
   94805 **   (1) acquire a lock for table pTab then
   94806 **   (2) open pTab as cursor iCur.
   94807 **
   94808 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
   94809 ** for that table that is actually opened.
   94810 */
   94811 SQLITE_PRIVATE void sqlite3OpenTable(
   94812   Parse *pParse,  /* Generate code into this VDBE */
   94813   int iCur,       /* The cursor number of the table */
   94814   int iDb,        /* The database index in sqlite3.aDb[] */
   94815   Table *pTab,    /* The table to be opened */
   94816   int opcode      /* OP_OpenRead or OP_OpenWrite */
   94817 ){
   94818   Vdbe *v;
   94819   assert( !IsVirtual(pTab) );
   94820   v = sqlite3GetVdbe(pParse);
   94821   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
   94822   sqlite3TableLock(pParse, iDb, pTab->tnum,
   94823                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
   94824   if( HasRowid(pTab) ){
   94825     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
   94826     VdbeComment((v, "%s", pTab->zName));
   94827   }else{
   94828     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   94829     assert( pPk!=0 );
   94830     assert( pPk->tnum=pTab->tnum );
   94831     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
   94832     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   94833     VdbeComment((v, "%s", pTab->zName));
   94834   }
   94835 }
   94836 
   94837 /*
   94838 ** Return a pointer to the column affinity string associated with index
   94839 ** pIdx. A column affinity string has one character for each column in
   94840 ** the table, according to the affinity of the column:
   94841 **
   94842 **  Character      Column affinity
   94843 **  ------------------------------
   94844 **  'a'            TEXT
   94845 **  'b'            NONE
   94846 **  'c'            NUMERIC
   94847 **  'd'            INTEGER
   94848 **  'e'            REAL
   94849 **
   94850 ** An extra 'd' is appended to the end of the string to cover the
   94851 ** rowid that appears as the last column in every index.
   94852 **
   94853 ** Memory for the buffer containing the column index affinity string
   94854 ** is managed along with the rest of the Index structure. It will be
   94855 ** released when sqlite3DeleteIndex() is called.
   94856 */
   94857 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
   94858   if( !pIdx->zColAff ){
   94859     /* The first time a column affinity string for a particular index is
   94860     ** required, it is allocated and populated here. It is then stored as
   94861     ** a member of the Index structure for subsequent use.
   94862     **
   94863     ** The column affinity string will eventually be deleted by
   94864     ** sqliteDeleteIndex() when the Index structure itself is cleaned
   94865     ** up.
   94866     */
   94867     int n;
   94868     Table *pTab = pIdx->pTable;
   94869     sqlite3 *db = sqlite3VdbeDb(v);
   94870     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
   94871     if( !pIdx->zColAff ){
   94872       db->mallocFailed = 1;
   94873       return 0;
   94874     }
   94875     for(n=0; n<pIdx->nColumn; n++){
   94876       i16 x = pIdx->aiColumn[n];
   94877       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
   94878     }
   94879     pIdx->zColAff[n] = 0;
   94880   }
   94881 
   94882   return pIdx->zColAff;
   94883 }
   94884 
   94885 /*
   94886 ** Compute the affinity string for table pTab, if it has not already been
   94887 ** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
   94888 **
   94889 ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
   94890 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
   94891 ** for register iReg and following.  Or if affinities exists and iReg==0,
   94892 ** then just set the P4 operand of the previous opcode (which should  be
   94893 ** an OP_MakeRecord) to the affinity string.
   94894 **
   94895 ** A column affinity string has one character per column:
   94896 **
   94897 **  Character      Column affinity
   94898 **  ------------------------------
   94899 **  'a'            TEXT
   94900 **  'b'            NONE
   94901 **  'c'            NUMERIC
   94902 **  'd'            INTEGER
   94903 **  'e'            REAL
   94904 */
   94905 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
   94906   int i;
   94907   char *zColAff = pTab->zColAff;
   94908   if( zColAff==0 ){
   94909     sqlite3 *db = sqlite3VdbeDb(v);
   94910     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   94911     if( !zColAff ){
   94912       db->mallocFailed = 1;
   94913       return;
   94914     }
   94915 
   94916     for(i=0; i<pTab->nCol; i++){
   94917       zColAff[i] = pTab->aCol[i].affinity;
   94918     }
   94919     do{
   94920       zColAff[i--] = 0;
   94921     }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
   94922     pTab->zColAff = zColAff;
   94923   }
   94924   i = sqlite3Strlen30(zColAff);
   94925   if( i ){
   94926     if( iReg ){
   94927       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
   94928     }else{
   94929       sqlite3VdbeChangeP4(v, -1, zColAff, i);
   94930     }
   94931   }
   94932 }
   94933 
   94934 /*
   94935 ** Return non-zero if the table pTab in database iDb or any of its indices
   94936 ** have been opened at any point in the VDBE program. This is used to see if
   94937 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
   94938 ** run without using a temporary table for the results of the SELECT.
   94939 */
   94940 static int readsTable(Parse *p, int iDb, Table *pTab){
   94941   Vdbe *v = sqlite3GetVdbe(p);
   94942   int i;
   94943   int iEnd = sqlite3VdbeCurrentAddr(v);
   94944 #ifndef SQLITE_OMIT_VIRTUALTABLE
   94945   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   94946 #endif
   94947 
   94948   for(i=1; i<iEnd; i++){
   94949     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   94950     assert( pOp!=0 );
   94951     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   94952       Index *pIndex;
   94953       int tnum = pOp->p2;
   94954       if( tnum==pTab->tnum ){
   94955         return 1;
   94956       }
   94957       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   94958         if( tnum==pIndex->tnum ){
   94959           return 1;
   94960         }
   94961       }
   94962     }
   94963 #ifndef SQLITE_OMIT_VIRTUALTABLE
   94964     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
   94965       assert( pOp->p4.pVtab!=0 );
   94966       assert( pOp->p4type==P4_VTAB );
   94967       return 1;
   94968     }
   94969 #endif
   94970   }
   94971   return 0;
   94972 }
   94973 
   94974 #ifndef SQLITE_OMIT_AUTOINCREMENT
   94975 /*
   94976 ** Locate or create an AutoincInfo structure associated with table pTab
   94977 ** which is in database iDb.  Return the register number for the register
   94978 ** that holds the maximum rowid.
   94979 **
   94980 ** There is at most one AutoincInfo structure per table even if the
   94981 ** same table is autoincremented multiple times due to inserts within
   94982 ** triggers.  A new AutoincInfo structure is created if this is the
   94983 ** first use of table pTab.  On 2nd and subsequent uses, the original
   94984 ** AutoincInfo structure is used.
   94985 **
   94986 ** Three memory locations are allocated:
   94987 **
   94988 **   (1)  Register to hold the name of the pTab table.
   94989 **   (2)  Register to hold the maximum ROWID of pTab.
   94990 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
   94991 **
   94992 ** The 2nd register is the one that is returned.  That is all the
   94993 ** insert routine needs to know about.
   94994 */
   94995 static int autoIncBegin(
   94996   Parse *pParse,      /* Parsing context */
   94997   int iDb,            /* Index of the database holding pTab */
   94998   Table *pTab         /* The table we are writing to */
   94999 ){
   95000   int memId = 0;      /* Register holding maximum rowid */
   95001   if( pTab->tabFlags & TF_Autoincrement ){
   95002     Parse *pToplevel = sqlite3ParseToplevel(pParse);
   95003     AutoincInfo *pInfo;
   95004 
   95005     pInfo = pToplevel->pAinc;
   95006     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   95007     if( pInfo==0 ){
   95008       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
   95009       if( pInfo==0 ) return 0;
   95010       pInfo->pNext = pToplevel->pAinc;
   95011       pToplevel->pAinc = pInfo;
   95012       pInfo->pTab = pTab;
   95013       pInfo->iDb = iDb;
   95014       pToplevel->nMem++;                  /* Register to hold name of table */
   95015       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
   95016       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   95017     }
   95018     memId = pInfo->regCtr;
   95019   }
   95020   return memId;
   95021 }
   95022 
   95023 /*
   95024 ** This routine generates code that will initialize all of the
   95025 ** register used by the autoincrement tracker.
   95026 */
   95027 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
   95028   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   95029   sqlite3 *db = pParse->db;  /* The database connection */
   95030   Db *pDb;                   /* Database only autoinc table */
   95031   int memId;                 /* Register holding max rowid */
   95032   int addr;                  /* A VDBE address */
   95033   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
   95034 
   95035   /* This routine is never called during trigger-generation.  It is
   95036   ** only called from the top-level */
   95037   assert( pParse->pTriggerTab==0 );
   95038   assert( pParse==sqlite3ParseToplevel(pParse) );
   95039 
   95040   assert( v );   /* We failed long ago if this is not so */
   95041   for(p = pParse->pAinc; p; p = p->pNext){
   95042     pDb = &db->aDb[p->iDb];
   95043     memId = p->regCtr;
   95044     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   95045     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   95046     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
   95047     addr = sqlite3VdbeCurrentAddr(v);
   95048     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
   95049     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
   95050     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
   95051     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
   95052     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   95053     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   95054     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
   95055     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
   95056     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
   95057     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
   95058     sqlite3VdbeAddOp0(v, OP_Close);
   95059   }
   95060 }
   95061 
   95062 /*
   95063 ** Update the maximum rowid for an autoincrement calculation.
   95064 **
   95065 ** This routine should be called when the top of the stack holds a
   95066 ** new rowid that is about to be inserted.  If that new rowid is
   95067 ** larger than the maximum rowid in the memId memory cell, then the
   95068 ** memory cell is updated.  The stack is unchanged.
   95069 */
   95070 static void autoIncStep(Parse *pParse, int memId, int regRowid){
   95071   if( memId>0 ){
   95072     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
   95073   }
   95074 }
   95075 
   95076 /*
   95077 ** This routine generates the code needed to write autoincrement
   95078 ** maximum rowid values back into the sqlite_sequence register.
   95079 ** Every statement that might do an INSERT into an autoincrement
   95080 ** table (either directly or through triggers) needs to call this
   95081 ** routine just before the "exit" code.
   95082 */
   95083 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
   95084   AutoincInfo *p;
   95085   Vdbe *v = pParse->pVdbe;
   95086   sqlite3 *db = pParse->db;
   95087 
   95088   assert( v );
   95089   for(p = pParse->pAinc; p; p = p->pNext){
   95090     Db *pDb = &db->aDb[p->iDb];
   95091     int j1;
   95092     int iRec;
   95093     int memId = p->regCtr;
   95094 
   95095     iRec = sqlite3GetTempReg(pParse);
   95096     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   95097     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   95098     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
   95099     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
   95100     sqlite3VdbeJumpHere(v, j1);
   95101     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
   95102     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
   95103     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   95104     sqlite3VdbeAddOp0(v, OP_Close);
   95105     sqlite3ReleaseTempReg(pParse, iRec);
   95106   }
   95107 }
   95108 #else
   95109 /*
   95110 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   95111 ** above are all no-ops
   95112 */
   95113 # define autoIncBegin(A,B,C) (0)
   95114 # define autoIncStep(A,B,C)
   95115 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   95116 
   95117 
   95118 /* Forward declaration */
   95119 static int xferOptimization(
   95120   Parse *pParse,        /* Parser context */
   95121   Table *pDest,         /* The table we are inserting into */
   95122   Select *pSelect,      /* A SELECT statement to use as the data source */
   95123   int onError,          /* How to handle constraint errors */
   95124   int iDbDest           /* The database of pDest */
   95125 );
   95126 
   95127 /*
   95128 ** This routine is called to handle SQL of the following forms:
   95129 **
   95130 **    insert into TABLE (IDLIST) values(EXPRLIST)
   95131 **    insert into TABLE (IDLIST) select
   95132 **
   95133 ** The IDLIST following the table name is always optional.  If omitted,
   95134 ** then a list of all columns for the table is substituted.  The IDLIST
   95135 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
   95136 **
   95137 ** The pList parameter holds EXPRLIST in the first form of the INSERT
   95138 ** statement above, and pSelect is NULL.  For the second form, pList is
   95139 ** NULL and pSelect is a pointer to the select statement used to generate
   95140 ** data for the insert.
   95141 **
   95142 ** The code generated follows one of four templates.  For a simple
   95143 ** insert with data coming from a VALUES clause, the code executes
   95144 ** once straight down through.  Pseudo-code follows (we call this
   95145 ** the "1st template"):
   95146 **
   95147 **         open write cursor to <table> and its indices
   95148 **         put VALUES clause expressions into registers
   95149 **         write the resulting record into <table>
   95150 **         cleanup
   95151 **
   95152 ** The three remaining templates assume the statement is of the form
   95153 **
   95154 **   INSERT INTO <table> SELECT ...
   95155 **
   95156 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   95157 ** in other words if the SELECT pulls all columns from a single table
   95158 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   95159 ** if <table2> and <table1> are distinct tables but have identical
   95160 ** schemas, including all the same indices, then a special optimization
   95161 ** is invoked that copies raw records from <table2> over to <table1>.
   95162 ** See the xferOptimization() function for the implementation of this
   95163 ** template.  This is the 2nd template.
   95164 **
   95165 **         open a write cursor to <table>
   95166 **         open read cursor on <table2>
   95167 **         transfer all records in <table2> over to <table>
   95168 **         close cursors
   95169 **         foreach index on <table>
   95170 **           open a write cursor on the <table> index
   95171 **           open a read cursor on the corresponding <table2> index
   95172 **           transfer all records from the read to the write cursors
   95173 **           close cursors
   95174 **         end foreach
   95175 **
   95176 ** The 3rd template is for when the second template does not apply
   95177 ** and the SELECT clause does not read from <table> at any time.
   95178 ** The generated code follows this template:
   95179 **
   95180 **         X <- A
   95181 **         goto B
   95182 **      A: setup for the SELECT
   95183 **         loop over the rows in the SELECT
   95184 **           load values into registers R..R+n
   95185 **           yield X
   95186 **         end loop
   95187 **         cleanup after the SELECT
   95188 **         end-coroutine X
   95189 **      B: open write cursor to <table> and its indices
   95190 **      C: yield X, at EOF goto D
   95191 **         insert the select result into <table> from R..R+n
   95192 **         goto C
   95193 **      D: cleanup
   95194 **
   95195 ** The 4th template is used if the insert statement takes its
   95196 ** values from a SELECT but the data is being inserted into a table
   95197 ** that is also read as part of the SELECT.  In the third form,
   95198 ** we have to use a intermediate table to store the results of
   95199 ** the select.  The template is like this:
   95200 **
   95201 **         X <- A
   95202 **         goto B
   95203 **      A: setup for the SELECT
   95204 **         loop over the tables in the SELECT
   95205 **           load value into register R..R+n
   95206 **           yield X
   95207 **         end loop
   95208 **         cleanup after the SELECT
   95209 **         end co-routine R
   95210 **      B: open temp table
   95211 **      L: yield X, at EOF goto M
   95212 **         insert row from R..R+n into temp table
   95213 **         goto L
   95214 **      M: open write cursor to <table> and its indices
   95215 **         rewind temp table
   95216 **      C: loop over rows of intermediate table
   95217 **           transfer values form intermediate table into <table>
   95218 **         end loop
   95219 **      D: cleanup
   95220 */
   95221 SQLITE_PRIVATE void sqlite3Insert(
   95222   Parse *pParse,        /* Parser context */
   95223   SrcList *pTabList,    /* Name of table into which we are inserting */
   95224   Select *pSelect,      /* A SELECT statement to use as the data source */
   95225   IdList *pColumn,      /* Column names corresponding to IDLIST. */
   95226   int onError           /* How to handle constraint errors */
   95227 ){
   95228   sqlite3 *db;          /* The main database structure */
   95229   Table *pTab;          /* The table to insert into.  aka TABLE */
   95230   char *zTab;           /* Name of the table into which we are inserting */
   95231   const char *zDb;      /* Name of the database holding this table */
   95232   int i, j, idx;        /* Loop counters */
   95233   Vdbe *v;              /* Generate code into this virtual machine */
   95234   Index *pIdx;          /* For looping over indices of the table */
   95235   int nColumn;          /* Number of columns in the data */
   95236   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   95237   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
   95238   int iIdxCur = 0;      /* First index cursor */
   95239   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   95240   int endOfLoop;        /* Label for the end of the insertion loop */
   95241   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   95242   int addrInsTop = 0;   /* Jump to label "D" */
   95243   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   95244   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   95245   int iDb;              /* Index of database holding TABLE */
   95246   Db *pDb;              /* The database containing table being inserted into */
   95247   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
   95248   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
   95249   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
   95250   u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
   95251   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
   95252 
   95253   /* Register allocations */
   95254   int regFromSelect = 0;/* Base register for data coming from SELECT */
   95255   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   95256   int regRowCount = 0;  /* Memory cell used for the row counter */
   95257   int regIns;           /* Block of regs holding rowid+data being inserted */
   95258   int regRowid;         /* registers holding insert rowid */
   95259   int regData;          /* register holding first column to insert */
   95260   int *aRegIdx = 0;     /* One register allocated to each index */
   95261 
   95262 #ifndef SQLITE_OMIT_TRIGGER
   95263   int isView;                 /* True if attempting to insert into a view */
   95264   Trigger *pTrigger;          /* List of triggers on pTab, if required */
   95265   int tmask;                  /* Mask of trigger times */
   95266 #endif
   95267 
   95268   db = pParse->db;
   95269   memset(&dest, 0, sizeof(dest));
   95270   if( pParse->nErr || db->mallocFailed ){
   95271     goto insert_cleanup;
   95272   }
   95273 
   95274   /* If the Select object is really just a simple VALUES() list with a
   95275   ** single row values (the common case) then keep that one row of values
   95276   ** and go ahead and discard the Select object
   95277   */
   95278   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
   95279     pList = pSelect->pEList;
   95280     pSelect->pEList = 0;
   95281     sqlite3SelectDelete(db, pSelect);
   95282     pSelect = 0;
   95283   }
   95284 
   95285   /* Locate the table into which we will be inserting new information.
   95286   */
   95287   assert( pTabList->nSrc==1 );
   95288   zTab = pTabList->a[0].zName;
   95289   if( NEVER(zTab==0) ) goto insert_cleanup;
   95290   pTab = sqlite3SrcListLookup(pParse, pTabList);
   95291   if( pTab==0 ){
   95292     goto insert_cleanup;
   95293   }
   95294   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   95295   assert( iDb<db->nDb );
   95296   pDb = &db->aDb[iDb];
   95297   zDb = pDb->zName;
   95298   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   95299     goto insert_cleanup;
   95300   }
   95301   withoutRowid = !HasRowid(pTab);
   95302 
   95303   /* Figure out if we have any triggers and if the table being
   95304   ** inserted into is a view
   95305   */
   95306 #ifndef SQLITE_OMIT_TRIGGER
   95307   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
   95308   isView = pTab->pSelect!=0;
   95309 #else
   95310 # define pTrigger 0
   95311 # define tmask 0
   95312 # define isView 0
   95313 #endif
   95314 #ifdef SQLITE_OMIT_VIEW
   95315 # undef isView
   95316 # define isView 0
   95317 #endif
   95318   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
   95319 
   95320   /* If pTab is really a view, make sure it has been initialized.
   95321   ** ViewGetColumnNames() is a no-op if pTab is not a view.
   95322   */
   95323   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   95324     goto insert_cleanup;
   95325   }
   95326 
   95327   /* Cannot insert into a read-only table.
   95328   */
   95329   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   95330     goto insert_cleanup;
   95331   }
   95332 
   95333   /* Allocate a VDBE
   95334   */
   95335   v = sqlite3GetVdbe(pParse);
   95336   if( v==0 ) goto insert_cleanup;
   95337   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   95338   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   95339 
   95340 #ifndef SQLITE_OMIT_XFER_OPT
   95341   /* If the statement is of the form
   95342   **
   95343   **       INSERT INTO <table1> SELECT * FROM <table2>;
   95344   **
   95345   ** Then special optimizations can be applied that make the transfer
   95346   ** very fast and which reduce fragmentation of indices.
   95347   **
   95348   ** This is the 2nd template.
   95349   */
   95350   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   95351     assert( !pTrigger );
   95352     assert( pList==0 );
   95353     goto insert_end;
   95354   }
   95355 #endif /* SQLITE_OMIT_XFER_OPT */
   95356 
   95357   /* If this is an AUTOINCREMENT table, look up the sequence number in the
   95358   ** sqlite_sequence table and store it in memory cell regAutoinc.
   95359   */
   95360   regAutoinc = autoIncBegin(pParse, iDb, pTab);
   95361 
   95362   /* Allocate registers for holding the rowid of the new row,
   95363   ** the content of the new row, and the assemblied row record.
   95364   */
   95365   regRowid = regIns = pParse->nMem+1;
   95366   pParse->nMem += pTab->nCol + 1;
   95367   if( IsVirtual(pTab) ){
   95368     regRowid++;
   95369     pParse->nMem++;
   95370   }
   95371   regData = regRowid+1;
   95372 
   95373   /* If the INSERT statement included an IDLIST term, then make sure
   95374   ** all elements of the IDLIST really are columns of the table and
   95375   ** remember the column indices.
   95376   **
   95377   ** If the table has an INTEGER PRIMARY KEY column and that column
   95378   ** is named in the IDLIST, then record in the ipkColumn variable
   95379   ** the index into IDLIST of the primary key column.  ipkColumn is
   95380   ** the index of the primary key as it appears in IDLIST, not as
   95381   ** is appears in the original table.  (The index of the INTEGER
   95382   ** PRIMARY KEY in the original table is pTab->iPKey.)
   95383   */
   95384   if( pColumn ){
   95385     for(i=0; i<pColumn->nId; i++){
   95386       pColumn->a[i].idx = -1;
   95387     }
   95388     for(i=0; i<pColumn->nId; i++){
   95389       for(j=0; j<pTab->nCol; j++){
   95390         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   95391           pColumn->a[i].idx = j;
   95392           if( i!=j ) bIdListInOrder = 0;
   95393           if( j==pTab->iPKey ){
   95394             ipkColumn = i;  assert( !withoutRowid );
   95395           }
   95396           break;
   95397         }
   95398       }
   95399       if( j>=pTab->nCol ){
   95400         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
   95401           ipkColumn = i;
   95402           bIdListInOrder = 0;
   95403         }else{
   95404           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   95405               pTabList, 0, pColumn->a[i].zName);
   95406           pParse->checkSchema = 1;
   95407           goto insert_cleanup;
   95408         }
   95409       }
   95410     }
   95411   }
   95412 
   95413   /* Figure out how many columns of data are supplied.  If the data
   95414   ** is coming from a SELECT statement, then generate a co-routine that
   95415   ** produces a single row of the SELECT on each invocation.  The
   95416   ** co-routine is the common header to the 3rd and 4th templates.
   95417   */
   95418   if( pSelect ){
   95419     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
   95420     int regYield;       /* Register holding co-routine entry-point */
   95421     int addrTop;        /* Top of the co-routine */
   95422     int rc;             /* Result code */
   95423 
   95424     regYield = ++pParse->nMem;
   95425     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
   95426     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
   95427     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
   95428     dest.iSdst = bIdListInOrder ? regData : 0;
   95429     dest.nSdst = pTab->nCol;
   95430     rc = sqlite3Select(pParse, pSelect, &dest);
   95431     regFromSelect = dest.iSdst;
   95432     assert( pParse->nErr==0 || rc );
   95433     if( rc || db->mallocFailed ) goto insert_cleanup;
   95434     sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
   95435     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
   95436     assert( pSelect->pEList );
   95437     nColumn = pSelect->pEList->nExpr;
   95438 
   95439     /* Set useTempTable to TRUE if the result of the SELECT statement
   95440     ** should be written into a temporary table (template 4).  Set to
   95441     ** FALSE if each output row of the SELECT can be written directly into
   95442     ** the destination table (template 3).
   95443     **
   95444     ** A temp table must be used if the table being updated is also one
   95445     ** of the tables being read by the SELECT statement.  Also use a
   95446     ** temp table in the case of row triggers.
   95447     */
   95448     if( pTrigger || readsTable(pParse, iDb, pTab) ){
   95449       useTempTable = 1;
   95450     }
   95451 
   95452     if( useTempTable ){
   95453       /* Invoke the coroutine to extract information from the SELECT
   95454       ** and add it to a transient table srcTab.  The code generated
   95455       ** here is from the 4th template:
   95456       **
   95457       **      B: open temp table
   95458       **      L: yield X, goto M at EOF
   95459       **         insert row from R..R+n into temp table
   95460       **         goto L
   95461       **      M: ...
   95462       */
   95463       int regRec;          /* Register to hold packed record */
   95464       int regTempRowid;    /* Register to hold temp table ROWID */
   95465       int addrL;           /* Label "L" */
   95466 
   95467       srcTab = pParse->nTab++;
   95468       regRec = sqlite3GetTempReg(pParse);
   95469       regTempRowid = sqlite3GetTempReg(pParse);
   95470       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   95471       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
   95472       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   95473       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   95474       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   95475       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
   95476       sqlite3VdbeJumpHere(v, addrL);
   95477       sqlite3ReleaseTempReg(pParse, regRec);
   95478       sqlite3ReleaseTempReg(pParse, regTempRowid);
   95479     }
   95480   }else{
   95481     /* This is the case if the data for the INSERT is coming from a VALUES
   95482     ** clause
   95483     */
   95484     NameContext sNC;
   95485     memset(&sNC, 0, sizeof(sNC));
   95486     sNC.pParse = pParse;
   95487     srcTab = -1;
   95488     assert( useTempTable==0 );
   95489     nColumn = pList ? pList->nExpr : 0;
   95490     for(i=0; i<nColumn; i++){
   95491       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   95492         goto insert_cleanup;
   95493       }
   95494     }
   95495   }
   95496 
   95497   /* If there is no IDLIST term but the table has an integer primary
   95498   ** key, the set the ipkColumn variable to the integer primary key
   95499   ** column index in the original table definition.
   95500   */
   95501   if( pColumn==0 && nColumn>0 ){
   95502     ipkColumn = pTab->iPKey;
   95503   }
   95504 
   95505   /* Make sure the number of columns in the source data matches the number
   95506   ** of columns to be inserted into the table.
   95507   */
   95508   if( IsVirtual(pTab) ){
   95509     for(i=0; i<pTab->nCol; i++){
   95510       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   95511     }
   95512   }
   95513   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   95514     sqlite3ErrorMsg(pParse,
   95515        "table %S has %d columns but %d values were supplied",
   95516        pTabList, 0, pTab->nCol-nHidden, nColumn);
   95517     goto insert_cleanup;
   95518   }
   95519   if( pColumn!=0 && nColumn!=pColumn->nId ){
   95520     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   95521     goto insert_cleanup;
   95522   }
   95523 
   95524   /* Initialize the count of rows to be inserted
   95525   */
   95526   if( db->flags & SQLITE_CountRows ){
   95527     regRowCount = ++pParse->nMem;
   95528     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   95529   }
   95530 
   95531   /* If this is not a view, open the table and and all indices */
   95532   if( !isView ){
   95533     int nIdx;
   95534     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
   95535                                       &iDataCur, &iIdxCur);
   95536     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
   95537     if( aRegIdx==0 ){
   95538       goto insert_cleanup;
   95539     }
   95540     for(i=0; i<nIdx; i++){
   95541       aRegIdx[i] = ++pParse->nMem;
   95542     }
   95543   }
   95544 
   95545   /* This is the top of the main insertion loop */
   95546   if( useTempTable ){
   95547     /* This block codes the top of loop only.  The complete loop is the
   95548     ** following pseudocode (template 4):
   95549     **
   95550     **         rewind temp table, if empty goto D
   95551     **      C: loop over rows of intermediate table
   95552     **           transfer values form intermediate table into <table>
   95553     **         end loop
   95554     **      D: ...
   95555     */
   95556     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
   95557     addrCont = sqlite3VdbeCurrentAddr(v);
   95558   }else if( pSelect ){
   95559     /* This block codes the top of loop only.  The complete loop is the
   95560     ** following pseudocode (template 3):
   95561     **
   95562     **      C: yield X, at EOF goto D
   95563     **         insert the select result into <table> from R..R+n
   95564     **         goto C
   95565     **      D: ...
   95566     */
   95567     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
   95568     VdbeCoverage(v);
   95569   }
   95570 
   95571   /* Run the BEFORE and INSTEAD OF triggers, if there are any
   95572   */
   95573   endOfLoop = sqlite3VdbeMakeLabel(v);
   95574   if( tmask & TRIGGER_BEFORE ){
   95575     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   95576 
   95577     /* build the NEW.* reference row.  Note that if there is an INTEGER
   95578     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   95579     ** translated into a unique ID for the row.  But on a BEFORE trigger,
   95580     ** we do not know what the unique ID will be (because the insert has
   95581     ** not happened yet) so we substitute a rowid of -1
   95582     */
   95583     if( ipkColumn<0 ){
   95584       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   95585     }else{
   95586       int j1;
   95587       assert( !withoutRowid );
   95588       if( useTempTable ){
   95589         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
   95590       }else{
   95591         assert( pSelect==0 );  /* Otherwise useTempTable is true */
   95592         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
   95593       }
   95594       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
   95595       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   95596       sqlite3VdbeJumpHere(v, j1);
   95597       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
   95598     }
   95599 
   95600     /* Cannot have triggers on a virtual table. If it were possible,
   95601     ** this block would have to account for hidden column.
   95602     */
   95603     assert( !IsVirtual(pTab) );
   95604 
   95605     /* Create the new column data
   95606     */
   95607     for(i=0; i<pTab->nCol; i++){
   95608       if( pColumn==0 ){
   95609         j = i;
   95610       }else{
   95611         for(j=0; j<pColumn->nId; j++){
   95612           if( pColumn->a[j].idx==i ) break;
   95613         }
   95614       }
   95615       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
   95616         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   95617       }else if( useTempTable ){
   95618         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
   95619       }else{
   95620         assert( pSelect==0 ); /* Otherwise useTempTable is true */
   95621         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   95622       }
   95623     }
   95624 
   95625     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   95626     ** do not attempt any conversions before assembling the record.
   95627     ** If this is a real table, attempt conversions as required by the
   95628     ** table column affinities.
   95629     */
   95630     if( !isView ){
   95631       sqlite3TableAffinity(v, pTab, regCols+1);
   95632     }
   95633 
   95634     /* Fire BEFORE or INSTEAD OF triggers */
   95635     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
   95636         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   95637 
   95638     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   95639   }
   95640 
   95641   /* Compute the content of the next row to insert into a range of
   95642   ** registers beginning at regIns.
   95643   */
   95644   if( !isView ){
   95645     if( IsVirtual(pTab) ){
   95646       /* The row that the VUpdate opcode will delete: none */
   95647       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   95648     }
   95649     if( ipkColumn>=0 ){
   95650       if( useTempTable ){
   95651         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
   95652       }else if( pSelect ){
   95653         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
   95654       }else{
   95655         VdbeOp *pOp;
   95656         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
   95657         pOp = sqlite3VdbeGetOp(v, -1);
   95658         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   95659           appendFlag = 1;
   95660           pOp->opcode = OP_NewRowid;
   95661           pOp->p1 = iDataCur;
   95662           pOp->p2 = regRowid;
   95663           pOp->p3 = regAutoinc;
   95664         }
   95665       }
   95666       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   95667       ** to generate a unique primary key value.
   95668       */
   95669       if( !appendFlag ){
   95670         int j1;
   95671         if( !IsVirtual(pTab) ){
   95672           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
   95673           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   95674           sqlite3VdbeJumpHere(v, j1);
   95675         }else{
   95676           j1 = sqlite3VdbeCurrentAddr(v);
   95677           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
   95678         }
   95679         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
   95680       }
   95681     }else if( IsVirtual(pTab) || withoutRowid ){
   95682       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   95683     }else{
   95684       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   95685       appendFlag = 1;
   95686     }
   95687     autoIncStep(pParse, regAutoinc, regRowid);
   95688 
   95689     /* Compute data for all columns of the new entry, beginning
   95690     ** with the first column.
   95691     */
   95692     nHidden = 0;
   95693     for(i=0; i<pTab->nCol; i++){
   95694       int iRegStore = regRowid+1+i;
   95695       if( i==pTab->iPKey ){
   95696         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   95697         ** Whenever this column is read, the rowid will be substituted
   95698         ** in its place.  Hence, fill this column with a NULL to avoid
   95699         ** taking up data space with information that will never be used.
   95700         ** As there may be shallow copies of this value, make it a soft-NULL */
   95701         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
   95702         continue;
   95703       }
   95704       if( pColumn==0 ){
   95705         if( IsHiddenColumn(&pTab->aCol[i]) ){
   95706           assert( IsVirtual(pTab) );
   95707           j = -1;
   95708           nHidden++;
   95709         }else{
   95710           j = i - nHidden;
   95711         }
   95712       }else{
   95713         for(j=0; j<pColumn->nId; j++){
   95714           if( pColumn->a[j].idx==i ) break;
   95715         }
   95716       }
   95717       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   95718         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
   95719       }else if( useTempTable ){
   95720         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
   95721       }else if( pSelect ){
   95722         if( regFromSelect!=regData ){
   95723           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
   95724         }
   95725       }else{
   95726         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
   95727       }
   95728     }
   95729 
   95730     /* Generate code to check constraints and generate index keys and
   95731     ** do the insertion.
   95732     */
   95733 #ifndef SQLITE_OMIT_VIRTUALTABLE
   95734     if( IsVirtual(pTab) ){
   95735       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   95736       sqlite3VtabMakeWritable(pParse, pTab);
   95737       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
   95738       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   95739       sqlite3MayAbort(pParse);
   95740     }else
   95741 #endif
   95742     {
   95743       int isReplace;    /* Set to true if constraints may cause a replace */
   95744       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
   95745           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
   95746       );
   95747       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
   95748       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
   95749                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
   95750     }
   95751   }
   95752 
   95753   /* Update the count of rows that are inserted
   95754   */
   95755   if( (db->flags & SQLITE_CountRows)!=0 ){
   95756     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   95757   }
   95758 
   95759   if( pTrigger ){
   95760     /* Code AFTER triggers */
   95761     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
   95762         pTab, regData-2-pTab->nCol, onError, endOfLoop);
   95763   }
   95764 
   95765   /* The bottom of the main insertion loop, if the data source
   95766   ** is a SELECT statement.
   95767   */
   95768   sqlite3VdbeResolveLabel(v, endOfLoop);
   95769   if( useTempTable ){
   95770     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
   95771     sqlite3VdbeJumpHere(v, addrInsTop);
   95772     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
   95773   }else if( pSelect ){
   95774     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
   95775     sqlite3VdbeJumpHere(v, addrInsTop);
   95776   }
   95777 
   95778   if( !IsVirtual(pTab) && !isView ){
   95779     /* Close all tables opened */
   95780     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
   95781     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
   95782       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
   95783     }
   95784   }
   95785 
   95786 insert_end:
   95787   /* Update the sqlite_sequence table by storing the content of the
   95788   ** maximum rowid counter values recorded while inserting into
   95789   ** autoincrement tables.
   95790   */
   95791   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   95792     sqlite3AutoincrementEnd(pParse);
   95793   }
   95794 
   95795   /*
   95796   ** Return the number of rows inserted. If this routine is
   95797   ** generating code because of a call to sqlite3NestedParse(), do not
   95798   ** invoke the callback function.
   95799   */
   95800   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   95801     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   95802     sqlite3VdbeSetNumCols(v, 1);
   95803     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
   95804   }
   95805 
   95806 insert_cleanup:
   95807   sqlite3SrcListDelete(db, pTabList);
   95808   sqlite3ExprListDelete(db, pList);
   95809   sqlite3SelectDelete(db, pSelect);
   95810   sqlite3IdListDelete(db, pColumn);
   95811   sqlite3DbFree(db, aRegIdx);
   95812 }
   95813 
   95814 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   95815 ** thely may interfere with compilation of other functions in this file
   95816 ** (or in another file, if this file becomes part of the amalgamation).  */
   95817 #ifdef isView
   95818  #undef isView
   95819 #endif
   95820 #ifdef pTrigger
   95821  #undef pTrigger
   95822 #endif
   95823 #ifdef tmask
   95824  #undef tmask
   95825 #endif
   95826 
   95827 /*
   95828 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
   95829 ** on table pTab.
   95830 **
   95831 ** The regNewData parameter is the first register in a range that contains
   95832 ** the data to be inserted or the data after the update.  There will be
   95833 ** pTab->nCol+1 registers in this range.  The first register (the one
   95834 ** that regNewData points to) will contain the new rowid, or NULL in the
   95835 ** case of a WITHOUT ROWID table.  The second register in the range will
   95836 ** contain the content of the first table column.  The third register will
   95837 ** contain the content of the second table column.  And so forth.
   95838 **
   95839 ** The regOldData parameter is similar to regNewData except that it contains
   95840 ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
   95841 ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
   95842 ** checking regOldData for zero.
   95843 **
   95844 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
   95845 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
   95846 ** might be modified by the UPDATE.  If pkChng is false, then the key of
   95847 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
   95848 **
   95849 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
   95850 ** was explicitly specified as part of the INSERT statement.  If pkChng
   95851 ** is zero, it means that the either rowid is computed automatically or
   95852 ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
   95853 ** pkChng will only be true if the INSERT statement provides an integer
   95854 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
   95855 **
   95856 ** The code generated by this routine will store new index entries into
   95857 ** registers identified by aRegIdx[].  No index entry is created for
   95858 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
   95859 ** the same as the order of indices on the linked list of indices
   95860 ** at pTab->pIndex.
   95861 **
   95862 ** The caller must have already opened writeable cursors on the main
   95863 ** table and all applicable indices (that is to say, all indices for which
   95864 ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
   95865 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
   95866 ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
   95867 ** for the first index in the pTab->pIndex list.  Cursors for other indices
   95868 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
   95869 **
   95870 ** This routine also generates code to check constraints.  NOT NULL,
   95871 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
   95872 ** then the appropriate action is performed.  There are five possible
   95873 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
   95874 **
   95875 **  Constraint type  Action       What Happens
   95876 **  ---------------  ----------   ----------------------------------------
   95877 **  any              ROLLBACK     The current transaction is rolled back and
   95878 **                                sqlite3_step() returns immediately with a
   95879 **                                return code of SQLITE_CONSTRAINT.
   95880 **
   95881 **  any              ABORT        Back out changes from the current command
   95882 **                                only (do not do a complete rollback) then
   95883 **                                cause sqlite3_step() to return immediately
   95884 **                                with SQLITE_CONSTRAINT.
   95885 **
   95886 **  any              FAIL         Sqlite3_step() returns immediately with a
   95887 **                                return code of SQLITE_CONSTRAINT.  The
   95888 **                                transaction is not rolled back and any
   95889 **                                changes to prior rows are retained.
   95890 **
   95891 **  any              IGNORE       The attempt in insert or update the current
   95892 **                                row is skipped, without throwing an error.
   95893 **                                Processing continues with the next row.
   95894 **                                (There is an immediate jump to ignoreDest.)
   95895 **
   95896 **  NOT NULL         REPLACE      The NULL value is replace by the default
   95897 **                                value for that column.  If the default value
   95898 **                                is NULL, the action is the same as ABORT.
   95899 **
   95900 **  UNIQUE           REPLACE      The other row that conflicts with the row
   95901 **                                being inserted is removed.
   95902 **
   95903 **  CHECK            REPLACE      Illegal.  The results in an exception.
   95904 **
   95905 ** Which action to take is determined by the overrideError parameter.
   95906 ** Or if overrideError==OE_Default, then the pParse->onError parameter
   95907 ** is used.  Or if pParse->onError==OE_Default then the onError value
   95908 ** for the constraint is used.
   95909 */
   95910 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   95911   Parse *pParse,       /* The parser context */
   95912   Table *pTab,         /* The table being inserted or updated */
   95913   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
   95914   int iDataCur,        /* Canonical data cursor (main table or PK index) */
   95915   int iIdxCur,         /* First index cursor */
   95916   int regNewData,      /* First register in a range holding values to insert */
   95917   int regOldData,      /* Previous content.  0 for INSERTs */
   95918   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
   95919   u8 overrideError,    /* Override onError to this if not OE_Default */
   95920   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
   95921   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
   95922 ){
   95923   Vdbe *v;             /* VDBE under constrution */
   95924   Index *pIdx;         /* Pointer to one of the indices */
   95925   Index *pPk = 0;      /* The PRIMARY KEY index */
   95926   sqlite3 *db;         /* Database connection */
   95927   int i;               /* loop counter */
   95928   int ix;              /* Index loop counter */
   95929   int nCol;            /* Number of columns */
   95930   int onError;         /* Conflict resolution strategy */
   95931   int j1;              /* Addresss of jump instruction */
   95932   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   95933   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
   95934   int ipkTop = 0;      /* Top of the rowid change constraint check */
   95935   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
   95936   u8 isUpdate;         /* True if this is an UPDATE operation */
   95937   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
   95938   int regRowid = -1;   /* Register holding ROWID value */
   95939 
   95940   isUpdate = regOldData!=0;
   95941   db = pParse->db;
   95942   v = sqlite3GetVdbe(pParse);
   95943   assert( v!=0 );
   95944   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   95945   nCol = pTab->nCol;
   95946 
   95947   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
   95948   ** normal rowid tables.  nPkField is the number of key fields in the
   95949   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
   95950   ** number of fields in the true primary key of the table. */
   95951   if( HasRowid(pTab) ){
   95952     pPk = 0;
   95953     nPkField = 1;
   95954   }else{
   95955     pPk = sqlite3PrimaryKeyIndex(pTab);
   95956     nPkField = pPk->nKeyCol;
   95957   }
   95958 
   95959   /* Record that this module has started */
   95960   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
   95961                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
   95962 
   95963   /* Test all NOT NULL constraints.
   95964   */
   95965   for(i=0; i<nCol; i++){
   95966     if( i==pTab->iPKey ){
   95967       continue;
   95968     }
   95969     onError = pTab->aCol[i].notNull;
   95970     if( onError==OE_None ) continue;
   95971     if( overrideError!=OE_Default ){
   95972       onError = overrideError;
   95973     }else if( onError==OE_Default ){
   95974       onError = OE_Abort;
   95975     }
   95976     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
   95977       onError = OE_Abort;
   95978     }
   95979     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   95980         || onError==OE_Ignore || onError==OE_Replace );
   95981     switch( onError ){
   95982       case OE_Abort:
   95983         sqlite3MayAbort(pParse);
   95984         /* Fall through */
   95985       case OE_Rollback:
   95986       case OE_Fail: {
   95987         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
   95988                                     pTab->aCol[i].zName);
   95989         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
   95990                           regNewData+1+i, zMsg, P4_DYNAMIC);
   95991         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
   95992         VdbeCoverage(v);
   95993         break;
   95994       }
   95995       case OE_Ignore: {
   95996         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
   95997         VdbeCoverage(v);
   95998         break;
   95999       }
   96000       default: {
   96001         assert( onError==OE_Replace );
   96002         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
   96003         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
   96004         sqlite3VdbeJumpHere(v, j1);
   96005         break;
   96006       }
   96007     }
   96008   }
   96009 
   96010   /* Test all CHECK constraints
   96011   */
   96012 #ifndef SQLITE_OMIT_CHECK
   96013   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
   96014     ExprList *pCheck = pTab->pCheck;
   96015     pParse->ckBase = regNewData+1;
   96016     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
   96017     for(i=0; i<pCheck->nExpr; i++){
   96018       int allOk = sqlite3VdbeMakeLabel(v);
   96019       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
   96020       if( onError==OE_Ignore ){
   96021         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   96022       }else{
   96023         char *zName = pCheck->a[i].zName;
   96024         if( zName==0 ) zName = pTab->zName;
   96025         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
   96026         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
   96027                               onError, zName, P4_TRANSIENT,
   96028                               P5_ConstraintCheck);
   96029       }
   96030       sqlite3VdbeResolveLabel(v, allOk);
   96031     }
   96032   }
   96033 #endif /* !defined(SQLITE_OMIT_CHECK) */
   96034 
   96035   /* If rowid is changing, make sure the new rowid does not previously
   96036   ** exist in the table.
   96037   */
   96038   if( pkChng && pPk==0 ){
   96039     int addrRowidOk = sqlite3VdbeMakeLabel(v);
   96040 
   96041     /* Figure out what action to take in case of a rowid collision */
   96042     onError = pTab->keyConf;
   96043     if( overrideError!=OE_Default ){
   96044       onError = overrideError;
   96045     }else if( onError==OE_Default ){
   96046       onError = OE_Abort;
   96047     }
   96048 
   96049     if( isUpdate ){
   96050       /* pkChng!=0 does not mean that the rowid has change, only that
   96051       ** it might have changed.  Skip the conflict logic below if the rowid
   96052       ** is unchanged. */
   96053       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
   96054       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   96055       VdbeCoverage(v);
   96056     }
   96057 
   96058     /* If the response to a rowid conflict is REPLACE but the response
   96059     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
   96060     ** to defer the running of the rowid conflict checking until after
   96061     ** the UNIQUE constraints have run.
   96062     */
   96063     if( onError==OE_Replace && overrideError!=OE_Replace ){
   96064       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   96065         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
   96066           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
   96067           break;
   96068         }
   96069       }
   96070     }
   96071 
   96072     /* Check to see if the new rowid already exists in the table.  Skip
   96073     ** the following conflict logic if it does not. */
   96074     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
   96075     VdbeCoverage(v);
   96076 
   96077     /* Generate code that deals with a rowid collision */
   96078     switch( onError ){
   96079       default: {
   96080         onError = OE_Abort;
   96081         /* Fall thru into the next case */
   96082       }
   96083       case OE_Rollback:
   96084       case OE_Abort:
   96085       case OE_Fail: {
   96086         sqlite3RowidConstraint(pParse, onError, pTab);
   96087         break;
   96088       }
   96089       case OE_Replace: {
   96090         /* If there are DELETE triggers on this table and the
   96091         ** recursive-triggers flag is set, call GenerateRowDelete() to
   96092         ** remove the conflicting row from the table. This will fire
   96093         ** the triggers and remove both the table and index b-tree entries.
   96094         **
   96095         ** Otherwise, if there are no triggers or the recursive-triggers
   96096         ** flag is not set, but the table has one or more indexes, call
   96097         ** GenerateRowIndexDelete(). This removes the index b-tree entries
   96098         ** only. The table b-tree entry will be replaced by the new entry
   96099         ** when it is inserted.
   96100         **
   96101         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
   96102         ** also invoke MultiWrite() to indicate that this VDBE may require
   96103         ** statement rollback (if the statement is aborted after the delete
   96104         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
   96105         ** but being more selective here allows statements like:
   96106         **
   96107         **   REPLACE INTO t(rowid) VALUES($newrowid)
   96108         **
   96109         ** to run without a statement journal if there are no indexes on the
   96110         ** table.
   96111         */
   96112         Trigger *pTrigger = 0;
   96113         if( db->flags&SQLITE_RecTriggers ){
   96114           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   96115         }
   96116         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
   96117           sqlite3MultiWrite(pParse);
   96118           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   96119                                    regNewData, 1, 0, OE_Replace, 1);
   96120         }else if( pTab->pIndex ){
   96121           sqlite3MultiWrite(pParse);
   96122           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
   96123         }
   96124         seenReplace = 1;
   96125         break;
   96126       }
   96127       case OE_Ignore: {
   96128         /*assert( seenReplace==0 );*/
   96129         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   96130         break;
   96131       }
   96132     }
   96133     sqlite3VdbeResolveLabel(v, addrRowidOk);
   96134     if( ipkTop ){
   96135       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
   96136       sqlite3VdbeJumpHere(v, ipkTop);
   96137     }
   96138   }
   96139 
   96140   /* Test all UNIQUE constraints by creating entries for each UNIQUE
   96141   ** index and making sure that duplicate entries do not already exist.
   96142   ** Compute the revised record entries for indices as we go.
   96143   **
   96144   ** This loop also handles the case of the PRIMARY KEY index for a
   96145   ** WITHOUT ROWID table.
   96146   */
   96147   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
   96148     int regIdx;          /* Range of registers hold conent for pIdx */
   96149     int regR;            /* Range of registers holding conflicting PK */
   96150     int iThisCur;        /* Cursor for this UNIQUE index */
   96151     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
   96152 
   96153     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
   96154     if( bAffinityDone==0 ){
   96155       sqlite3TableAffinity(v, pTab, regNewData+1);
   96156       bAffinityDone = 1;
   96157     }
   96158     iThisCur = iIdxCur+ix;
   96159     addrUniqueOk = sqlite3VdbeMakeLabel(v);
   96160 
   96161     /* Skip partial indices for which the WHERE clause is not true */
   96162     if( pIdx->pPartIdxWhere ){
   96163       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
   96164       pParse->ckBase = regNewData+1;
   96165       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
   96166                          SQLITE_JUMPIFNULL);
   96167       pParse->ckBase = 0;
   96168     }
   96169 
   96170     /* Create a record for this index entry as it should appear after
   96171     ** the insert or update.  Store that record in the aRegIdx[ix] register
   96172     */
   96173     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
   96174     for(i=0; i<pIdx->nColumn; i++){
   96175       int iField = pIdx->aiColumn[i];
   96176       int x;
   96177       if( iField<0 || iField==pTab->iPKey ){
   96178         if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
   96179         x = regNewData;
   96180         regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
   96181       }else{
   96182         x = iField + regNewData + 1;
   96183       }
   96184       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
   96185       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
   96186     }
   96187     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
   96188     VdbeComment((v, "for %s", pIdx->zName));
   96189     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
   96190 
   96191     /* In an UPDATE operation, if this index is the PRIMARY KEY index
   96192     ** of a WITHOUT ROWID table and there has been no change the
   96193     ** primary key, then no collision is possible.  The collision detection
   96194     ** logic below can all be skipped. */
   96195     if( isUpdate && pPk==pIdx && pkChng==0 ){
   96196       sqlite3VdbeResolveLabel(v, addrUniqueOk);
   96197       continue;
   96198     }
   96199 
   96200     /* Find out what action to take in case there is a uniqueness conflict */
   96201     onError = pIdx->onError;
   96202     if( onError==OE_None ){
   96203       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
   96204       sqlite3VdbeResolveLabel(v, addrUniqueOk);
   96205       continue;  /* pIdx is not a UNIQUE index */
   96206     }
   96207     if( overrideError!=OE_Default ){
   96208       onError = overrideError;
   96209     }else if( onError==OE_Default ){
   96210       onError = OE_Abort;
   96211     }
   96212 
   96213     /* Check to see if the new index entry will be unique */
   96214     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
   96215                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
   96216 
   96217     /* Generate code to handle collisions */
   96218     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
   96219     if( isUpdate || onError==OE_Replace ){
   96220       if( HasRowid(pTab) ){
   96221         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
   96222         /* Conflict only if the rowid of the existing index entry
   96223         ** is different from old-rowid */
   96224         if( isUpdate ){
   96225           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
   96226           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   96227           VdbeCoverage(v);
   96228         }
   96229       }else{
   96230         int x;
   96231         /* Extract the PRIMARY KEY from the end of the index entry and
   96232         ** store it in registers regR..regR+nPk-1 */
   96233         if( pIdx!=pPk ){
   96234           for(i=0; i<pPk->nKeyCol; i++){
   96235             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
   96236             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
   96237             VdbeComment((v, "%s.%s", pTab->zName,
   96238                          pTab->aCol[pPk->aiColumn[i]].zName));
   96239           }
   96240         }
   96241         if( isUpdate ){
   96242           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
   96243           ** table, only conflict if the new PRIMARY KEY values are actually
   96244           ** different from the old.
   96245           **
   96246           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
   96247           ** of the matched index row are different from the original PRIMARY
   96248           ** KEY values of this row before the update.  */
   96249           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
   96250           int op = OP_Ne;
   96251           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
   96252 
   96253           for(i=0; i<pPk->nKeyCol; i++){
   96254             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
   96255             x = pPk->aiColumn[i];
   96256             if( i==(pPk->nKeyCol-1) ){
   96257               addrJump = addrUniqueOk;
   96258               op = OP_Eq;
   96259             }
   96260             sqlite3VdbeAddOp4(v, op,
   96261                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
   96262             );
   96263             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   96264             VdbeCoverageIf(v, op==OP_Eq);
   96265             VdbeCoverageIf(v, op==OP_Ne);
   96266           }
   96267         }
   96268       }
   96269     }
   96270 
   96271     /* Generate code that executes if the new index entry is not unique */
   96272     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   96273         || onError==OE_Ignore || onError==OE_Replace );
   96274     switch( onError ){
   96275       case OE_Rollback:
   96276       case OE_Abort:
   96277       case OE_Fail: {
   96278         sqlite3UniqueConstraint(pParse, onError, pIdx);
   96279         break;
   96280       }
   96281       case OE_Ignore: {
   96282         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   96283         break;
   96284       }
   96285       default: {
   96286         Trigger *pTrigger = 0;
   96287         assert( onError==OE_Replace );
   96288         sqlite3MultiWrite(pParse);
   96289         if( db->flags&SQLITE_RecTriggers ){
   96290           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   96291         }
   96292         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   96293                                  regR, nPkField, 0, OE_Replace, pIdx==pPk);
   96294         seenReplace = 1;
   96295         break;
   96296       }
   96297     }
   96298     sqlite3VdbeResolveLabel(v, addrUniqueOk);
   96299     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
   96300     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
   96301   }
   96302   if( ipkTop ){
   96303     sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
   96304     sqlite3VdbeJumpHere(v, ipkBottom);
   96305   }
   96306 
   96307   *pbMayReplace = seenReplace;
   96308   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
   96309 }
   96310 
   96311 /*
   96312 ** This routine generates code to finish the INSERT or UPDATE operation
   96313 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
   96314 ** A consecutive range of registers starting at regNewData contains the
   96315 ** rowid and the content to be inserted.
   96316 **
   96317 ** The arguments to this routine should be the same as the first six
   96318 ** arguments to sqlite3GenerateConstraintChecks.
   96319 */
   96320 SQLITE_PRIVATE void sqlite3CompleteInsertion(
   96321   Parse *pParse,      /* The parser context */
   96322   Table *pTab,        /* the table into which we are inserting */
   96323   int iDataCur,       /* Cursor of the canonical data source */
   96324   int iIdxCur,        /* First index cursor */
   96325   int regNewData,     /* Range of content */
   96326   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   96327   int isUpdate,       /* True for UPDATE, False for INSERT */
   96328   int appendBias,     /* True if this is likely to be an append */
   96329   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
   96330 ){
   96331   Vdbe *v;            /* Prepared statements under construction */
   96332   Index *pIdx;        /* An index being inserted or updated */
   96333   u8 pik_flags;       /* flag values passed to the btree insert */
   96334   int regData;        /* Content registers (after the rowid) */
   96335   int regRec;         /* Register holding assemblied record for the table */
   96336   int i;              /* Loop counter */
   96337   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
   96338 
   96339   v = sqlite3GetVdbe(pParse);
   96340   assert( v!=0 );
   96341   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   96342   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   96343     if( aRegIdx[i]==0 ) continue;
   96344     bAffinityDone = 1;
   96345     if( pIdx->pPartIdxWhere ){
   96346       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
   96347       VdbeCoverage(v);
   96348     }
   96349     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
   96350     pik_flags = 0;
   96351     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
   96352     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
   96353       assert( pParse->nested==0 );
   96354       pik_flags |= OPFLAG_NCHANGE;
   96355     }
   96356     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
   96357   }
   96358   if( !HasRowid(pTab) ) return;
   96359   regData = regNewData + 1;
   96360   regRec = sqlite3GetTempReg(pParse);
   96361   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
   96362   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
   96363   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
   96364   if( pParse->nested ){
   96365     pik_flags = 0;
   96366   }else{
   96367     pik_flags = OPFLAG_NCHANGE;
   96368     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
   96369   }
   96370   if( appendBias ){
   96371     pik_flags |= OPFLAG_APPEND;
   96372   }
   96373   if( useSeekResult ){
   96374     pik_flags |= OPFLAG_USESEEKRESULT;
   96375   }
   96376   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
   96377   if( !pParse->nested ){
   96378     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
   96379   }
   96380   sqlite3VdbeChangeP5(v, pik_flags);
   96381 }
   96382 
   96383 /*
   96384 ** Allocate cursors for the pTab table and all its indices and generate
   96385 ** code to open and initialized those cursors.
   96386 **
   96387 ** The cursor for the object that contains the complete data (normally
   96388 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
   96389 ** ROWID table) is returned in *piDataCur.  The first index cursor is
   96390 ** returned in *piIdxCur.  The number of indices is returned.
   96391 **
   96392 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
   96393 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
   96394 ** If iBase is negative, then allocate the next available cursor.
   96395 **
   96396 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
   96397 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
   96398 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
   96399 ** pTab->pIndex list.
   96400 */
   96401 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
   96402   Parse *pParse,   /* Parsing context */
   96403   Table *pTab,     /* Table to be opened */
   96404   int op,          /* OP_OpenRead or OP_OpenWrite */
   96405   int iBase,       /* Use this for the table cursor, if there is one */
   96406   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
   96407   int *piDataCur,  /* Write the database source cursor number here */
   96408   int *piIdxCur    /* Write the first index cursor number here */
   96409 ){
   96410   int i;
   96411   int iDb;
   96412   int iDataCur;
   96413   Index *pIdx;
   96414   Vdbe *v;
   96415 
   96416   assert( op==OP_OpenRead || op==OP_OpenWrite );
   96417   if( IsVirtual(pTab) ){
   96418     assert( aToOpen==0 );
   96419     *piDataCur = 0;
   96420     *piIdxCur = 1;
   96421     return 0;
   96422   }
   96423   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   96424   v = sqlite3GetVdbe(pParse);
   96425   assert( v!=0 );
   96426   if( iBase<0 ) iBase = pParse->nTab;
   96427   iDataCur = iBase++;
   96428   if( piDataCur ) *piDataCur = iDataCur;
   96429   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
   96430     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
   96431   }else{
   96432     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
   96433   }
   96434   if( piIdxCur ) *piIdxCur = iBase;
   96435   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   96436     int iIdxCur = iBase++;
   96437     assert( pIdx->pSchema==pTab->pSchema );
   96438     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
   96439       *piDataCur = iIdxCur;
   96440     }
   96441     if( aToOpen==0 || aToOpen[i+1] ){
   96442       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
   96443       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   96444       VdbeComment((v, "%s", pIdx->zName));
   96445     }
   96446   }
   96447   if( iBase>pParse->nTab ) pParse->nTab = iBase;
   96448   return i;
   96449 }
   96450 
   96451 
   96452 #ifdef SQLITE_TEST
   96453 /*
   96454 ** The following global variable is incremented whenever the
   96455 ** transfer optimization is used.  This is used for testing
   96456 ** purposes only - to make sure the transfer optimization really
   96457 ** is happening when it is suppose to.
   96458 */
   96459 SQLITE_API int sqlite3_xferopt_count;
   96460 #endif /* SQLITE_TEST */
   96461 
   96462 
   96463 #ifndef SQLITE_OMIT_XFER_OPT
   96464 /*
   96465 ** Check to collation names to see if they are compatible.
   96466 */
   96467 static int xferCompatibleCollation(const char *z1, const char *z2){
   96468   if( z1==0 ){
   96469     return z2==0;
   96470   }
   96471   if( z2==0 ){
   96472     return 0;
   96473   }
   96474   return sqlite3StrICmp(z1, z2)==0;
   96475 }
   96476 
   96477 
   96478 /*
   96479 ** Check to see if index pSrc is compatible as a source of data
   96480 ** for index pDest in an insert transfer optimization.  The rules
   96481 ** for a compatible index:
   96482 **
   96483 **    *   The index is over the same set of columns
   96484 **    *   The same DESC and ASC markings occurs on all columns
   96485 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
   96486 **    *   The same collating sequence on each column
   96487 **    *   The index has the exact same WHERE clause
   96488 */
   96489 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
   96490   int i;
   96491   assert( pDest && pSrc );
   96492   assert( pDest->pTable!=pSrc->pTable );
   96493   if( pDest->nKeyCol!=pSrc->nKeyCol ){
   96494     return 0;   /* Different number of columns */
   96495   }
   96496   if( pDest->onError!=pSrc->onError ){
   96497     return 0;   /* Different conflict resolution strategies */
   96498   }
   96499   for(i=0; i<pSrc->nKeyCol; i++){
   96500     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
   96501       return 0;   /* Different columns indexed */
   96502     }
   96503     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
   96504       return 0;   /* Different sort orders */
   96505     }
   96506     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
   96507       return 0;   /* Different collating sequences */
   96508     }
   96509   }
   96510   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
   96511     return 0;     /* Different WHERE clauses */
   96512   }
   96513 
   96514   /* If no test above fails then the indices must be compatible */
   96515   return 1;
   96516 }
   96517 
   96518 /*
   96519 ** Attempt the transfer optimization on INSERTs of the form
   96520 **
   96521 **     INSERT INTO tab1 SELECT * FROM tab2;
   96522 **
   96523 ** The xfer optimization transfers raw records from tab2 over to tab1.
   96524 ** Columns are not decoded and reassemblied, which greatly improves
   96525 ** performance.  Raw index records are transferred in the same way.
   96526 **
   96527 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
   96528 ** There are lots of rules for determining compatibility - see comments
   96529 ** embedded in the code for details.
   96530 **
   96531 ** This routine returns TRUE if the optimization is guaranteed to be used.
   96532 ** Sometimes the xfer optimization will only work if the destination table
   96533 ** is empty - a factor that can only be determined at run-time.  In that
   96534 ** case, this routine generates code for the xfer optimization but also
   96535 ** does a test to see if the destination table is empty and jumps over the
   96536 ** xfer optimization code if the test fails.  In that case, this routine
   96537 ** returns FALSE so that the caller will know to go ahead and generate
   96538 ** an unoptimized transfer.  This routine also returns FALSE if there
   96539 ** is no chance that the xfer optimization can be applied.
   96540 **
   96541 ** This optimization is particularly useful at making VACUUM run faster.
   96542 */
   96543 static int xferOptimization(
   96544   Parse *pParse,        /* Parser context */
   96545   Table *pDest,         /* The table we are inserting into */
   96546   Select *pSelect,      /* A SELECT statement to use as the data source */
   96547   int onError,          /* How to handle constraint errors */
   96548   int iDbDest           /* The database of pDest */
   96549 ){
   96550   ExprList *pEList;                /* The result set of the SELECT */
   96551   Table *pSrc;                     /* The table in the FROM clause of SELECT */
   96552   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
   96553   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
   96554   int i;                           /* Loop counter */
   96555   int iDbSrc;                      /* The database of pSrc */
   96556   int iSrc, iDest;                 /* Cursors from source and destination */
   96557   int addr1, addr2;                /* Loop addresses */
   96558   int emptyDestTest = 0;           /* Address of test for empty pDest */
   96559   int emptySrcTest = 0;            /* Address of test for empty pSrc */
   96560   Vdbe *v;                         /* The VDBE we are building */
   96561   int regAutoinc;                  /* Memory register used by AUTOINC */
   96562   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
   96563   int regData, regRowid;           /* Registers holding data and rowid */
   96564 
   96565   if( pSelect==0 ){
   96566     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
   96567   }
   96568   if( pParse->pWith || pSelect->pWith ){
   96569     /* Do not attempt to process this query if there are an WITH clauses
   96570     ** attached to it. Proceeding may generate a false "no such table: xxx"
   96571     ** error if pSelect reads from a CTE named "xxx".  */
   96572     return 0;
   96573   }
   96574   if( sqlite3TriggerList(pParse, pDest) ){
   96575     return 0;   /* tab1 must not have triggers */
   96576   }
   96577 #ifndef SQLITE_OMIT_VIRTUALTABLE
   96578   if( pDest->tabFlags & TF_Virtual ){
   96579     return 0;   /* tab1 must not be a virtual table */
   96580   }
   96581 #endif
   96582   if( onError==OE_Default ){
   96583     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
   96584     if( onError==OE_Default ) onError = OE_Abort;
   96585   }
   96586   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
   96587   if( pSelect->pSrc->nSrc!=1 ){
   96588     return 0;   /* FROM clause must have exactly one term */
   96589   }
   96590   if( pSelect->pSrc->a[0].pSelect ){
   96591     return 0;   /* FROM clause cannot contain a subquery */
   96592   }
   96593   if( pSelect->pWhere ){
   96594     return 0;   /* SELECT may not have a WHERE clause */
   96595   }
   96596   if( pSelect->pOrderBy ){
   96597     return 0;   /* SELECT may not have an ORDER BY clause */
   96598   }
   96599   /* Do not need to test for a HAVING clause.  If HAVING is present but
   96600   ** there is no ORDER BY, we will get an error. */
   96601   if( pSelect->pGroupBy ){
   96602     return 0;   /* SELECT may not have a GROUP BY clause */
   96603   }
   96604   if( pSelect->pLimit ){
   96605     return 0;   /* SELECT may not have a LIMIT clause */
   96606   }
   96607   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
   96608   if( pSelect->pPrior ){
   96609     return 0;   /* SELECT may not be a compound query */
   96610   }
   96611   if( pSelect->selFlags & SF_Distinct ){
   96612     return 0;   /* SELECT may not be DISTINCT */
   96613   }
   96614   pEList = pSelect->pEList;
   96615   assert( pEList!=0 );
   96616   if( pEList->nExpr!=1 ){
   96617     return 0;   /* The result set must have exactly one column */
   96618   }
   96619   assert( pEList->a[0].pExpr );
   96620   if( pEList->a[0].pExpr->op!=TK_ALL ){
   96621     return 0;   /* The result set must be the special operator "*" */
   96622   }
   96623 
   96624   /* At this point we have established that the statement is of the
   96625   ** correct syntactic form to participate in this optimization.  Now
   96626   ** we have to check the semantics.
   96627   */
   96628   pItem = pSelect->pSrc->a;
   96629   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
   96630   if( pSrc==0 ){
   96631     return 0;   /* FROM clause does not contain a real table */
   96632   }
   96633   if( pSrc==pDest ){
   96634     return 0;   /* tab1 and tab2 may not be the same table */
   96635   }
   96636   if( HasRowid(pDest)!=HasRowid(pSrc) ){
   96637     return 0;   /* source and destination must both be WITHOUT ROWID or not */
   96638   }
   96639 #ifndef SQLITE_OMIT_VIRTUALTABLE
   96640   if( pSrc->tabFlags & TF_Virtual ){
   96641     return 0;   /* tab2 must not be a virtual table */
   96642   }
   96643 #endif
   96644   if( pSrc->pSelect ){
   96645     return 0;   /* tab2 may not be a view */
   96646   }
   96647   if( pDest->nCol!=pSrc->nCol ){
   96648     return 0;   /* Number of columns must be the same in tab1 and tab2 */
   96649   }
   96650   if( pDest->iPKey!=pSrc->iPKey ){
   96651     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
   96652   }
   96653   for(i=0; i<pDest->nCol; i++){
   96654     Column *pDestCol = &pDest->aCol[i];
   96655     Column *pSrcCol = &pSrc->aCol[i];
   96656     if( pDestCol->affinity!=pSrcCol->affinity ){
   96657       return 0;    /* Affinity must be the same on all columns */
   96658     }
   96659     if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
   96660       return 0;    /* Collating sequence must be the same on all columns */
   96661     }
   96662     if( pDestCol->notNull && !pSrcCol->notNull ){
   96663       return 0;    /* tab2 must be NOT NULL if tab1 is */
   96664     }
   96665     /* Default values for second and subsequent columns need to match. */
   96666     if( i>0
   96667      && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
   96668          || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
   96669     ){
   96670       return 0;    /* Default values must be the same for all columns */
   96671     }
   96672   }
   96673   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   96674     if( IsUniqueIndex(pDestIdx) ){
   96675       destHasUniqueIdx = 1;
   96676     }
   96677     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
   96678       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   96679     }
   96680     if( pSrcIdx==0 ){
   96681       return 0;    /* pDestIdx has no corresponding index in pSrc */
   96682     }
   96683   }
   96684 #ifndef SQLITE_OMIT_CHECK
   96685   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
   96686     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
   96687   }
   96688 #endif
   96689 #ifndef SQLITE_OMIT_FOREIGN_KEY
   96690   /* Disallow the transfer optimization if the destination table constains
   96691   ** any foreign key constraints.  This is more restrictive than necessary.
   96692   ** But the main beneficiary of the transfer optimization is the VACUUM
   96693   ** command, and the VACUUM command disables foreign key constraints.  So
   96694   ** the extra complication to make this rule less restrictive is probably
   96695   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
   96696   */
   96697   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
   96698     return 0;
   96699   }
   96700 #endif
   96701   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
   96702     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
   96703   }
   96704 
   96705   /* If we get this far, it means that the xfer optimization is at
   96706   ** least a possibility, though it might only work if the destination
   96707   ** table (tab1) is initially empty.
   96708   */
   96709 #ifdef SQLITE_TEST
   96710   sqlite3_xferopt_count++;
   96711 #endif
   96712   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
   96713   v = sqlite3GetVdbe(pParse);
   96714   sqlite3CodeVerifySchema(pParse, iDbSrc);
   96715   iSrc = pParse->nTab++;
   96716   iDest = pParse->nTab++;
   96717   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
   96718   regData = sqlite3GetTempReg(pParse);
   96719   regRowid = sqlite3GetTempReg(pParse);
   96720   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
   96721   assert( HasRowid(pDest) || destHasUniqueIdx );
   96722   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
   96723    || destHasUniqueIdx                              /* (2) */
   96724    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
   96725   ){
   96726     /* In some circumstances, we are able to run the xfer optimization
   96727     ** only if the destination table is initially empty.  This code makes
   96728     ** that determination.  Conditions under which the destination must
   96729     ** be empty:
   96730     **
   96731     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
   96732     **     (If the destination is not initially empty, the rowid fields
   96733     **     of index entries might need to change.)
   96734     **
   96735     ** (2) The destination has a unique index.  (The xfer optimization
   96736     **     is unable to test uniqueness.)
   96737     **
   96738     ** (3) onError is something other than OE_Abort and OE_Rollback.
   96739     */
   96740     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
   96741     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   96742     sqlite3VdbeJumpHere(v, addr1);
   96743   }
   96744   if( HasRowid(pSrc) ){
   96745     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
   96746     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
   96747     if( pDest->iPKey>=0 ){
   96748       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   96749       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
   96750       VdbeCoverage(v);
   96751       sqlite3RowidConstraint(pParse, onError, pDest);
   96752       sqlite3VdbeJumpHere(v, addr2);
   96753       autoIncStep(pParse, regAutoinc, regRowid);
   96754     }else if( pDest->pIndex==0 ){
   96755       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
   96756     }else{
   96757       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   96758       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
   96759     }
   96760     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
   96761     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
   96762     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
   96763     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
   96764     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
   96765     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   96766     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   96767   }else{
   96768     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
   96769     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
   96770   }
   96771   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   96772     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
   96773       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   96774     }
   96775     assert( pSrcIdx );
   96776     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
   96777     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
   96778     VdbeComment((v, "%s", pSrcIdx->zName));
   96779     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
   96780     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
   96781     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
   96782     VdbeComment((v, "%s", pDestIdx->zName));
   96783     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
   96784     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
   96785     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
   96786     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
   96787     sqlite3VdbeJumpHere(v, addr1);
   96788     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   96789     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   96790   }
   96791   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
   96792   sqlite3ReleaseTempReg(pParse, regRowid);
   96793   sqlite3ReleaseTempReg(pParse, regData);
   96794   if( emptyDestTest ){
   96795     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
   96796     sqlite3VdbeJumpHere(v, emptyDestTest);
   96797     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   96798     return 0;
   96799   }else{
   96800     return 1;
   96801   }
   96802 }
   96803 #endif /* SQLITE_OMIT_XFER_OPT */
   96804 
   96805 /************** End of insert.c **********************************************/
   96806 /************** Begin file legacy.c ******************************************/
   96807 /*
   96808 ** 2001 September 15
   96809 **
   96810 ** The author disclaims copyright to this source code.  In place of
   96811 ** a legal notice, here is a blessing:
   96812 **
   96813 **    May you do good and not evil.
   96814 **    May you find forgiveness for yourself and forgive others.
   96815 **    May you share freely, never taking more than you give.
   96816 **
   96817 *************************************************************************
   96818 ** Main file for the SQLite library.  The routines in this file
   96819 ** implement the programmer interface to the library.  Routines in
   96820 ** other files are for internal use by SQLite and should not be
   96821 ** accessed by users of the library.
   96822 */
   96823 
   96824 
   96825 /*
   96826 ** Execute SQL code.  Return one of the SQLITE_ success/failure
   96827 ** codes.  Also write an error message into memory obtained from
   96828 ** malloc() and make *pzErrMsg point to that message.
   96829 **
   96830 ** If the SQL is a query, then for each row in the query result
   96831 ** the xCallback() function is called.  pArg becomes the first
   96832 ** argument to xCallback().  If xCallback=NULL then no callback
   96833 ** is invoked, even for queries.
   96834 */
   96835 SQLITE_API int sqlite3_exec(
   96836   sqlite3 *db,                /* The database on which the SQL executes */
   96837   const char *zSql,           /* The SQL to be executed */
   96838   sqlite3_callback xCallback, /* Invoke this callback routine */
   96839   void *pArg,                 /* First argument to xCallback() */
   96840   char **pzErrMsg             /* Write error messages here */
   96841 ){
   96842   int rc = SQLITE_OK;         /* Return code */
   96843   const char *zLeftover;      /* Tail of unprocessed SQL */
   96844   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
   96845   char **azCols = 0;          /* Names of result columns */
   96846   int callbackIsInit;         /* True if callback data is initialized */
   96847 
   96848   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   96849   if( zSql==0 ) zSql = "";
   96850 
   96851   sqlite3_mutex_enter(db->mutex);
   96852   sqlite3Error(db, SQLITE_OK, 0);
   96853   while( rc==SQLITE_OK && zSql[0] ){
   96854     int nCol;
   96855     char **azVals = 0;
   96856 
   96857     pStmt = 0;
   96858     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
   96859     assert( rc==SQLITE_OK || pStmt==0 );
   96860     if( rc!=SQLITE_OK ){
   96861       continue;
   96862     }
   96863     if( !pStmt ){
   96864       /* this happens for a comment or white-space */
   96865       zSql = zLeftover;
   96866       continue;
   96867     }
   96868 
   96869     callbackIsInit = 0;
   96870     nCol = sqlite3_column_count(pStmt);
   96871 
   96872     while( 1 ){
   96873       int i;
   96874       rc = sqlite3_step(pStmt);
   96875 
   96876       /* Invoke the callback function if required */
   96877       if( xCallback && (SQLITE_ROW==rc ||
   96878           (SQLITE_DONE==rc && !callbackIsInit
   96879                            && db->flags&SQLITE_NullCallback)) ){
   96880         if( !callbackIsInit ){
   96881           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
   96882           if( azCols==0 ){
   96883             goto exec_out;
   96884           }
   96885           for(i=0; i<nCol; i++){
   96886             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
   96887             /* sqlite3VdbeSetColName() installs column names as UTF8
   96888             ** strings so there is no way for sqlite3_column_name() to fail. */
   96889             assert( azCols[i]!=0 );
   96890           }
   96891           callbackIsInit = 1;
   96892         }
   96893         if( rc==SQLITE_ROW ){
   96894           azVals = &azCols[nCol];
   96895           for(i=0; i<nCol; i++){
   96896             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
   96897             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
   96898               db->mallocFailed = 1;
   96899               goto exec_out;
   96900             }
   96901           }
   96902         }
   96903         if( xCallback(pArg, nCol, azVals, azCols) ){
   96904           /* EVIDENCE-OF: R-38229-40159 If the callback function to
   96905           ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
   96906           ** return SQLITE_ABORT. */
   96907           rc = SQLITE_ABORT;
   96908           sqlite3VdbeFinalize((Vdbe *)pStmt);
   96909           pStmt = 0;
   96910           sqlite3Error(db, SQLITE_ABORT, 0);
   96911           goto exec_out;
   96912         }
   96913       }
   96914 
   96915       if( rc!=SQLITE_ROW ){
   96916         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
   96917         pStmt = 0;
   96918         zSql = zLeftover;
   96919         while( sqlite3Isspace(zSql[0]) ) zSql++;
   96920         break;
   96921       }
   96922     }
   96923 
   96924     sqlite3DbFree(db, azCols);
   96925     azCols = 0;
   96926   }
   96927 
   96928 exec_out:
   96929   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
   96930   sqlite3DbFree(db, azCols);
   96931 
   96932   rc = sqlite3ApiExit(db, rc);
   96933   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
   96934     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
   96935     *pzErrMsg = sqlite3Malloc(nErrMsg);
   96936     if( *pzErrMsg ){
   96937       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
   96938     }else{
   96939       rc = SQLITE_NOMEM;
   96940       sqlite3Error(db, SQLITE_NOMEM, 0);
   96941     }
   96942   }else if( pzErrMsg ){
   96943     *pzErrMsg = 0;
   96944   }
   96945 
   96946   assert( (rc&db->errMask)==rc );
   96947   sqlite3_mutex_leave(db->mutex);
   96948   return rc;
   96949 }
   96950 
   96951 /************** End of legacy.c **********************************************/
   96952 /************** Begin file loadext.c *****************************************/
   96953 /*
   96954 ** 2006 June 7
   96955 **
   96956 ** The author disclaims copyright to this source code.  In place of
   96957 ** a legal notice, here is a blessing:
   96958 **
   96959 **    May you do good and not evil.
   96960 **    May you find forgiveness for yourself and forgive others.
   96961 **    May you share freely, never taking more than you give.
   96962 **
   96963 *************************************************************************
   96964 ** This file contains code used to dynamically load extensions into
   96965 ** the SQLite library.
   96966 */
   96967 
   96968 #ifndef SQLITE_CORE
   96969   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
   96970 #endif
   96971 /************** Include sqlite3ext.h in the middle of loadext.c **************/
   96972 /************** Begin file sqlite3ext.h **************************************/
   96973 /*
   96974 ** 2006 June 7
   96975 **
   96976 ** The author disclaims copyright to this source code.  In place of
   96977 ** a legal notice, here is a blessing:
   96978 **
   96979 **    May you do good and not evil.
   96980 **    May you find forgiveness for yourself and forgive others.
   96981 **    May you share freely, never taking more than you give.
   96982 **
   96983 *************************************************************************
   96984 ** This header file defines the SQLite interface for use by
   96985 ** shared libraries that want to be imported as extensions into
   96986 ** an SQLite instance.  Shared libraries that intend to be loaded
   96987 ** as extensions by SQLite should #include this file instead of
   96988 ** sqlite3.h.
   96989 */
   96990 #ifndef _SQLITE3EXT_H_
   96991 #define _SQLITE3EXT_H_
   96992 
   96993 typedef struct sqlite3_api_routines sqlite3_api_routines;
   96994 
   96995 /*
   96996 ** The following structure holds pointers to all of the SQLite API
   96997 ** routines.
   96998 **
   96999 ** WARNING:  In order to maintain backwards compatibility, add new
   97000 ** interfaces to the end of this structure only.  If you insert new
   97001 ** interfaces in the middle of this structure, then older different
   97002 ** versions of SQLite will not be able to load each others' shared
   97003 ** libraries!
   97004 */
   97005 struct sqlite3_api_routines {
   97006   void * (*aggregate_context)(sqlite3_context*,int nBytes);
   97007   int  (*aggregate_count)(sqlite3_context*);
   97008   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
   97009   int  (*bind_double)(sqlite3_stmt*,int,double);
   97010   int  (*bind_int)(sqlite3_stmt*,int,int);
   97011   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
   97012   int  (*bind_null)(sqlite3_stmt*,int);
   97013   int  (*bind_parameter_count)(sqlite3_stmt*);
   97014   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
   97015   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
   97016   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
   97017   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
   97018   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
   97019   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
   97020   int  (*busy_timeout)(sqlite3*,int ms);
   97021   int  (*changes)(sqlite3*);
   97022   int  (*close)(sqlite3*);
   97023   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
   97024                            int eTextRep,const char*));
   97025   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
   97026                              int eTextRep,const void*));
   97027   const void * (*column_blob)(sqlite3_stmt*,int iCol);
   97028   int  (*column_bytes)(sqlite3_stmt*,int iCol);
   97029   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
   97030   int  (*column_count)(sqlite3_stmt*pStmt);
   97031   const char * (*column_database_name)(sqlite3_stmt*,int);
   97032   const void * (*column_database_name16)(sqlite3_stmt*,int);
   97033   const char * (*column_decltype)(sqlite3_stmt*,int i);
   97034   const void * (*column_decltype16)(sqlite3_stmt*,int);
   97035   double  (*column_double)(sqlite3_stmt*,int iCol);
   97036   int  (*column_int)(sqlite3_stmt*,int iCol);
   97037   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
   97038   const char * (*column_name)(sqlite3_stmt*,int);
   97039   const void * (*column_name16)(sqlite3_stmt*,int);
   97040   const char * (*column_origin_name)(sqlite3_stmt*,int);
   97041   const void * (*column_origin_name16)(sqlite3_stmt*,int);
   97042   const char * (*column_table_name)(sqlite3_stmt*,int);
   97043   const void * (*column_table_name16)(sqlite3_stmt*,int);
   97044   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
   97045   const void * (*column_text16)(sqlite3_stmt*,int iCol);
   97046   int  (*column_type)(sqlite3_stmt*,int iCol);
   97047   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
   97048   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
   97049   int  (*complete)(const char*sql);
   97050   int  (*complete16)(const void*sql);
   97051   int  (*create_collation)(sqlite3*,const char*,int,void*,
   97052                            int(*)(void*,int,const void*,int,const void*));
   97053   int  (*create_collation16)(sqlite3*,const void*,int,void*,
   97054                              int(*)(void*,int,const void*,int,const void*));
   97055   int  (*create_function)(sqlite3*,const char*,int,int,void*,
   97056                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   97057                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   97058                           void (*xFinal)(sqlite3_context*));
   97059   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
   97060                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   97061                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   97062                             void (*xFinal)(sqlite3_context*));
   97063   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
   97064   int  (*data_count)(sqlite3_stmt*pStmt);
   97065   sqlite3 * (*db_handle)(sqlite3_stmt*);
   97066   int (*declare_vtab)(sqlite3*,const char*);
   97067   int  (*enable_shared_cache)(int);
   97068   int  (*errcode)(sqlite3*db);
   97069   const char * (*errmsg)(sqlite3*);
   97070   const void * (*errmsg16)(sqlite3*);
   97071   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
   97072   int  (*expired)(sqlite3_stmt*);
   97073   int  (*finalize)(sqlite3_stmt*pStmt);
   97074   void  (*free)(void*);
   97075   void  (*free_table)(char**result);
   97076   int  (*get_autocommit)(sqlite3*);
   97077   void * (*get_auxdata)(sqlite3_context*,int);
   97078   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
   97079   int  (*global_recover)(void);
   97080   void  (*interruptx)(sqlite3*);
   97081   sqlite_int64  (*last_insert_rowid)(sqlite3*);
   97082   const char * (*libversion)(void);
   97083   int  (*libversion_number)(void);
   97084   void *(*malloc)(int);
   97085   char * (*mprintf)(const char*,...);
   97086   int  (*open)(const char*,sqlite3**);
   97087   int  (*open16)(const void*,sqlite3**);
   97088   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   97089   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   97090   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
   97091   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
   97092   void *(*realloc)(void*,int);
   97093   int  (*reset)(sqlite3_stmt*pStmt);
   97094   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
   97095   void  (*result_double)(sqlite3_context*,double);
   97096   void  (*result_error)(sqlite3_context*,const char*,int);
   97097   void  (*result_error16)(sqlite3_context*,const void*,int);
   97098   void  (*result_int)(sqlite3_context*,int);
   97099   void  (*result_int64)(sqlite3_context*,sqlite_int64);
   97100   void  (*result_null)(sqlite3_context*);
   97101   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
   97102   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
   97103   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
   97104   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
   97105   void  (*result_value)(sqlite3_context*,sqlite3_value*);
   97106   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
   97107   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
   97108                          const char*,const char*),void*);
   97109   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
   97110   char * (*snprintf)(int,char*,const char*,...);
   97111   int  (*step)(sqlite3_stmt*);
   97112   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
   97113                                 char const**,char const**,int*,int*,int*);
   97114   void  (*thread_cleanup)(void);
   97115   int  (*total_changes)(sqlite3*);
   97116   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
   97117   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
   97118   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
   97119                                          sqlite_int64),void*);
   97120   void * (*user_data)(sqlite3_context*);
   97121   const void * (*value_blob)(sqlite3_value*);
   97122   int  (*value_bytes)(sqlite3_value*);
   97123   int  (*value_bytes16)(sqlite3_value*);
   97124   double  (*value_double)(sqlite3_value*);
   97125   int  (*value_int)(sqlite3_value*);
   97126   sqlite_int64  (*value_int64)(sqlite3_value*);
   97127   int  (*value_numeric_type)(sqlite3_value*);
   97128   const unsigned char * (*value_text)(sqlite3_value*);
   97129   const void * (*value_text16)(sqlite3_value*);
   97130   const void * (*value_text16be)(sqlite3_value*);
   97131   const void * (*value_text16le)(sqlite3_value*);
   97132   int  (*value_type)(sqlite3_value*);
   97133   char *(*vmprintf)(const char*,va_list);
   97134   /* Added ??? */
   97135   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
   97136   /* Added by 3.3.13 */
   97137   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   97138   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   97139   int (*clear_bindings)(sqlite3_stmt*);
   97140   /* Added by 3.4.1 */
   97141   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
   97142                           void (*xDestroy)(void *));
   97143   /* Added by 3.5.0 */
   97144   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
   97145   int (*blob_bytes)(sqlite3_blob*);
   97146   int (*blob_close)(sqlite3_blob*);
   97147   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
   97148                    int,sqlite3_blob**);
   97149   int (*blob_read)(sqlite3_blob*,void*,int,int);
   97150   int (*blob_write)(sqlite3_blob*,const void*,int,int);
   97151   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
   97152                              int(*)(void*,int,const void*,int,const void*),
   97153                              void(*)(void*));
   97154   int (*file_control)(sqlite3*,const char*,int,void*);
   97155   sqlite3_int64 (*memory_highwater)(int);
   97156   sqlite3_int64 (*memory_used)(void);
   97157   sqlite3_mutex *(*mutex_alloc)(int);
   97158   void (*mutex_enter)(sqlite3_mutex*);
   97159   void (*mutex_free)(sqlite3_mutex*);
   97160   void (*mutex_leave)(sqlite3_mutex*);
   97161   int (*mutex_try)(sqlite3_mutex*);
   97162   int (*open_v2)(const char*,sqlite3**,int,const char*);
   97163   int (*release_memory)(int);
   97164   void (*result_error_nomem)(sqlite3_context*);
   97165   void (*result_error_toobig)(sqlite3_context*);
   97166   int (*sleep)(int);
   97167   void (*soft_heap_limit)(int);
   97168   sqlite3_vfs *(*vfs_find)(const char*);
   97169   int (*vfs_register)(sqlite3_vfs*,int);
   97170   int (*vfs_unregister)(sqlite3_vfs*);
   97171   int (*xthreadsafe)(void);
   97172   void (*result_zeroblob)(sqlite3_context*,int);
   97173   void (*result_error_code)(sqlite3_context*,int);
   97174   int (*test_control)(int, ...);
   97175   void (*randomness)(int,void*);
   97176   sqlite3 *(*context_db_handle)(sqlite3_context*);
   97177   int (*extended_result_codes)(sqlite3*,int);
   97178   int (*limit)(sqlite3*,int,int);
   97179   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
   97180   const char *(*sql)(sqlite3_stmt*);
   97181   int (*status)(int,int*,int*,int);
   97182   int (*backup_finish)(sqlite3_backup*);
   97183   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
   97184   int (*backup_pagecount)(sqlite3_backup*);
   97185   int (*backup_remaining)(sqlite3_backup*);
   97186   int (*backup_step)(sqlite3_backup*,int);
   97187   const char *(*compileoption_get)(int);
   97188   int (*compileoption_used)(const char*);
   97189   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
   97190                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   97191                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   97192                             void (*xFinal)(sqlite3_context*),
   97193                             void(*xDestroy)(void*));
   97194   int (*db_config)(sqlite3*,int,...);
   97195   sqlite3_mutex *(*db_mutex)(sqlite3*);
   97196   int (*db_status)(sqlite3*,int,int*,int*,int);
   97197   int (*extended_errcode)(sqlite3*);
   97198   void (*log)(int,const char*,...);
   97199   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
   97200   const char *(*sourceid)(void);
   97201   int (*stmt_status)(sqlite3_stmt*,int,int);
   97202   int (*strnicmp)(const char*,const char*,int);
   97203   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
   97204   int (*wal_autocheckpoint)(sqlite3*,int);
   97205   int (*wal_checkpoint)(sqlite3*,const char*);
   97206   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
   97207   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
   97208   int (*vtab_config)(sqlite3*,int op,...);
   97209   int (*vtab_on_conflict)(sqlite3*);
   97210   /* Version 3.7.16 and later */
   97211   int (*close_v2)(sqlite3*);
   97212   const char *(*db_filename)(sqlite3*,const char*);
   97213   int (*db_readonly)(sqlite3*,const char*);
   97214   int (*db_release_memory)(sqlite3*);
   97215   const char *(*errstr)(int);
   97216   int (*stmt_busy)(sqlite3_stmt*);
   97217   int (*stmt_readonly)(sqlite3_stmt*);
   97218   int (*stricmp)(const char*,const char*);
   97219   int (*uri_boolean)(const char*,const char*,int);
   97220   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
   97221   const char *(*uri_parameter)(const char*,const char*);
   97222   char *(*vsnprintf)(int,char*,const char*,va_list);
   97223   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
   97224 };
   97225 
   97226 /*
   97227 ** The following macros redefine the API routines so that they are
   97228 ** redirected throught the global sqlite3_api structure.
   97229 **
   97230 ** This header file is also used by the loadext.c source file
   97231 ** (part of the main SQLite library - not an extension) so that
   97232 ** it can get access to the sqlite3_api_routines structure
   97233 ** definition.  But the main library does not want to redefine
   97234 ** the API.  So the redefinition macros are only valid if the
   97235 ** SQLITE_CORE macros is undefined.
   97236 */
   97237 #ifndef SQLITE_CORE
   97238 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
   97239 #ifndef SQLITE_OMIT_DEPRECATED
   97240 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
   97241 #endif
   97242 #define sqlite3_bind_blob              sqlite3_api->bind_blob
   97243 #define sqlite3_bind_double            sqlite3_api->bind_double
   97244 #define sqlite3_bind_int               sqlite3_api->bind_int
   97245 #define sqlite3_bind_int64             sqlite3_api->bind_int64
   97246 #define sqlite3_bind_null              sqlite3_api->bind_null
   97247 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
   97248 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
   97249 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
   97250 #define sqlite3_bind_text              sqlite3_api->bind_text
   97251 #define sqlite3_bind_text16            sqlite3_api->bind_text16
   97252 #define sqlite3_bind_value             sqlite3_api->bind_value
   97253 #define sqlite3_busy_handler           sqlite3_api->busy_handler
   97254 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
   97255 #define sqlite3_changes                sqlite3_api->changes
   97256 #define sqlite3_close                  sqlite3_api->close
   97257 #define sqlite3_collation_needed       sqlite3_api->collation_needed
   97258 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
   97259 #define sqlite3_column_blob            sqlite3_api->column_blob
   97260 #define sqlite3_column_bytes           sqlite3_api->column_bytes
   97261 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
   97262 #define sqlite3_column_count           sqlite3_api->column_count
   97263 #define sqlite3_column_database_name   sqlite3_api->column_database_name
   97264 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
   97265 #define sqlite3_column_decltype        sqlite3_api->column_decltype
   97266 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
   97267 #define sqlite3_column_double          sqlite3_api->column_double
   97268 #define sqlite3_column_int             sqlite3_api->column_int
   97269 #define sqlite3_column_int64           sqlite3_api->column_int64
   97270 #define sqlite3_column_name            sqlite3_api->column_name
   97271 #define sqlite3_column_name16          sqlite3_api->column_name16
   97272 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
   97273 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
   97274 #define sqlite3_column_table_name      sqlite3_api->column_table_name
   97275 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
   97276 #define sqlite3_column_text            sqlite3_api->column_text
   97277 #define sqlite3_column_text16          sqlite3_api->column_text16
   97278 #define sqlite3_column_type            sqlite3_api->column_type
   97279 #define sqlite3_column_value           sqlite3_api->column_value
   97280 #define sqlite3_commit_hook            sqlite3_api->commit_hook
   97281 #define sqlite3_complete               sqlite3_api->complete
   97282 #define sqlite3_complete16             sqlite3_api->complete16
   97283 #define sqlite3_create_collation       sqlite3_api->create_collation
   97284 #define sqlite3_create_collation16     sqlite3_api->create_collation16
   97285 #define sqlite3_create_function        sqlite3_api->create_function
   97286 #define sqlite3_create_function16      sqlite3_api->create_function16
   97287 #define sqlite3_create_module          sqlite3_api->create_module
   97288 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
   97289 #define sqlite3_data_count             sqlite3_api->data_count
   97290 #define sqlite3_db_handle              sqlite3_api->db_handle
   97291 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
   97292 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
   97293 #define sqlite3_errcode                sqlite3_api->errcode
   97294 #define sqlite3_errmsg                 sqlite3_api->errmsg
   97295 #define sqlite3_errmsg16               sqlite3_api->errmsg16
   97296 #define sqlite3_exec                   sqlite3_api->exec
   97297 #ifndef SQLITE_OMIT_DEPRECATED
   97298 #define sqlite3_expired                sqlite3_api->expired
   97299 #endif
   97300 #define sqlite3_finalize               sqlite3_api->finalize
   97301 #define sqlite3_free                   sqlite3_api->free
   97302 #define sqlite3_free_table             sqlite3_api->free_table
   97303 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
   97304 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
   97305 #define sqlite3_get_table              sqlite3_api->get_table
   97306 #ifndef SQLITE_OMIT_DEPRECATED
   97307 #define sqlite3_global_recover         sqlite3_api->global_recover
   97308 #endif
   97309 #define sqlite3_interrupt              sqlite3_api->interruptx
   97310 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
   97311 #define sqlite3_libversion             sqlite3_api->libversion
   97312 #define sqlite3_libversion_number      sqlite3_api->libversion_number
   97313 #define sqlite3_malloc                 sqlite3_api->malloc
   97314 #define sqlite3_mprintf                sqlite3_api->mprintf
   97315 #define sqlite3_open                   sqlite3_api->open
   97316 #define sqlite3_open16                 sqlite3_api->open16
   97317 #define sqlite3_prepare                sqlite3_api->prepare
   97318 #define sqlite3_prepare16              sqlite3_api->prepare16
   97319 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   97320 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   97321 #define sqlite3_profile                sqlite3_api->profile
   97322 #define sqlite3_progress_handler       sqlite3_api->progress_handler
   97323 #define sqlite3_realloc                sqlite3_api->realloc
   97324 #define sqlite3_reset                  sqlite3_api->reset
   97325 #define sqlite3_result_blob            sqlite3_api->result_blob
   97326 #define sqlite3_result_double          sqlite3_api->result_double
   97327 #define sqlite3_result_error           sqlite3_api->result_error
   97328 #define sqlite3_result_error16         sqlite3_api->result_error16
   97329 #define sqlite3_result_int             sqlite3_api->result_int
   97330 #define sqlite3_result_int64           sqlite3_api->result_int64
   97331 #define sqlite3_result_null            sqlite3_api->result_null
   97332 #define sqlite3_result_text            sqlite3_api->result_text
   97333 #define sqlite3_result_text16          sqlite3_api->result_text16
   97334 #define sqlite3_result_text16be        sqlite3_api->result_text16be
   97335 #define sqlite3_result_text16le        sqlite3_api->result_text16le
   97336 #define sqlite3_result_value           sqlite3_api->result_value
   97337 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
   97338 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
   97339 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
   97340 #define sqlite3_snprintf               sqlite3_api->snprintf
   97341 #define sqlite3_step                   sqlite3_api->step
   97342 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
   97343 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
   97344 #define sqlite3_total_changes          sqlite3_api->total_changes
   97345 #define sqlite3_trace                  sqlite3_api->trace
   97346 #ifndef SQLITE_OMIT_DEPRECATED
   97347 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
   97348 #endif
   97349 #define sqlite3_update_hook            sqlite3_api->update_hook
   97350 #define sqlite3_user_data              sqlite3_api->user_data
   97351 #define sqlite3_value_blob             sqlite3_api->value_blob
   97352 #define sqlite3_value_bytes            sqlite3_api->value_bytes
   97353 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
   97354 #define sqlite3_value_double           sqlite3_api->value_double
   97355 #define sqlite3_value_int              sqlite3_api->value_int
   97356 #define sqlite3_value_int64            sqlite3_api->value_int64
   97357 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
   97358 #define sqlite3_value_text             sqlite3_api->value_text
   97359 #define sqlite3_value_text16           sqlite3_api->value_text16
   97360 #define sqlite3_value_text16be         sqlite3_api->value_text16be
   97361 #define sqlite3_value_text16le         sqlite3_api->value_text16le
   97362 #define sqlite3_value_type             sqlite3_api->value_type
   97363 #define sqlite3_vmprintf               sqlite3_api->vmprintf
   97364 #define sqlite3_overload_function      sqlite3_api->overload_function
   97365 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   97366 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   97367 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
   97368 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
   97369 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
   97370 #define sqlite3_blob_close             sqlite3_api->blob_close
   97371 #define sqlite3_blob_open              sqlite3_api->blob_open
   97372 #define sqlite3_blob_read              sqlite3_api->blob_read
   97373 #define sqlite3_blob_write             sqlite3_api->blob_write
   97374 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
   97375 #define sqlite3_file_control           sqlite3_api->file_control
   97376 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
   97377 #define sqlite3_memory_used            sqlite3_api->memory_used
   97378 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
   97379 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
   97380 #define sqlite3_mutex_free             sqlite3_api->mutex_free
   97381 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
   97382 #define sqlite3_mutex_try              sqlite3_api->mutex_try
   97383 #define sqlite3_open_v2                sqlite3_api->open_v2
   97384 #define sqlite3_release_memory         sqlite3_api->release_memory
   97385 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
   97386 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
   97387 #define sqlite3_sleep                  sqlite3_api->sleep
   97388 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
   97389 #define sqlite3_vfs_find               sqlite3_api->vfs_find
   97390 #define sqlite3_vfs_register           sqlite3_api->vfs_register
   97391 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
   97392 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
   97393 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
   97394 #define sqlite3_result_error_code      sqlite3_api->result_error_code
   97395 #define sqlite3_test_control           sqlite3_api->test_control
   97396 #define sqlite3_randomness             sqlite3_api->randomness
   97397 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
   97398 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
   97399 #define sqlite3_limit                  sqlite3_api->limit
   97400 #define sqlite3_next_stmt              sqlite3_api->next_stmt
   97401 #define sqlite3_sql                    sqlite3_api->sql
   97402 #define sqlite3_status                 sqlite3_api->status
   97403 #define sqlite3_backup_finish          sqlite3_api->backup_finish
   97404 #define sqlite3_backup_init            sqlite3_api->backup_init
   97405 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
   97406 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
   97407 #define sqlite3_backup_step            sqlite3_api->backup_step
   97408 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
   97409 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
   97410 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
   97411 #define sqlite3_db_config              sqlite3_api->db_config
   97412 #define sqlite3_db_mutex               sqlite3_api->db_mutex
   97413 #define sqlite3_db_status              sqlite3_api->db_status
   97414 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
   97415 #define sqlite3_log                    sqlite3_api->log
   97416 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
   97417 #define sqlite3_sourceid               sqlite3_api->sourceid
   97418 #define sqlite3_stmt_status            sqlite3_api->stmt_status
   97419 #define sqlite3_strnicmp               sqlite3_api->strnicmp
   97420 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
   97421 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
   97422 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
   97423 #define sqlite3_wal_hook               sqlite3_api->wal_hook
   97424 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
   97425 #define sqlite3_vtab_config            sqlite3_api->vtab_config
   97426 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
   97427 /* Version 3.7.16 and later */
   97428 #define sqlite3_close_v2               sqlite3_api->close_v2
   97429 #define sqlite3_db_filename            sqlite3_api->db_filename
   97430 #define sqlite3_db_readonly            sqlite3_api->db_readonly
   97431 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
   97432 #define sqlite3_errstr                 sqlite3_api->errstr
   97433 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
   97434 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
   97435 #define sqlite3_stricmp                sqlite3_api->stricmp
   97436 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
   97437 #define sqlite3_uri_int64              sqlite3_api->uri_int64
   97438 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
   97439 #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
   97440 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
   97441 #endif /* SQLITE_CORE */
   97442 
   97443 #ifndef SQLITE_CORE
   97444   /* This case when the file really is being compiled as a loadable
   97445   ** extension */
   97446 # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
   97447 # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
   97448 # define SQLITE_EXTENSION_INIT3     \
   97449     extern const sqlite3_api_routines *sqlite3_api;
   97450 #else
   97451   /* This case when the file is being statically linked into the
   97452   ** application */
   97453 # define SQLITE_EXTENSION_INIT1     /*no-op*/
   97454 # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
   97455 # define SQLITE_EXTENSION_INIT3     /*no-op*/
   97456 #endif
   97457 
   97458 #endif /* _SQLITE3EXT_H_ */
   97459 
   97460 /************** End of sqlite3ext.h ******************************************/
   97461 /************** Continuing where we left off in loadext.c ********************/
   97462 /* #include <string.h> */
   97463 
   97464 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   97465 
   97466 /*
   97467 ** Some API routines are omitted when various features are
   97468 ** excluded from a build of SQLite.  Substitute a NULL pointer
   97469 ** for any missing APIs.
   97470 */
   97471 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   97472 # define sqlite3_column_database_name   0
   97473 # define sqlite3_column_database_name16 0
   97474 # define sqlite3_column_table_name      0
   97475 # define sqlite3_column_table_name16    0
   97476 # define sqlite3_column_origin_name     0
   97477 # define sqlite3_column_origin_name16   0
   97478 # define sqlite3_table_column_metadata  0
   97479 #endif
   97480 
   97481 #ifdef SQLITE_OMIT_AUTHORIZATION
   97482 # define sqlite3_set_authorizer         0
   97483 #endif
   97484 
   97485 #ifdef SQLITE_OMIT_UTF16
   97486 # define sqlite3_bind_text16            0
   97487 # define sqlite3_collation_needed16     0
   97488 # define sqlite3_column_decltype16      0
   97489 # define sqlite3_column_name16          0
   97490 # define sqlite3_column_text16          0
   97491 # define sqlite3_complete16             0
   97492 # define sqlite3_create_collation16     0
   97493 # define sqlite3_create_function16      0
   97494 # define sqlite3_errmsg16               0
   97495 # define sqlite3_open16                 0
   97496 # define sqlite3_prepare16              0
   97497 # define sqlite3_prepare16_v2           0
   97498 # define sqlite3_result_error16         0
   97499 # define sqlite3_result_text16          0
   97500 # define sqlite3_result_text16be        0
   97501 # define sqlite3_result_text16le        0
   97502 # define sqlite3_value_text16           0
   97503 # define sqlite3_value_text16be         0
   97504 # define sqlite3_value_text16le         0
   97505 # define sqlite3_column_database_name16 0
   97506 # define sqlite3_column_table_name16    0
   97507 # define sqlite3_column_origin_name16   0
   97508 #endif
   97509 
   97510 #ifdef SQLITE_OMIT_COMPLETE
   97511 # define sqlite3_complete 0
   97512 # define sqlite3_complete16 0
   97513 #endif
   97514 
   97515 #ifdef SQLITE_OMIT_DECLTYPE
   97516 # define sqlite3_column_decltype16      0
   97517 # define sqlite3_column_decltype        0
   97518 #endif
   97519 
   97520 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   97521 # define sqlite3_progress_handler 0
   97522 #endif
   97523 
   97524 #ifdef SQLITE_OMIT_VIRTUALTABLE
   97525 # define sqlite3_create_module 0
   97526 # define sqlite3_create_module_v2 0
   97527 # define sqlite3_declare_vtab 0
   97528 # define sqlite3_vtab_config 0
   97529 # define sqlite3_vtab_on_conflict 0
   97530 #endif
   97531 
   97532 #ifdef SQLITE_OMIT_SHARED_CACHE
   97533 # define sqlite3_enable_shared_cache 0
   97534 #endif
   97535 
   97536 #ifdef SQLITE_OMIT_TRACE
   97537 # define sqlite3_profile       0
   97538 # define sqlite3_trace         0
   97539 #endif
   97540 
   97541 #ifdef SQLITE_OMIT_GET_TABLE
   97542 # define sqlite3_free_table    0
   97543 # define sqlite3_get_table     0
   97544 #endif
   97545 
   97546 #ifdef SQLITE_OMIT_INCRBLOB
   97547 #define sqlite3_bind_zeroblob  0
   97548 #define sqlite3_blob_bytes     0
   97549 #define sqlite3_blob_close     0
   97550 #define sqlite3_blob_open      0
   97551 #define sqlite3_blob_read      0
   97552 #define sqlite3_blob_write     0
   97553 #define sqlite3_blob_reopen    0
   97554 #endif
   97555 
   97556 /*
   97557 ** The following structure contains pointers to all SQLite API routines.
   97558 ** A pointer to this structure is passed into extensions when they are
   97559 ** loaded so that the extension can make calls back into the SQLite
   97560 ** library.
   97561 **
   97562 ** When adding new APIs, add them to the bottom of this structure
   97563 ** in order to preserve backwards compatibility.
   97564 **
   97565 ** Extensions that use newer APIs should first call the
   97566 ** sqlite3_libversion_number() to make sure that the API they
   97567 ** intend to use is supported by the library.  Extensions should
   97568 ** also check to make sure that the pointer to the function is
   97569 ** not NULL before calling it.
   97570 */
   97571 static const sqlite3_api_routines sqlite3Apis = {
   97572   sqlite3_aggregate_context,
   97573 #ifndef SQLITE_OMIT_DEPRECATED
   97574   sqlite3_aggregate_count,
   97575 #else
   97576   0,
   97577 #endif
   97578   sqlite3_bind_blob,
   97579   sqlite3_bind_double,
   97580   sqlite3_bind_int,
   97581   sqlite3_bind_int64,
   97582   sqlite3_bind_null,
   97583   sqlite3_bind_parameter_count,
   97584   sqlite3_bind_parameter_index,
   97585   sqlite3_bind_parameter_name,
   97586   sqlite3_bind_text,
   97587   sqlite3_bind_text16,
   97588   sqlite3_bind_value,
   97589   sqlite3_busy_handler,
   97590   sqlite3_busy_timeout,
   97591   sqlite3_changes,
   97592   sqlite3_close,
   97593   sqlite3_collation_needed,
   97594   sqlite3_collation_needed16,
   97595   sqlite3_column_blob,
   97596   sqlite3_column_bytes,
   97597   sqlite3_column_bytes16,
   97598   sqlite3_column_count,
   97599   sqlite3_column_database_name,
   97600   sqlite3_column_database_name16,
   97601   sqlite3_column_decltype,
   97602   sqlite3_column_decltype16,
   97603   sqlite3_column_double,
   97604   sqlite3_column_int,
   97605   sqlite3_column_int64,
   97606   sqlite3_column_name,
   97607   sqlite3_column_name16,
   97608   sqlite3_column_origin_name,
   97609   sqlite3_column_origin_name16,
   97610   sqlite3_column_table_name,
   97611   sqlite3_column_table_name16,
   97612   sqlite3_column_text,
   97613   sqlite3_column_text16,
   97614   sqlite3_column_type,
   97615   sqlite3_column_value,
   97616   sqlite3_commit_hook,
   97617   sqlite3_complete,
   97618   sqlite3_complete16,
   97619   sqlite3_create_collation,
   97620   sqlite3_create_collation16,
   97621   sqlite3_create_function,
   97622   sqlite3_create_function16,
   97623   sqlite3_create_module,
   97624   sqlite3_data_count,
   97625   sqlite3_db_handle,
   97626   sqlite3_declare_vtab,
   97627   sqlite3_enable_shared_cache,
   97628   sqlite3_errcode,
   97629   sqlite3_errmsg,
   97630   sqlite3_errmsg16,
   97631   sqlite3_exec,
   97632 #ifndef SQLITE_OMIT_DEPRECATED
   97633   sqlite3_expired,
   97634 #else
   97635   0,
   97636 #endif
   97637   sqlite3_finalize,
   97638   sqlite3_free,
   97639   sqlite3_free_table,
   97640   sqlite3_get_autocommit,
   97641   sqlite3_get_auxdata,
   97642   sqlite3_get_table,
   97643   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
   97644   sqlite3_interrupt,
   97645   sqlite3_last_insert_rowid,
   97646   sqlite3_libversion,
   97647   sqlite3_libversion_number,
   97648   sqlite3_malloc,
   97649   sqlite3_mprintf,
   97650   sqlite3_open,
   97651   sqlite3_open16,
   97652   sqlite3_prepare,
   97653   sqlite3_prepare16,
   97654   sqlite3_profile,
   97655   sqlite3_progress_handler,
   97656   sqlite3_realloc,
   97657   sqlite3_reset,
   97658   sqlite3_result_blob,
   97659   sqlite3_result_double,
   97660   sqlite3_result_error,
   97661   sqlite3_result_error16,
   97662   sqlite3_result_int,
   97663   sqlite3_result_int64,
   97664   sqlite3_result_null,
   97665   sqlite3_result_text,
   97666   sqlite3_result_text16,
   97667   sqlite3_result_text16be,
   97668   sqlite3_result_text16le,
   97669   sqlite3_result_value,
   97670   sqlite3_rollback_hook,
   97671   sqlite3_set_authorizer,
   97672   sqlite3_set_auxdata,
   97673   sqlite3_snprintf,
   97674   sqlite3_step,
   97675   sqlite3_table_column_metadata,
   97676 #ifndef SQLITE_OMIT_DEPRECATED
   97677   sqlite3_thread_cleanup,
   97678 #else
   97679   0,
   97680 #endif
   97681   sqlite3_total_changes,
   97682   sqlite3_trace,
   97683 #ifndef SQLITE_OMIT_DEPRECATED
   97684   sqlite3_transfer_bindings,
   97685 #else
   97686   0,
   97687 #endif
   97688   sqlite3_update_hook,
   97689   sqlite3_user_data,
   97690   sqlite3_value_blob,
   97691   sqlite3_value_bytes,
   97692   sqlite3_value_bytes16,
   97693   sqlite3_value_double,
   97694   sqlite3_value_int,
   97695   sqlite3_value_int64,
   97696   sqlite3_value_numeric_type,
   97697   sqlite3_value_text,
   97698   sqlite3_value_text16,
   97699   sqlite3_value_text16be,
   97700   sqlite3_value_text16le,
   97701   sqlite3_value_type,
   97702   sqlite3_vmprintf,
   97703   /*
   97704   ** The original API set ends here.  All extensions can call any
   97705   ** of the APIs above provided that the pointer is not NULL.  But
   97706   ** before calling APIs that follow, extension should check the
   97707   ** sqlite3_libversion_number() to make sure they are dealing with
   97708   ** a library that is new enough to support that API.
   97709   *************************************************************************
   97710   */
   97711   sqlite3_overload_function,
   97712 
   97713   /*
   97714   ** Added after 3.3.13
   97715   */
   97716   sqlite3_prepare_v2,
   97717   sqlite3_prepare16_v2,
   97718   sqlite3_clear_bindings,
   97719 
   97720   /*
   97721   ** Added for 3.4.1
   97722   */
   97723   sqlite3_create_module_v2,
   97724 
   97725   /*
   97726   ** Added for 3.5.0
   97727   */
   97728   sqlite3_bind_zeroblob,
   97729   sqlite3_blob_bytes,
   97730   sqlite3_blob_close,
   97731   sqlite3_blob_open,
   97732   sqlite3_blob_read,
   97733   sqlite3_blob_write,
   97734   sqlite3_create_collation_v2,
   97735   sqlite3_file_control,
   97736   sqlite3_memory_highwater,
   97737   sqlite3_memory_used,
   97738 #ifdef SQLITE_MUTEX_OMIT
   97739   0,
   97740   0,
   97741   0,
   97742   0,
   97743   0,
   97744 #else
   97745   sqlite3_mutex_alloc,
   97746   sqlite3_mutex_enter,
   97747   sqlite3_mutex_free,
   97748   sqlite3_mutex_leave,
   97749   sqlite3_mutex_try,
   97750 #endif
   97751   sqlite3_open_v2,
   97752   sqlite3_release_memory,
   97753   sqlite3_result_error_nomem,
   97754   sqlite3_result_error_toobig,
   97755   sqlite3_sleep,
   97756   sqlite3_soft_heap_limit,
   97757   sqlite3_vfs_find,
   97758   sqlite3_vfs_register,
   97759   sqlite3_vfs_unregister,
   97760 
   97761   /*
   97762   ** Added for 3.5.8
   97763   */
   97764   sqlite3_threadsafe,
   97765   sqlite3_result_zeroblob,
   97766   sqlite3_result_error_code,
   97767   sqlite3_test_control,
   97768   sqlite3_randomness,
   97769   sqlite3_context_db_handle,
   97770 
   97771   /*
   97772   ** Added for 3.6.0
   97773   */
   97774   sqlite3_extended_result_codes,
   97775   sqlite3_limit,
   97776   sqlite3_next_stmt,
   97777   sqlite3_sql,
   97778   sqlite3_status,
   97779 
   97780   /*
   97781   ** Added for 3.7.4
   97782   */
   97783   sqlite3_backup_finish,
   97784   sqlite3_backup_init,
   97785   sqlite3_backup_pagecount,
   97786   sqlite3_backup_remaining,
   97787   sqlite3_backup_step,
   97788 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   97789   sqlite3_compileoption_get,
   97790   sqlite3_compileoption_used,
   97791 #else
   97792   0,
   97793   0,
   97794 #endif
   97795   sqlite3_create_function_v2,
   97796   sqlite3_db_config,
   97797   sqlite3_db_mutex,
   97798   sqlite3_db_status,
   97799   sqlite3_extended_errcode,
   97800   sqlite3_log,
   97801   sqlite3_soft_heap_limit64,
   97802   sqlite3_sourceid,
   97803   sqlite3_stmt_status,
   97804   sqlite3_strnicmp,
   97805 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   97806   sqlite3_unlock_notify,
   97807 #else
   97808   0,
   97809 #endif
   97810 #ifndef SQLITE_OMIT_WAL
   97811   sqlite3_wal_autocheckpoint,
   97812   sqlite3_wal_checkpoint,
   97813   sqlite3_wal_hook,
   97814 #else
   97815   0,
   97816   0,
   97817   0,
   97818 #endif
   97819   sqlite3_blob_reopen,
   97820   sqlite3_vtab_config,
   97821   sqlite3_vtab_on_conflict,
   97822   sqlite3_close_v2,
   97823   sqlite3_db_filename,
   97824   sqlite3_db_readonly,
   97825   sqlite3_db_release_memory,
   97826   sqlite3_errstr,
   97827   sqlite3_stmt_busy,
   97828   sqlite3_stmt_readonly,
   97829   sqlite3_stricmp,
   97830   sqlite3_uri_boolean,
   97831   sqlite3_uri_int64,
   97832   sqlite3_uri_parameter,
   97833   sqlite3_vsnprintf,
   97834   sqlite3_wal_checkpoint_v2
   97835 };
   97836 
   97837 /*
   97838 ** Attempt to load an SQLite extension library contained in the file
   97839 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
   97840 ** default entry point name (sqlite3_extension_init) is used.  Use
   97841 ** of the default name is recommended.
   97842 **
   97843 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
   97844 **
   97845 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
   97846 ** error message text.  The calling function should free this memory
   97847 ** by calling sqlite3DbFree(db, ).
   97848 */
   97849 static int sqlite3LoadExtension(
   97850   sqlite3 *db,          /* Load the extension into this database connection */
   97851   const char *zFile,    /* Name of the shared library containing extension */
   97852   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   97853   char **pzErrMsg       /* Put error message here if not 0 */
   97854 ){
   97855   sqlite3_vfs *pVfs = db->pVfs;
   97856   void *handle;
   97857   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   97858   char *zErrmsg = 0;
   97859   const char *zEntry;
   97860   char *zAltEntry = 0;
   97861   void **aHandle;
   97862   int nMsg = 300 + sqlite3Strlen30(zFile);
   97863   int ii;
   97864 
   97865   /* Shared library endings to try if zFile cannot be loaded as written */
   97866   static const char *azEndings[] = {
   97867 #if SQLITE_OS_WIN
   97868      "dll"
   97869 #elif defined(__APPLE__)
   97870      "dylib"
   97871 #else
   97872      "so"
   97873 #endif
   97874   };
   97875 
   97876 
   97877   if( pzErrMsg ) *pzErrMsg = 0;
   97878 
   97879   /* Ticket #1863.  To avoid a creating security problems for older
   97880   ** applications that relink against newer versions of SQLite, the
   97881   ** ability to run load_extension is turned off by default.  One
   97882   ** must call sqlite3_enable_load_extension() to turn on extension
   97883   ** loading.  Otherwise you get the following error.
   97884   */
   97885   if( (db->flags & SQLITE_LoadExtension)==0 ){
   97886     if( pzErrMsg ){
   97887       *pzErrMsg = sqlite3_mprintf("not authorized");
   97888     }
   97889     return SQLITE_ERROR;
   97890   }
   97891 
   97892   zEntry = zProc ? zProc : "sqlite3_extension_init";
   97893 
   97894   handle = sqlite3OsDlOpen(pVfs, zFile);
   97895 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
   97896   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
   97897     char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
   97898     if( zAltFile==0 ) return SQLITE_NOMEM;
   97899     handle = sqlite3OsDlOpen(pVfs, zAltFile);
   97900     sqlite3_free(zAltFile);
   97901   }
   97902 #endif
   97903   if( handle==0 ){
   97904     if( pzErrMsg ){
   97905       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   97906       if( zErrmsg ){
   97907         sqlite3_snprintf(nMsg, zErrmsg,
   97908             "unable to open shared library [%s]", zFile);
   97909         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   97910       }
   97911     }
   97912     return SQLITE_ERROR;
   97913   }
   97914   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   97915                    sqlite3OsDlSym(pVfs, handle, zEntry);
   97916 
   97917   /* If no entry point was specified and the default legacy
   97918   ** entry point name "sqlite3_extension_init" was not found, then
   97919   ** construct an entry point name "sqlite3_X_init" where the X is
   97920   ** replaced by the lowercase value of every ASCII alphabetic
   97921   ** character in the filename after the last "/" upto the first ".",
   97922   ** and eliding the first three characters if they are "lib".
   97923   ** Examples:
   97924   **
   97925   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
   97926   **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
   97927   */
   97928   if( xInit==0 && zProc==0 ){
   97929     int iFile, iEntry, c;
   97930     int ncFile = sqlite3Strlen30(zFile);
   97931     zAltEntry = sqlite3_malloc(ncFile+30);
   97932     if( zAltEntry==0 ){
   97933       sqlite3OsDlClose(pVfs, handle);
   97934       return SQLITE_NOMEM;
   97935     }
   97936     memcpy(zAltEntry, "sqlite3_", 8);
   97937     for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
   97938     iFile++;
   97939     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
   97940     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
   97941       if( sqlite3Isalpha(c) ){
   97942         zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
   97943       }
   97944     }
   97945     memcpy(zAltEntry+iEntry, "_init", 6);
   97946     zEntry = zAltEntry;
   97947     xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   97948                      sqlite3OsDlSym(pVfs, handle, zEntry);
   97949   }
   97950   if( xInit==0 ){
   97951     if( pzErrMsg ){
   97952       nMsg += sqlite3Strlen30(zEntry);
   97953       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   97954       if( zErrmsg ){
   97955         sqlite3_snprintf(nMsg, zErrmsg,
   97956             "no entry point [%s] in shared library [%s]", zEntry, zFile);
   97957         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   97958       }
   97959     }
   97960     sqlite3OsDlClose(pVfs, handle);
   97961     sqlite3_free(zAltEntry);
   97962     return SQLITE_ERROR;
   97963   }
   97964   sqlite3_free(zAltEntry);
   97965   if( xInit(db, &zErrmsg, &sqlite3Apis) ){
   97966     if( pzErrMsg ){
   97967       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
   97968     }
   97969     sqlite3_free(zErrmsg);
   97970     sqlite3OsDlClose(pVfs, handle);
   97971     return SQLITE_ERROR;
   97972   }
   97973 
   97974   /* Append the new shared library handle to the db->aExtension array. */
   97975   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
   97976   if( aHandle==0 ){
   97977     return SQLITE_NOMEM;
   97978   }
   97979   if( db->nExtension>0 ){
   97980     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
   97981   }
   97982   sqlite3DbFree(db, db->aExtension);
   97983   db->aExtension = aHandle;
   97984 
   97985   db->aExtension[db->nExtension++] = handle;
   97986   return SQLITE_OK;
   97987 }
   97988 SQLITE_API int sqlite3_load_extension(
   97989   sqlite3 *db,          /* Load the extension into this database connection */
   97990   const char *zFile,    /* Name of the shared library containing extension */
   97991   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   97992   char **pzErrMsg       /* Put error message here if not 0 */
   97993 ){
   97994   int rc;
   97995   sqlite3_mutex_enter(db->mutex);
   97996   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
   97997   rc = sqlite3ApiExit(db, rc);
   97998   sqlite3_mutex_leave(db->mutex);
   97999   return rc;
   98000 }
   98001 
   98002 /*
   98003 ** Call this routine when the database connection is closing in order
   98004 ** to clean up loaded extensions
   98005 */
   98006 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
   98007   int i;
   98008   assert( sqlite3_mutex_held(db->mutex) );
   98009   for(i=0; i<db->nExtension; i++){
   98010     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
   98011   }
   98012   sqlite3DbFree(db, db->aExtension);
   98013 }
   98014 
   98015 /*
   98016 ** Enable or disable extension loading.  Extension loading is disabled by
   98017 ** default so as not to open security holes in older applications.
   98018 */
   98019 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
   98020   sqlite3_mutex_enter(db->mutex);
   98021   if( onoff ){
   98022     db->flags |= SQLITE_LoadExtension;
   98023   }else{
   98024     db->flags &= ~SQLITE_LoadExtension;
   98025   }
   98026   sqlite3_mutex_leave(db->mutex);
   98027   return SQLITE_OK;
   98028 }
   98029 
   98030 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   98031 
   98032 /*
   98033 ** The auto-extension code added regardless of whether or not extension
   98034 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
   98035 ** code if regular extension loading is not available.  This is that
   98036 ** dummy pointer.
   98037 */
   98038 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   98039 static const sqlite3_api_routines sqlite3Apis = { 0 };
   98040 #endif
   98041 
   98042 
   98043 /*
   98044 ** The following object holds the list of automatically loaded
   98045 ** extensions.
   98046 **
   98047 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
   98048 ** mutex must be held while accessing this list.
   98049 */
   98050 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
   98051 static SQLITE_WSD struct sqlite3AutoExtList {
   98052   int nExt;              /* Number of entries in aExt[] */
   98053   void (**aExt)(void);   /* Pointers to the extension init functions */
   98054 } sqlite3Autoext = { 0, 0 };
   98055 
   98056 /* The "wsdAutoext" macro will resolve to the autoextension
   98057 ** state vector.  If writable static data is unsupported on the target,
   98058 ** we have to locate the state vector at run-time.  In the more common
   98059 ** case where writable static data is supported, wsdStat can refer directly
   98060 ** to the "sqlite3Autoext" state vector declared above.
   98061 */
   98062 #ifdef SQLITE_OMIT_WSD
   98063 # define wsdAutoextInit \
   98064   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
   98065 # define wsdAutoext x[0]
   98066 #else
   98067 # define wsdAutoextInit
   98068 # define wsdAutoext sqlite3Autoext
   98069 #endif
   98070 
   98071 
   98072 /*
   98073 ** Register a statically linked extension that is automatically
   98074 ** loaded by every new database connection.
   98075 */
   98076 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
   98077   int rc = SQLITE_OK;
   98078 #ifndef SQLITE_OMIT_AUTOINIT
   98079   rc = sqlite3_initialize();
   98080   if( rc ){
   98081     return rc;
   98082   }else
   98083 #endif
   98084   {
   98085     int i;
   98086 #if SQLITE_THREADSAFE
   98087     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   98088 #endif
   98089     wsdAutoextInit;
   98090     sqlite3_mutex_enter(mutex);
   98091     for(i=0; i<wsdAutoext.nExt; i++){
   98092       if( wsdAutoext.aExt[i]==xInit ) break;
   98093     }
   98094     if( i==wsdAutoext.nExt ){
   98095       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
   98096       void (**aNew)(void);
   98097       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
   98098       if( aNew==0 ){
   98099         rc = SQLITE_NOMEM;
   98100       }else{
   98101         wsdAutoext.aExt = aNew;
   98102         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
   98103         wsdAutoext.nExt++;
   98104       }
   98105     }
   98106     sqlite3_mutex_leave(mutex);
   98107     assert( (rc&0xff)==rc );
   98108     return rc;
   98109   }
   98110 }
   98111 
   98112 /*
   98113 ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
   98114 ** set of routines that is invoked for each new database connection, if it
   98115 ** is currently on the list.  If xInit is not on the list, then this
   98116 ** routine is a no-op.
   98117 **
   98118 ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
   98119 ** was not on the list.
   98120 */
   98121 SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
   98122 #if SQLITE_THREADSAFE
   98123   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   98124 #endif
   98125   int i;
   98126   int n = 0;
   98127   wsdAutoextInit;
   98128   sqlite3_mutex_enter(mutex);
   98129   for(i=wsdAutoext.nExt-1; i>=0; i--){
   98130     if( wsdAutoext.aExt[i]==xInit ){
   98131       wsdAutoext.nExt--;
   98132       wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
   98133       n++;
   98134       break;
   98135     }
   98136   }
   98137   sqlite3_mutex_leave(mutex);
   98138   return n;
   98139 }
   98140 
   98141 /*
   98142 ** Reset the automatic extension loading mechanism.
   98143 */
   98144 SQLITE_API void sqlite3_reset_auto_extension(void){
   98145 #ifndef SQLITE_OMIT_AUTOINIT
   98146   if( sqlite3_initialize()==SQLITE_OK )
   98147 #endif
   98148   {
   98149 #if SQLITE_THREADSAFE
   98150     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   98151 #endif
   98152     wsdAutoextInit;
   98153     sqlite3_mutex_enter(mutex);
   98154     sqlite3_free(wsdAutoext.aExt);
   98155     wsdAutoext.aExt = 0;
   98156     wsdAutoext.nExt = 0;
   98157     sqlite3_mutex_leave(mutex);
   98158   }
   98159 }
   98160 
   98161 /*
   98162 ** Load all automatic extensions.
   98163 **
   98164 ** If anything goes wrong, set an error in the database connection.
   98165 */
   98166 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
   98167   int i;
   98168   int go = 1;
   98169   int rc;
   98170   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   98171 
   98172   wsdAutoextInit;
   98173   if( wsdAutoext.nExt==0 ){
   98174     /* Common case: early out without every having to acquire a mutex */
   98175     return;
   98176   }
   98177   for(i=0; go; i++){
   98178     char *zErrmsg;
   98179 #if SQLITE_THREADSAFE
   98180     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   98181 #endif
   98182     sqlite3_mutex_enter(mutex);
   98183     if( i>=wsdAutoext.nExt ){
   98184       xInit = 0;
   98185       go = 0;
   98186     }else{
   98187       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   98188               wsdAutoext.aExt[i];
   98189     }
   98190     sqlite3_mutex_leave(mutex);
   98191     zErrmsg = 0;
   98192     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
   98193       sqlite3Error(db, rc,
   98194             "automatic extension loading failed: %s", zErrmsg);
   98195       go = 0;
   98196     }
   98197     sqlite3_free(zErrmsg);
   98198   }
   98199 }
   98200 
   98201 /************** End of loadext.c *********************************************/
   98202 /************** Begin file pragma.c ******************************************/
   98203 /*
   98204 ** 2003 April 6
   98205 **
   98206 ** The author disclaims copyright to this source code.  In place of
   98207 ** a legal notice, here is a blessing:
   98208 **
   98209 **    May you do good and not evil.
   98210 **    May you find forgiveness for yourself and forgive others.
   98211 **    May you share freely, never taking more than you give.
   98212 **
   98213 *************************************************************************
   98214 ** This file contains code used to implement the PRAGMA command.
   98215 */
   98216 
   98217 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   98218 #  if defined(__APPLE__)
   98219 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   98220 #  else
   98221 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   98222 #  endif
   98223 #endif
   98224 
   98225 /***************************************************************************
   98226 ** The next block of code, including the PragTyp_XXXX macro definitions and
   98227 ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
   98228 **
   98229 ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
   98230 ** that script.  Then copy/paste the output in place of the following:
   98231 */
   98232 #define PragTyp_HEADER_VALUE                   0
   98233 #define PragTyp_AUTO_VACUUM                    1
   98234 #define PragTyp_FLAG                           2
   98235 #define PragTyp_BUSY_TIMEOUT                   3
   98236 #define PragTyp_CACHE_SIZE                     4
   98237 #define PragTyp_CASE_SENSITIVE_LIKE            5
   98238 #define PragTyp_COLLATION_LIST                 6
   98239 #define PragTyp_COMPILE_OPTIONS                7
   98240 #define PragTyp_DATA_STORE_DIRECTORY           8
   98241 #define PragTyp_DATABASE_LIST                  9
   98242 #define PragTyp_DEFAULT_CACHE_SIZE            10
   98243 #define PragTyp_ENCODING                      11
   98244 #define PragTyp_FOREIGN_KEY_CHECK             12
   98245 #define PragTyp_FOREIGN_KEY_LIST              13
   98246 #define PragTyp_INCREMENTAL_VACUUM            14
   98247 #define PragTyp_INDEX_INFO                    15
   98248 #define PragTyp_INDEX_LIST                    16
   98249 #define PragTyp_INTEGRITY_CHECK               17
   98250 #define PragTyp_JOURNAL_MODE                  18
   98251 #define PragTyp_JOURNAL_SIZE_LIMIT            19
   98252 #define PragTyp_LOCK_PROXY_FILE               20
   98253 #define PragTyp_LOCKING_MODE                  21
   98254 #define PragTyp_PAGE_COUNT                    22
   98255 #define PragTyp_MMAP_SIZE                     23
   98256 #define PragTyp_PAGE_SIZE                     24
   98257 #define PragTyp_SECURE_DELETE                 25
   98258 #define PragTyp_SHRINK_MEMORY                 26
   98259 #define PragTyp_SOFT_HEAP_LIMIT               27
   98260 #define PragTyp_STATS                         28
   98261 #define PragTyp_SYNCHRONOUS                   29
   98262 #define PragTyp_TABLE_INFO                    30
   98263 #define PragTyp_TEMP_STORE                    31
   98264 #define PragTyp_TEMP_STORE_DIRECTORY          32
   98265 #define PragTyp_WAL_AUTOCHECKPOINT            33
   98266 #define PragTyp_WAL_CHECKPOINT                34
   98267 #define PragTyp_ACTIVATE_EXTENSIONS           35
   98268 #define PragTyp_HEXKEY                        36
   98269 #define PragTyp_KEY                           37
   98270 #define PragTyp_REKEY                         38
   98271 #define PragTyp_LOCK_STATUS                   39
   98272 #define PragTyp_PARSER_TRACE                  40
   98273 #define PragFlag_NeedSchema           0x01
   98274 static const struct sPragmaNames {
   98275   const char *const zName;  /* Name of pragma */
   98276   u8 ePragTyp;              /* PragTyp_XXX value */
   98277   u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
   98278   u32 iArg;                 /* Extra argument */
   98279 } aPragmaNames[] = {
   98280 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   98281   { /* zName:     */ "activate_extensions",
   98282     /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
   98283     /* ePragFlag: */ 0,
   98284     /* iArg:      */ 0 },
   98285 #endif
   98286 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   98287   { /* zName:     */ "application_id",
   98288     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   98289     /* ePragFlag: */ 0,
   98290     /* iArg:      */ 0 },
   98291 #endif
   98292 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   98293   { /* zName:     */ "auto_vacuum",
   98294     /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
   98295     /* ePragFlag: */ PragFlag_NeedSchema,
   98296     /* iArg:      */ 0 },
   98297 #endif
   98298 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98299 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
   98300   { /* zName:     */ "automatic_index",
   98301     /* ePragTyp:  */ PragTyp_FLAG,
   98302     /* ePragFlag: */ 0,
   98303     /* iArg:      */ SQLITE_AutoIndex },
   98304 #endif
   98305 #endif
   98306   { /* zName:     */ "busy_timeout",
   98307     /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
   98308     /* ePragFlag: */ 0,
   98309     /* iArg:      */ 0 },
   98310 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98311   { /* zName:     */ "cache_size",
   98312     /* ePragTyp:  */ PragTyp_CACHE_SIZE,
   98313     /* ePragFlag: */ PragFlag_NeedSchema,
   98314     /* iArg:      */ 0 },
   98315 #endif
   98316 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98317   { /* zName:     */ "cache_spill",
   98318     /* ePragTyp:  */ PragTyp_FLAG,
   98319     /* ePragFlag: */ 0,
   98320     /* iArg:      */ SQLITE_CacheSpill },
   98321 #endif
   98322   { /* zName:     */ "case_sensitive_like",
   98323     /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
   98324     /* ePragFlag: */ 0,
   98325     /* iArg:      */ 0 },
   98326 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98327   { /* zName:     */ "checkpoint_fullfsync",
   98328     /* ePragTyp:  */ PragTyp_FLAG,
   98329     /* ePragFlag: */ 0,
   98330     /* iArg:      */ SQLITE_CkptFullFSync },
   98331 #endif
   98332 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98333   { /* zName:     */ "collation_list",
   98334     /* ePragTyp:  */ PragTyp_COLLATION_LIST,
   98335     /* ePragFlag: */ 0,
   98336     /* iArg:      */ 0 },
   98337 #endif
   98338 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
   98339   { /* zName:     */ "compile_options",
   98340     /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
   98341     /* ePragFlag: */ 0,
   98342     /* iArg:      */ 0 },
   98343 #endif
   98344 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98345   { /* zName:     */ "count_changes",
   98346     /* ePragTyp:  */ PragTyp_FLAG,
   98347     /* ePragFlag: */ 0,
   98348     /* iArg:      */ SQLITE_CountRows },
   98349 #endif
   98350 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
   98351   { /* zName:     */ "data_store_directory",
   98352     /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
   98353     /* ePragFlag: */ 0,
   98354     /* iArg:      */ 0 },
   98355 #endif
   98356 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98357   { /* zName:     */ "database_list",
   98358     /* ePragTyp:  */ PragTyp_DATABASE_LIST,
   98359     /* ePragFlag: */ PragFlag_NeedSchema,
   98360     /* iArg:      */ 0 },
   98361 #endif
   98362 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   98363   { /* zName:     */ "default_cache_size",
   98364     /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
   98365     /* ePragFlag: */ PragFlag_NeedSchema,
   98366     /* iArg:      */ 0 },
   98367 #endif
   98368 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98369 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98370   { /* zName:     */ "defer_foreign_keys",
   98371     /* ePragTyp:  */ PragTyp_FLAG,
   98372     /* ePragFlag: */ 0,
   98373     /* iArg:      */ SQLITE_DeferFKs },
   98374 #endif
   98375 #endif
   98376 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98377   { /* zName:     */ "empty_result_callbacks",
   98378     /* ePragTyp:  */ PragTyp_FLAG,
   98379     /* ePragFlag: */ 0,
   98380     /* iArg:      */ SQLITE_NullCallback },
   98381 #endif
   98382 #if !defined(SQLITE_OMIT_UTF16)
   98383   { /* zName:     */ "encoding",
   98384     /* ePragTyp:  */ PragTyp_ENCODING,
   98385     /* ePragFlag: */ 0,
   98386     /* iArg:      */ 0 },
   98387 #endif
   98388 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98389   { /* zName:     */ "foreign_key_check",
   98390     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
   98391     /* ePragFlag: */ PragFlag_NeedSchema,
   98392     /* iArg:      */ 0 },
   98393 #endif
   98394 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
   98395   { /* zName:     */ "foreign_key_list",
   98396     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
   98397     /* ePragFlag: */ PragFlag_NeedSchema,
   98398     /* iArg:      */ 0 },
   98399 #endif
   98400 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98401 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98402   { /* zName:     */ "foreign_keys",
   98403     /* ePragTyp:  */ PragTyp_FLAG,
   98404     /* ePragFlag: */ 0,
   98405     /* iArg:      */ SQLITE_ForeignKeys },
   98406 #endif
   98407 #endif
   98408 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   98409   { /* zName:     */ "freelist_count",
   98410     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   98411     /* ePragFlag: */ 0,
   98412     /* iArg:      */ 0 },
   98413 #endif
   98414 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98415   { /* zName:     */ "full_column_names",
   98416     /* ePragTyp:  */ PragTyp_FLAG,
   98417     /* ePragFlag: */ 0,
   98418     /* iArg:      */ SQLITE_FullColNames },
   98419   { /* zName:     */ "fullfsync",
   98420     /* ePragTyp:  */ PragTyp_FLAG,
   98421     /* ePragFlag: */ 0,
   98422     /* iArg:      */ SQLITE_FullFSync },
   98423 #endif
   98424 #if defined(SQLITE_HAS_CODEC)
   98425   { /* zName:     */ "hexkey",
   98426     /* ePragTyp:  */ PragTyp_HEXKEY,
   98427     /* ePragFlag: */ 0,
   98428     /* iArg:      */ 0 },
   98429   { /* zName:     */ "hexrekey",
   98430     /* ePragTyp:  */ PragTyp_HEXKEY,
   98431     /* ePragFlag: */ 0,
   98432     /* iArg:      */ 0 },
   98433 #endif
   98434 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98435 #if !defined(SQLITE_OMIT_CHECK)
   98436   { /* zName:     */ "ignore_check_constraints",
   98437     /* ePragTyp:  */ PragTyp_FLAG,
   98438     /* ePragFlag: */ 0,
   98439     /* iArg:      */ SQLITE_IgnoreChecks },
   98440 #endif
   98441 #endif
   98442 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   98443   { /* zName:     */ "incremental_vacuum",
   98444     /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
   98445     /* ePragFlag: */ PragFlag_NeedSchema,
   98446     /* iArg:      */ 0 },
   98447 #endif
   98448 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98449   { /* zName:     */ "index_info",
   98450     /* ePragTyp:  */ PragTyp_INDEX_INFO,
   98451     /* ePragFlag: */ PragFlag_NeedSchema,
   98452     /* iArg:      */ 0 },
   98453   { /* zName:     */ "index_list",
   98454     /* ePragTyp:  */ PragTyp_INDEX_LIST,
   98455     /* ePragFlag: */ PragFlag_NeedSchema,
   98456     /* iArg:      */ 0 },
   98457 #endif
   98458 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
   98459   { /* zName:     */ "integrity_check",
   98460     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
   98461     /* ePragFlag: */ PragFlag_NeedSchema,
   98462     /* iArg:      */ 0 },
   98463 #endif
   98464 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98465   { /* zName:     */ "journal_mode",
   98466     /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
   98467     /* ePragFlag: */ PragFlag_NeedSchema,
   98468     /* iArg:      */ 0 },
   98469   { /* zName:     */ "journal_size_limit",
   98470     /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
   98471     /* ePragFlag: */ 0,
   98472     /* iArg:      */ 0 },
   98473 #endif
   98474 #if defined(SQLITE_HAS_CODEC)
   98475   { /* zName:     */ "key",
   98476     /* ePragTyp:  */ PragTyp_KEY,
   98477     /* ePragFlag: */ 0,
   98478     /* iArg:      */ 0 },
   98479 #endif
   98480 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98481   { /* zName:     */ "legacy_file_format",
   98482     /* ePragTyp:  */ PragTyp_FLAG,
   98483     /* ePragFlag: */ 0,
   98484     /* iArg:      */ SQLITE_LegacyFileFmt },
   98485 #endif
   98486 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
   98487   { /* zName:     */ "lock_proxy_file",
   98488     /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
   98489     /* ePragFlag: */ 0,
   98490     /* iArg:      */ 0 },
   98491 #endif
   98492 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   98493   { /* zName:     */ "lock_status",
   98494     /* ePragTyp:  */ PragTyp_LOCK_STATUS,
   98495     /* ePragFlag: */ 0,
   98496     /* iArg:      */ 0 },
   98497 #endif
   98498 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98499   { /* zName:     */ "locking_mode",
   98500     /* ePragTyp:  */ PragTyp_LOCKING_MODE,
   98501     /* ePragFlag: */ 0,
   98502     /* iArg:      */ 0 },
   98503   { /* zName:     */ "max_page_count",
   98504     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
   98505     /* ePragFlag: */ PragFlag_NeedSchema,
   98506     /* iArg:      */ 0 },
   98507   { /* zName:     */ "mmap_size",
   98508     /* ePragTyp:  */ PragTyp_MMAP_SIZE,
   98509     /* ePragFlag: */ 0,
   98510     /* iArg:      */ 0 },
   98511   { /* zName:     */ "page_count",
   98512     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
   98513     /* ePragFlag: */ PragFlag_NeedSchema,
   98514     /* iArg:      */ 0 },
   98515   { /* zName:     */ "page_size",
   98516     /* ePragTyp:  */ PragTyp_PAGE_SIZE,
   98517     /* ePragFlag: */ 0,
   98518     /* iArg:      */ 0 },
   98519 #endif
   98520 #if defined(SQLITE_DEBUG)
   98521   { /* zName:     */ "parser_trace",
   98522     /* ePragTyp:  */ PragTyp_PARSER_TRACE,
   98523     /* ePragFlag: */ 0,
   98524     /* iArg:      */ 0 },
   98525 #endif
   98526 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98527   { /* zName:     */ "query_only",
   98528     /* ePragTyp:  */ PragTyp_FLAG,
   98529     /* ePragFlag: */ 0,
   98530     /* iArg:      */ SQLITE_QueryOnly },
   98531 #endif
   98532 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
   98533   { /* zName:     */ "quick_check",
   98534     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
   98535     /* ePragFlag: */ PragFlag_NeedSchema,
   98536     /* iArg:      */ 0 },
   98537 #endif
   98538 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98539   { /* zName:     */ "read_uncommitted",
   98540     /* ePragTyp:  */ PragTyp_FLAG,
   98541     /* ePragFlag: */ 0,
   98542     /* iArg:      */ SQLITE_ReadUncommitted },
   98543   { /* zName:     */ "recursive_triggers",
   98544     /* ePragTyp:  */ PragTyp_FLAG,
   98545     /* ePragFlag: */ 0,
   98546     /* iArg:      */ SQLITE_RecTriggers },
   98547 #endif
   98548 #if defined(SQLITE_HAS_CODEC)
   98549   { /* zName:     */ "rekey",
   98550     /* ePragTyp:  */ PragTyp_REKEY,
   98551     /* ePragFlag: */ 0,
   98552     /* iArg:      */ 0 },
   98553 #endif
   98554 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98555   { /* zName:     */ "reverse_unordered_selects",
   98556     /* ePragTyp:  */ PragTyp_FLAG,
   98557     /* ePragFlag: */ 0,
   98558     /* iArg:      */ SQLITE_ReverseOrder },
   98559 #endif
   98560 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   98561   { /* zName:     */ "schema_version",
   98562     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   98563     /* ePragFlag: */ 0,
   98564     /* iArg:      */ 0 },
   98565 #endif
   98566 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98567   { /* zName:     */ "secure_delete",
   98568     /* ePragTyp:  */ PragTyp_SECURE_DELETE,
   98569     /* ePragFlag: */ 0,
   98570     /* iArg:      */ 0 },
   98571 #endif
   98572 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98573   { /* zName:     */ "short_column_names",
   98574     /* ePragTyp:  */ PragTyp_FLAG,
   98575     /* ePragFlag: */ 0,
   98576     /* iArg:      */ SQLITE_ShortColNames },
   98577 #endif
   98578   { /* zName:     */ "shrink_memory",
   98579     /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
   98580     /* ePragFlag: */ 0,
   98581     /* iArg:      */ 0 },
   98582   { /* zName:     */ "soft_heap_limit",
   98583     /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
   98584     /* ePragFlag: */ 0,
   98585     /* iArg:      */ 0 },
   98586 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98587 #if defined(SQLITE_DEBUG)
   98588   { /* zName:     */ "sql_trace",
   98589     /* ePragTyp:  */ PragTyp_FLAG,
   98590     /* ePragFlag: */ 0,
   98591     /* iArg:      */ SQLITE_SqlTrace },
   98592 #endif
   98593 #endif
   98594 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98595   { /* zName:     */ "stats",
   98596     /* ePragTyp:  */ PragTyp_STATS,
   98597     /* ePragFlag: */ PragFlag_NeedSchema,
   98598     /* iArg:      */ 0 },
   98599 #endif
   98600 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98601   { /* zName:     */ "synchronous",
   98602     /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
   98603     /* ePragFlag: */ PragFlag_NeedSchema,
   98604     /* iArg:      */ 0 },
   98605 #endif
   98606 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   98607   { /* zName:     */ "table_info",
   98608     /* ePragTyp:  */ PragTyp_TABLE_INFO,
   98609     /* ePragFlag: */ PragFlag_NeedSchema,
   98610     /* iArg:      */ 0 },
   98611 #endif
   98612 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   98613   { /* zName:     */ "temp_store",
   98614     /* ePragTyp:  */ PragTyp_TEMP_STORE,
   98615     /* ePragFlag: */ 0,
   98616     /* iArg:      */ 0 },
   98617   { /* zName:     */ "temp_store_directory",
   98618     /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
   98619     /* ePragFlag: */ 0,
   98620     /* iArg:      */ 0 },
   98621 #endif
   98622 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   98623   { /* zName:     */ "user_version",
   98624     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   98625     /* ePragFlag: */ 0,
   98626     /* iArg:      */ 0 },
   98627 #endif
   98628 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98629 #if defined(SQLITE_DEBUG)
   98630   { /* zName:     */ "vdbe_addoptrace",
   98631     /* ePragTyp:  */ PragTyp_FLAG,
   98632     /* ePragFlag: */ 0,
   98633     /* iArg:      */ SQLITE_VdbeAddopTrace },
   98634   { /* zName:     */ "vdbe_debug",
   98635     /* ePragTyp:  */ PragTyp_FLAG,
   98636     /* ePragFlag: */ 0,
   98637     /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
   98638   { /* zName:     */ "vdbe_eqp",
   98639     /* ePragTyp:  */ PragTyp_FLAG,
   98640     /* ePragFlag: */ 0,
   98641     /* iArg:      */ SQLITE_VdbeEQP },
   98642   { /* zName:     */ "vdbe_listing",
   98643     /* ePragTyp:  */ PragTyp_FLAG,
   98644     /* ePragFlag: */ 0,
   98645     /* iArg:      */ SQLITE_VdbeListing },
   98646   { /* zName:     */ "vdbe_trace",
   98647     /* ePragTyp:  */ PragTyp_FLAG,
   98648     /* ePragFlag: */ 0,
   98649     /* iArg:      */ SQLITE_VdbeTrace },
   98650 #endif
   98651 #endif
   98652 #if !defined(SQLITE_OMIT_WAL)
   98653   { /* zName:     */ "wal_autocheckpoint",
   98654     /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
   98655     /* ePragFlag: */ 0,
   98656     /* iArg:      */ 0 },
   98657   { /* zName:     */ "wal_checkpoint",
   98658     /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
   98659     /* ePragFlag: */ PragFlag_NeedSchema,
   98660     /* iArg:      */ 0 },
   98661 #endif
   98662 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   98663   { /* zName:     */ "writable_schema",
   98664     /* ePragTyp:  */ PragTyp_FLAG,
   98665     /* ePragFlag: */ 0,
   98666     /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
   98667 #endif
   98668 };
   98669 /* Number of pragmas: 56 on by default, 69 total. */
   98670 /* End of the automatically generated pragma table.
   98671 ***************************************************************************/
   98672 
   98673 /*
   98674 ** Interpret the given string as a safety level.  Return 0 for OFF,
   98675 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
   98676 ** unrecognized string argument.  The FULL option is disallowed
   98677 ** if the omitFull parameter it 1.
   98678 **
   98679 ** Note that the values returned are one less that the values that
   98680 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
   98681 ** to support legacy SQL code.  The safety level used to be boolean
   98682 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
   98683 */
   98684 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
   98685                              /* 123456789 123456789 */
   98686   static const char zText[] = "onoffalseyestruefull";
   98687   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
   98688   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
   98689   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
   98690   int i, n;
   98691   if( sqlite3Isdigit(*z) ){
   98692     return (u8)sqlite3Atoi(z);
   98693   }
   98694   n = sqlite3Strlen30(z);
   98695   for(i=0; i<ArraySize(iLength)-omitFull; i++){
   98696     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
   98697       return iValue[i];
   98698     }
   98699   }
   98700   return dflt;
   98701 }
   98702 
   98703 /*
   98704 ** Interpret the given string as a boolean value.
   98705 */
   98706 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
   98707   return getSafetyLevel(z,1,dflt)!=0;
   98708 }
   98709 
   98710 /* The sqlite3GetBoolean() function is used by other modules but the
   98711 ** remainder of this file is specific to PRAGMA processing.  So omit
   98712 ** the rest of the file if PRAGMAs are omitted from the build.
   98713 */
   98714 #if !defined(SQLITE_OMIT_PRAGMA)
   98715 
   98716 /*
   98717 ** Interpret the given string as a locking mode value.
   98718 */
   98719 static int getLockingMode(const char *z){
   98720   if( z ){
   98721     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
   98722     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
   98723   }
   98724   return PAGER_LOCKINGMODE_QUERY;
   98725 }
   98726 
   98727 #ifndef SQLITE_OMIT_AUTOVACUUM
   98728 /*
   98729 ** Interpret the given string as an auto-vacuum mode value.
   98730 **
   98731 ** The following strings, "none", "full" and "incremental" are
   98732 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
   98733 */
   98734 static int getAutoVacuum(const char *z){
   98735   int i;
   98736   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
   98737   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
   98738   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
   98739   i = sqlite3Atoi(z);
   98740   return (u8)((i>=0&&i<=2)?i:0);
   98741 }
   98742 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
   98743 
   98744 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   98745 /*
   98746 ** Interpret the given string as a temp db location. Return 1 for file
   98747 ** backed temporary databases, 2 for the Red-Black tree in memory database
   98748 ** and 0 to use the compile-time default.
   98749 */
   98750 static int getTempStore(const char *z){
   98751   if( z[0]>='0' && z[0]<='2' ){
   98752     return z[0] - '0';
   98753   }else if( sqlite3StrICmp(z, "file")==0 ){
   98754     return 1;
   98755   }else if( sqlite3StrICmp(z, "memory")==0 ){
   98756     return 2;
   98757   }else{
   98758     return 0;
   98759   }
   98760 }
   98761 #endif /* SQLITE_PAGER_PRAGMAS */
   98762 
   98763 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   98764 /*
   98765 ** Invalidate temp storage, either when the temp storage is changed
   98766 ** from default, or when 'file' and the temp_store_directory has changed
   98767 */
   98768 static int invalidateTempStorage(Parse *pParse){
   98769   sqlite3 *db = pParse->db;
   98770   if( db->aDb[1].pBt!=0 ){
   98771     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
   98772       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
   98773         "from within a transaction");
   98774       return SQLITE_ERROR;
   98775     }
   98776     sqlite3BtreeClose(db->aDb[1].pBt);
   98777     db->aDb[1].pBt = 0;
   98778     sqlite3ResetAllSchemasOfConnection(db);
   98779   }
   98780   return SQLITE_OK;
   98781 }
   98782 #endif /* SQLITE_PAGER_PRAGMAS */
   98783 
   98784 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   98785 /*
   98786 ** If the TEMP database is open, close it and mark the database schema
   98787 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
   98788 ** or DEFAULT_TEMP_STORE pragmas.
   98789 */
   98790 static int changeTempStorage(Parse *pParse, const char *zStorageType){
   98791   int ts = getTempStore(zStorageType);
   98792   sqlite3 *db = pParse->db;
   98793   if( db->temp_store==ts ) return SQLITE_OK;
   98794   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
   98795     return SQLITE_ERROR;
   98796   }
   98797   db->temp_store = (u8)ts;
   98798   return SQLITE_OK;
   98799 }
   98800 #endif /* SQLITE_PAGER_PRAGMAS */
   98801 
   98802 /*
   98803 ** Generate code to return a single integer value.
   98804 */
   98805 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
   98806   Vdbe *v = sqlite3GetVdbe(pParse);
   98807   int mem = ++pParse->nMem;
   98808   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
   98809   if( pI64 ){
   98810     memcpy(pI64, &value, sizeof(value));
   98811   }
   98812   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
   98813   sqlite3VdbeSetNumCols(v, 1);
   98814   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
   98815   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   98816 }
   98817 
   98818 
   98819 /*
   98820 ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
   98821 ** set these values for all pagers.
   98822 */
   98823 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   98824 static void setAllPagerFlags(sqlite3 *db){
   98825   if( db->autoCommit ){
   98826     Db *pDb = db->aDb;
   98827     int n = db->nDb;
   98828     assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
   98829     assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
   98830     assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
   98831     assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
   98832              ==  PAGER_FLAGS_MASK );
   98833     assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
   98834     while( (n--) > 0 ){
   98835       if( pDb->pBt ){
   98836         sqlite3BtreeSetPagerFlags(pDb->pBt,
   98837                  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
   98838       }
   98839       pDb++;
   98840     }
   98841   }
   98842 }
   98843 #else
   98844 # define setAllPagerFlags(X)  /* no-op */
   98845 #endif
   98846 
   98847 
   98848 /*
   98849 ** Return a human-readable name for a constraint resolution action.
   98850 */
   98851 #ifndef SQLITE_OMIT_FOREIGN_KEY
   98852 static const char *actionName(u8 action){
   98853   const char *zName;
   98854   switch( action ){
   98855     case OE_SetNull:  zName = "SET NULL";        break;
   98856     case OE_SetDflt:  zName = "SET DEFAULT";     break;
   98857     case OE_Cascade:  zName = "CASCADE";         break;
   98858     case OE_Restrict: zName = "RESTRICT";        break;
   98859     default:          zName = "NO ACTION";
   98860                       assert( action==OE_None ); break;
   98861   }
   98862   return zName;
   98863 }
   98864 #endif
   98865 
   98866 
   98867 /*
   98868 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
   98869 ** defined in pager.h. This function returns the associated lowercase
   98870 ** journal-mode name.
   98871 */
   98872 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
   98873   static char * const azModeName[] = {
   98874     "delete", "persist", "off", "truncate", "memory"
   98875 #ifndef SQLITE_OMIT_WAL
   98876      , "wal"
   98877 #endif
   98878   };
   98879   assert( PAGER_JOURNALMODE_DELETE==0 );
   98880   assert( PAGER_JOURNALMODE_PERSIST==1 );
   98881   assert( PAGER_JOURNALMODE_OFF==2 );
   98882   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
   98883   assert( PAGER_JOURNALMODE_MEMORY==4 );
   98884   assert( PAGER_JOURNALMODE_WAL==5 );
   98885   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
   98886 
   98887   if( eMode==ArraySize(azModeName) ) return 0;
   98888   return azModeName[eMode];
   98889 }
   98890 
   98891 /*
   98892 ** Process a pragma statement.
   98893 **
   98894 ** Pragmas are of this form:
   98895 **
   98896 **      PRAGMA [database.]id [= value]
   98897 **
   98898 ** The identifier might also be a string.  The value is a string, and
   98899 ** identifier, or a number.  If minusFlag is true, then the value is
   98900 ** a number that was preceded by a minus sign.
   98901 **
   98902 ** If the left side is "database.id" then pId1 is the database name
   98903 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
   98904 ** id and pId2 is any empty string.
   98905 */
   98906 SQLITE_PRIVATE void sqlite3Pragma(
   98907   Parse *pParse,
   98908   Token *pId1,        /* First part of [database.]id field */
   98909   Token *pId2,        /* Second part of [database.]id field, or NULL */
   98910   Token *pValue,      /* Token for <value>, or NULL */
   98911   int minusFlag       /* True if a '-' sign preceded <value> */
   98912 ){
   98913   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
   98914   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
   98915   const char *zDb = 0;   /* The database name */
   98916   Token *pId;            /* Pointer to <id> token */
   98917   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
   98918   int iDb;               /* Database index for <database> */
   98919   int lwr, upr, mid;           /* Binary search bounds */
   98920   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
   98921   sqlite3 *db = pParse->db;    /* The database connection */
   98922   Db *pDb;                     /* The specific database being pragmaed */
   98923   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
   98924 
   98925   if( v==0 ) return;
   98926   sqlite3VdbeRunOnlyOnce(v);
   98927   pParse->nMem = 2;
   98928 
   98929   /* Interpret the [database.] part of the pragma statement. iDb is the
   98930   ** index of the database this pragma is being applied to in db.aDb[]. */
   98931   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
   98932   if( iDb<0 ) return;
   98933   pDb = &db->aDb[iDb];
   98934 
   98935   /* If the temp database has been explicitly named as part of the
   98936   ** pragma, make sure it is open.
   98937   */
   98938   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
   98939     return;
   98940   }
   98941 
   98942   zLeft = sqlite3NameFromToken(db, pId);
   98943   if( !zLeft ) return;
   98944   if( minusFlag ){
   98945     zRight = sqlite3MPrintf(db, "-%T", pValue);
   98946   }else{
   98947     zRight = sqlite3NameFromToken(db, pValue);
   98948   }
   98949 
   98950   assert( pId2 );
   98951   zDb = pId2->n>0 ? pDb->zName : 0;
   98952   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   98953     goto pragma_out;
   98954   }
   98955 
   98956   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
   98957   ** connection.  If it returns SQLITE_OK, then assume that the VFS
   98958   ** handled the pragma and generate a no-op prepared statement.
   98959   */
   98960   aFcntl[0] = 0;
   98961   aFcntl[1] = zLeft;
   98962   aFcntl[2] = zRight;
   98963   aFcntl[3] = 0;
   98964   db->busyHandler.nBusy = 0;
   98965   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
   98966   if( rc==SQLITE_OK ){
   98967     if( aFcntl[0] ){
   98968       int mem = ++pParse->nMem;
   98969       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
   98970       sqlite3VdbeSetNumCols(v, 1);
   98971       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
   98972       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   98973       sqlite3_free(aFcntl[0]);
   98974     }
   98975     goto pragma_out;
   98976   }
   98977   if( rc!=SQLITE_NOTFOUND ){
   98978     if( aFcntl[0] ){
   98979       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
   98980       sqlite3_free(aFcntl[0]);
   98981     }
   98982     pParse->nErr++;
   98983     pParse->rc = rc;
   98984     goto pragma_out;
   98985   }
   98986 
   98987   /* Locate the pragma in the lookup table */
   98988   lwr = 0;
   98989   upr = ArraySize(aPragmaNames)-1;
   98990   while( lwr<=upr ){
   98991     mid = (lwr+upr)/2;
   98992     rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
   98993     if( rc==0 ) break;
   98994     if( rc<0 ){
   98995       upr = mid - 1;
   98996     }else{
   98997       lwr = mid + 1;
   98998     }
   98999   }
   99000   if( lwr>upr ) goto pragma_out;
   99001 
   99002   /* Make sure the database schema is loaded if the pragma requires that */
   99003   if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
   99004     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   99005   }
   99006 
   99007   /* Jump to the appropriate pragma handler */
   99008   switch( aPragmaNames[mid].ePragTyp ){
   99009 
   99010 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   99011   /*
   99012   **  PRAGMA [database.]default_cache_size
   99013   **  PRAGMA [database.]default_cache_size=N
   99014   **
   99015   ** The first form reports the current persistent setting for the
   99016   ** page cache size.  The value returned is the maximum number of
   99017   ** pages in the page cache.  The second form sets both the current
   99018   ** page cache size value and the persistent page cache size value
   99019   ** stored in the database file.
   99020   **
   99021   ** Older versions of SQLite would set the default cache size to a
   99022   ** negative number to indicate synchronous=OFF.  These days, synchronous
   99023   ** is always on by default regardless of the sign of the default cache
   99024   ** size.  But continue to take the absolute value of the default cache
   99025   ** size of historical compatibility.
   99026   */
   99027   case PragTyp_DEFAULT_CACHE_SIZE: {
   99028     static const int iLn = VDBE_OFFSET_LINENO(2);
   99029     static const VdbeOpList getCacheSize[] = {
   99030       { OP_Transaction, 0, 0,        0},                         /* 0 */
   99031       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
   99032       { OP_IfPos,       1, 8,        0},
   99033       { OP_Integer,     0, 2,        0},
   99034       { OP_Subtract,    1, 2,        1},
   99035       { OP_IfPos,       1, 8,        0},
   99036       { OP_Integer,     0, 1,        0},                         /* 6 */
   99037       { OP_Noop,        0, 0,        0},
   99038       { OP_ResultRow,   1, 1,        0},
   99039     };
   99040     int addr;
   99041     sqlite3VdbeUsesBtree(v, iDb);
   99042     if( !zRight ){
   99043       sqlite3VdbeSetNumCols(v, 1);
   99044       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
   99045       pParse->nMem += 2;
   99046       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
   99047       sqlite3VdbeChangeP1(v, addr, iDb);
   99048       sqlite3VdbeChangeP1(v, addr+1, iDb);
   99049       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
   99050     }else{
   99051       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
   99052       sqlite3BeginWriteOperation(pParse, 0, iDb);
   99053       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
   99054       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
   99055       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99056       pDb->pSchema->cache_size = size;
   99057       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   99058     }
   99059     break;
   99060   }
   99061 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
   99062 
   99063 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   99064   /*
   99065   **  PRAGMA [database.]page_size
   99066   **  PRAGMA [database.]page_size=N
   99067   **
   99068   ** The first form reports the current setting for the
   99069   ** database page size in bytes.  The second form sets the
   99070   ** database page size value.  The value can only be set if
   99071   ** the database has not yet been created.
   99072   */
   99073   case PragTyp_PAGE_SIZE: {
   99074     Btree *pBt = pDb->pBt;
   99075     assert( pBt!=0 );
   99076     if( !zRight ){
   99077       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
   99078       returnSingleInt(pParse, "page_size", size);
   99079     }else{
   99080       /* Malloc may fail when setting the page-size, as there is an internal
   99081       ** buffer that the pager module resizes using sqlite3_realloc().
   99082       */
   99083       db->nextPagesize = sqlite3Atoi(zRight);
   99084       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
   99085         db->mallocFailed = 1;
   99086       }
   99087     }
   99088     break;
   99089   }
   99090 
   99091   /*
   99092   **  PRAGMA [database.]secure_delete
   99093   **  PRAGMA [database.]secure_delete=ON/OFF
   99094   **
   99095   ** The first form reports the current setting for the
   99096   ** secure_delete flag.  The second form changes the secure_delete
   99097   ** flag setting and reports thenew value.
   99098   */
   99099   case PragTyp_SECURE_DELETE: {
   99100     Btree *pBt = pDb->pBt;
   99101     int b = -1;
   99102     assert( pBt!=0 );
   99103     if( zRight ){
   99104       b = sqlite3GetBoolean(zRight, 0);
   99105     }
   99106     if( pId2->n==0 && b>=0 ){
   99107       int ii;
   99108       for(ii=0; ii<db->nDb; ii++){
   99109         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
   99110       }
   99111     }
   99112     b = sqlite3BtreeSecureDelete(pBt, b);
   99113     returnSingleInt(pParse, "secure_delete", b);
   99114     break;
   99115   }
   99116 
   99117   /*
   99118   **  PRAGMA [database.]max_page_count
   99119   **  PRAGMA [database.]max_page_count=N
   99120   **
   99121   ** The first form reports the current setting for the
   99122   ** maximum number of pages in the database file.  The
   99123   ** second form attempts to change this setting.  Both
   99124   ** forms return the current setting.
   99125   **
   99126   ** The absolute value of N is used.  This is undocumented and might
   99127   ** change.  The only purpose is to provide an easy way to test
   99128   ** the sqlite3AbsInt32() function.
   99129   **
   99130   **  PRAGMA [database.]page_count
   99131   **
   99132   ** Return the number of pages in the specified database.
   99133   */
   99134   case PragTyp_PAGE_COUNT: {
   99135     int iReg;
   99136     sqlite3CodeVerifySchema(pParse, iDb);
   99137     iReg = ++pParse->nMem;
   99138     if( sqlite3Tolower(zLeft[0])=='p' ){
   99139       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
   99140     }else{
   99141       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
   99142                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
   99143     }
   99144     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
   99145     sqlite3VdbeSetNumCols(v, 1);
   99146     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   99147     break;
   99148   }
   99149 
   99150   /*
   99151   **  PRAGMA [database.]locking_mode
   99152   **  PRAGMA [database.]locking_mode = (normal|exclusive)
   99153   */
   99154   case PragTyp_LOCKING_MODE: {
   99155     const char *zRet = "normal";
   99156     int eMode = getLockingMode(zRight);
   99157 
   99158     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
   99159       /* Simple "PRAGMA locking_mode;" statement. This is a query for
   99160       ** the current default locking mode (which may be different to
   99161       ** the locking-mode of the main database).
   99162       */
   99163       eMode = db->dfltLockMode;
   99164     }else{
   99165       Pager *pPager;
   99166       if( pId2->n==0 ){
   99167         /* This indicates that no database name was specified as part
   99168         ** of the PRAGMA command. In this case the locking-mode must be
   99169         ** set on all attached databases, as well as the main db file.
   99170         **
   99171         ** Also, the sqlite3.dfltLockMode variable is set so that
   99172         ** any subsequently attached databases also use the specified
   99173         ** locking mode.
   99174         */
   99175         int ii;
   99176         assert(pDb==&db->aDb[0]);
   99177         for(ii=2; ii<db->nDb; ii++){
   99178           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
   99179           sqlite3PagerLockingMode(pPager, eMode);
   99180         }
   99181         db->dfltLockMode = (u8)eMode;
   99182       }
   99183       pPager = sqlite3BtreePager(pDb->pBt);
   99184       eMode = sqlite3PagerLockingMode(pPager, eMode);
   99185     }
   99186 
   99187     assert( eMode==PAGER_LOCKINGMODE_NORMAL
   99188             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   99189     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
   99190       zRet = "exclusive";
   99191     }
   99192     sqlite3VdbeSetNumCols(v, 1);
   99193     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
   99194     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
   99195     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99196     break;
   99197   }
   99198 
   99199   /*
   99200   **  PRAGMA [database.]journal_mode
   99201   **  PRAGMA [database.]journal_mode =
   99202   **                      (delete|persist|off|truncate|memory|wal|off)
   99203   */
   99204   case PragTyp_JOURNAL_MODE: {
   99205     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
   99206     int ii;           /* Loop counter */
   99207 
   99208     sqlite3VdbeSetNumCols(v, 1);
   99209     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
   99210 
   99211     if( zRight==0 ){
   99212       /* If there is no "=MODE" part of the pragma, do a query for the
   99213       ** current mode */
   99214       eMode = PAGER_JOURNALMODE_QUERY;
   99215     }else{
   99216       const char *zMode;
   99217       int n = sqlite3Strlen30(zRight);
   99218       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
   99219         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
   99220       }
   99221       if( !zMode ){
   99222         /* If the "=MODE" part does not match any known journal mode,
   99223         ** then do a query */
   99224         eMode = PAGER_JOURNALMODE_QUERY;
   99225       }
   99226     }
   99227     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
   99228       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
   99229       iDb = 0;
   99230       pId2->n = 1;
   99231     }
   99232     for(ii=db->nDb-1; ii>=0; ii--){
   99233       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   99234         sqlite3VdbeUsesBtree(v, ii);
   99235         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
   99236       }
   99237     }
   99238     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99239     break;
   99240   }
   99241 
   99242   /*
   99243   **  PRAGMA [database.]journal_size_limit
   99244   **  PRAGMA [database.]journal_size_limit=N
   99245   **
   99246   ** Get or set the size limit on rollback journal files.
   99247   */
   99248   case PragTyp_JOURNAL_SIZE_LIMIT: {
   99249     Pager *pPager = sqlite3BtreePager(pDb->pBt);
   99250     i64 iLimit = -2;
   99251     if( zRight ){
   99252       sqlite3DecOrHexToI64(zRight, &iLimit);
   99253       if( iLimit<-1 ) iLimit = -1;
   99254     }
   99255     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
   99256     returnSingleInt(pParse, "journal_size_limit", iLimit);
   99257     break;
   99258   }
   99259 
   99260 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   99261 
   99262   /*
   99263   **  PRAGMA [database.]auto_vacuum
   99264   **  PRAGMA [database.]auto_vacuum=N
   99265   **
   99266   ** Get or set the value of the database 'auto-vacuum' parameter.
   99267   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
   99268   */
   99269 #ifndef SQLITE_OMIT_AUTOVACUUM
   99270   case PragTyp_AUTO_VACUUM: {
   99271     Btree *pBt = pDb->pBt;
   99272     assert( pBt!=0 );
   99273     if( !zRight ){
   99274       returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
   99275     }else{
   99276       int eAuto = getAutoVacuum(zRight);
   99277       assert( eAuto>=0 && eAuto<=2 );
   99278       db->nextAutovac = (u8)eAuto;
   99279       /* Call SetAutoVacuum() to set initialize the internal auto and
   99280       ** incr-vacuum flags. This is required in case this connection
   99281       ** creates the database file. It is important that it is created
   99282       ** as an auto-vacuum capable db.
   99283       */
   99284       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
   99285       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
   99286         /* When setting the auto_vacuum mode to either "full" or
   99287         ** "incremental", write the value of meta[6] in the database
   99288         ** file. Before writing to meta[6], check that meta[3] indicates
   99289         ** that this really is an auto-vacuum capable database.
   99290         */
   99291         static const int iLn = VDBE_OFFSET_LINENO(2);
   99292         static const VdbeOpList setMeta6[] = {
   99293           { OP_Transaction,    0,         1,                 0},    /* 0 */
   99294           { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
   99295           { OP_If,             1,         0,                 0},    /* 2 */
   99296           { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
   99297           { OP_Integer,        0,         1,                 0},    /* 4 */
   99298           { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
   99299         };
   99300         int iAddr;
   99301         iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
   99302         sqlite3VdbeChangeP1(v, iAddr, iDb);
   99303         sqlite3VdbeChangeP1(v, iAddr+1, iDb);
   99304         sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
   99305         sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
   99306         sqlite3VdbeChangeP1(v, iAddr+5, iDb);
   99307         sqlite3VdbeUsesBtree(v, iDb);
   99308       }
   99309     }
   99310     break;
   99311   }
   99312 #endif
   99313 
   99314   /*
   99315   **  PRAGMA [database.]incremental_vacuum(N)
   99316   **
   99317   ** Do N steps of incremental vacuuming on a database.
   99318   */
   99319 #ifndef SQLITE_OMIT_AUTOVACUUM
   99320   case PragTyp_INCREMENTAL_VACUUM: {
   99321     int iLimit, addr;
   99322     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
   99323       iLimit = 0x7fffffff;
   99324     }
   99325     sqlite3BeginWriteOperation(pParse, 0, iDb);
   99326     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
   99327     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
   99328     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
   99329     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   99330     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
   99331     sqlite3VdbeJumpHere(v, addr);
   99332     break;
   99333   }
   99334 #endif
   99335 
   99336 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   99337   /*
   99338   **  PRAGMA [database.]cache_size
   99339   **  PRAGMA [database.]cache_size=N
   99340   **
   99341   ** The first form reports the current local setting for the
   99342   ** page cache size. The second form sets the local
   99343   ** page cache size value.  If N is positive then that is the
   99344   ** number of pages in the cache.  If N is negative, then the
   99345   ** number of pages is adjusted so that the cache uses -N kibibytes
   99346   ** of memory.
   99347   */
   99348   case PragTyp_CACHE_SIZE: {
   99349     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99350     if( !zRight ){
   99351       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
   99352     }else{
   99353       int size = sqlite3Atoi(zRight);
   99354       pDb->pSchema->cache_size = size;
   99355       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   99356     }
   99357     break;
   99358   }
   99359 
   99360   /*
   99361   **  PRAGMA [database.]mmap_size(N)
   99362   **
   99363   ** Used to set mapping size limit. The mapping size limit is
   99364   ** used to limit the aggregate size of all memory mapped regions of the
   99365   ** database file. If this parameter is set to zero, then memory mapping
   99366   ** is not used at all.  If N is negative, then the default memory map
   99367   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
   99368   ** The parameter N is measured in bytes.
   99369   **
   99370   ** This value is advisory.  The underlying VFS is free to memory map
   99371   ** as little or as much as it wants.  Except, if N is set to 0 then the
   99372   ** upper layers will never invoke the xFetch interfaces to the VFS.
   99373   */
   99374   case PragTyp_MMAP_SIZE: {
   99375     sqlite3_int64 sz;
   99376 #if SQLITE_MAX_MMAP_SIZE>0
   99377     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99378     if( zRight ){
   99379       int ii;
   99380       sqlite3DecOrHexToI64(zRight, &sz);
   99381       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
   99382       if( pId2->n==0 ) db->szMmap = sz;
   99383       for(ii=db->nDb-1; ii>=0; ii--){
   99384         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   99385           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
   99386         }
   99387       }
   99388     }
   99389     sz = -1;
   99390     rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
   99391 #else
   99392     sz = 0;
   99393     rc = SQLITE_OK;
   99394 #endif
   99395     if( rc==SQLITE_OK ){
   99396       returnSingleInt(pParse, "mmap_size", sz);
   99397     }else if( rc!=SQLITE_NOTFOUND ){
   99398       pParse->nErr++;
   99399       pParse->rc = rc;
   99400     }
   99401     break;
   99402   }
   99403 
   99404   /*
   99405   **   PRAGMA temp_store
   99406   **   PRAGMA temp_store = "default"|"memory"|"file"
   99407   **
   99408   ** Return or set the local value of the temp_store flag.  Changing
   99409   ** the local value does not make changes to the disk file and the default
   99410   ** value will be restored the next time the database is opened.
   99411   **
   99412   ** Note that it is possible for the library compile-time options to
   99413   ** override this setting
   99414   */
   99415   case PragTyp_TEMP_STORE: {
   99416     if( !zRight ){
   99417       returnSingleInt(pParse, "temp_store", db->temp_store);
   99418     }else{
   99419       changeTempStorage(pParse, zRight);
   99420     }
   99421     break;
   99422   }
   99423 
   99424   /*
   99425   **   PRAGMA temp_store_directory
   99426   **   PRAGMA temp_store_directory = ""|"directory_name"
   99427   **
   99428   ** Return or set the local value of the temp_store_directory flag.  Changing
   99429   ** the value sets a specific directory to be used for temporary files.
   99430   ** Setting to a null string reverts to the default temporary directory search.
   99431   ** If temporary directory is changed, then invalidateTempStorage.
   99432   **
   99433   */
   99434   case PragTyp_TEMP_STORE_DIRECTORY: {
   99435     if( !zRight ){
   99436       if( sqlite3_temp_directory ){
   99437         sqlite3VdbeSetNumCols(v, 1);
   99438         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   99439             "temp_store_directory", SQLITE_STATIC);
   99440         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
   99441         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99442       }
   99443     }else{
   99444 #ifndef SQLITE_OMIT_WSD
   99445       if( zRight[0] ){
   99446         int res;
   99447         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   99448         if( rc!=SQLITE_OK || res==0 ){
   99449           sqlite3ErrorMsg(pParse, "not a writable directory");
   99450           goto pragma_out;
   99451         }
   99452       }
   99453       if( SQLITE_TEMP_STORE==0
   99454        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
   99455        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
   99456       ){
   99457         invalidateTempStorage(pParse);
   99458       }
   99459       sqlite3_free(sqlite3_temp_directory);
   99460       if( zRight[0] ){
   99461         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
   99462       }else{
   99463         sqlite3_temp_directory = 0;
   99464       }
   99465 #endif /* SQLITE_OMIT_WSD */
   99466     }
   99467     break;
   99468   }
   99469 
   99470 #if SQLITE_OS_WIN
   99471   /*
   99472   **   PRAGMA data_store_directory
   99473   **   PRAGMA data_store_directory = ""|"directory_name"
   99474   **
   99475   ** Return or set the local value of the data_store_directory flag.  Changing
   99476   ** the value sets a specific directory to be used for database files that
   99477   ** were specified with a relative pathname.  Setting to a null string reverts
   99478   ** to the default database directory, which for database files specified with
   99479   ** a relative path will probably be based on the current directory for the
   99480   ** process.  Database file specified with an absolute path are not impacted
   99481   ** by this setting, regardless of its value.
   99482   **
   99483   */
   99484   case PragTyp_DATA_STORE_DIRECTORY: {
   99485     if( !zRight ){
   99486       if( sqlite3_data_directory ){
   99487         sqlite3VdbeSetNumCols(v, 1);
   99488         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   99489             "data_store_directory", SQLITE_STATIC);
   99490         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
   99491         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99492       }
   99493     }else{
   99494 #ifndef SQLITE_OMIT_WSD
   99495       if( zRight[0] ){
   99496         int res;
   99497         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   99498         if( rc!=SQLITE_OK || res==0 ){
   99499           sqlite3ErrorMsg(pParse, "not a writable directory");
   99500           goto pragma_out;
   99501         }
   99502       }
   99503       sqlite3_free(sqlite3_data_directory);
   99504       if( zRight[0] ){
   99505         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
   99506       }else{
   99507         sqlite3_data_directory = 0;
   99508       }
   99509 #endif /* SQLITE_OMIT_WSD */
   99510     }
   99511     break;
   99512   }
   99513 #endif
   99514 
   99515 #if SQLITE_ENABLE_LOCKING_STYLE
   99516   /*
   99517   **   PRAGMA [database.]lock_proxy_file
   99518   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
   99519   **
   99520   ** Return or set the value of the lock_proxy_file flag.  Changing
   99521   ** the value sets a specific file to be used for database access locks.
   99522   **
   99523   */
   99524   case PragTyp_LOCK_PROXY_FILE: {
   99525     if( !zRight ){
   99526       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   99527       char *proxy_file_path = NULL;
   99528       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   99529       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
   99530                            &proxy_file_path);
   99531 
   99532       if( proxy_file_path ){
   99533         sqlite3VdbeSetNumCols(v, 1);
   99534         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   99535                               "lock_proxy_file", SQLITE_STATIC);
   99536         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
   99537         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   99538       }
   99539     }else{
   99540       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   99541       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   99542       int res;
   99543       if( zRight[0] ){
   99544         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   99545                                      zRight);
   99546       } else {
   99547         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   99548                                      NULL);
   99549       }
   99550       if( res!=SQLITE_OK ){
   99551         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
   99552         goto pragma_out;
   99553       }
   99554     }
   99555     break;
   99556   }
   99557 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   99558 
   99559   /*
   99560   **   PRAGMA [database.]synchronous
   99561   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
   99562   **
   99563   ** Return or set the local value of the synchronous flag.  Changing
   99564   ** the local value does not make changes to the disk file and the
   99565   ** default value will be restored the next time the database is
   99566   ** opened.
   99567   */
   99568   case PragTyp_SYNCHRONOUS: {
   99569     if( !zRight ){
   99570       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
   99571     }else{
   99572       if( !db->autoCommit ){
   99573         sqlite3ErrorMsg(pParse,
   99574             "Safety level may not be changed inside a transaction");
   99575       }else{
   99576         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
   99577         setAllPagerFlags(db);
   99578       }
   99579     }
   99580     break;
   99581   }
   99582 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   99583 
   99584 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   99585   case PragTyp_FLAG: {
   99586     if( zRight==0 ){
   99587       returnSingleInt(pParse, aPragmaNames[mid].zName,
   99588                      (db->flags & aPragmaNames[mid].iArg)!=0 );
   99589     }else{
   99590       int mask = aPragmaNames[mid].iArg;    /* Mask of bits to set or clear. */
   99591       if( db->autoCommit==0 ){
   99592         /* Foreign key support may not be enabled or disabled while not
   99593         ** in auto-commit mode.  */
   99594         mask &= ~(SQLITE_ForeignKeys);
   99595       }
   99596 
   99597       if( sqlite3GetBoolean(zRight, 0) ){
   99598         db->flags |= mask;
   99599       }else{
   99600         db->flags &= ~mask;
   99601         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
   99602       }
   99603 
   99604       /* Many of the flag-pragmas modify the code generated by the SQL
   99605       ** compiler (eg. count_changes). So add an opcode to expire all
   99606       ** compiled SQL statements after modifying a pragma value.
   99607       */
   99608       sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   99609       setAllPagerFlags(db);
   99610     }
   99611     break;
   99612   }
   99613 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   99614 
   99615 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
   99616   /*
   99617   **   PRAGMA table_info(<table>)
   99618   **
   99619   ** Return a single row for each column of the named table. The columns of
   99620   ** the returned data set are:
   99621   **
   99622   ** cid:        Column id (numbered from left to right, starting at 0)
   99623   ** name:       Column name
   99624   ** type:       Column declaration type.
   99625   ** notnull:    True if 'NOT NULL' is part of column declaration
   99626   ** dflt_value: The default value for the column, if any.
   99627   */
   99628   case PragTyp_TABLE_INFO: if( zRight ){
   99629     Table *pTab;
   99630     pTab = sqlite3FindTable(db, zRight, zDb);
   99631     if( pTab ){
   99632       int i, k;
   99633       int nHidden = 0;
   99634       Column *pCol;
   99635       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   99636       sqlite3VdbeSetNumCols(v, 6);
   99637       pParse->nMem = 6;
   99638       sqlite3CodeVerifySchema(pParse, iDb);
   99639       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
   99640       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   99641       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
   99642       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
   99643       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
   99644       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
   99645       sqlite3ViewGetColumnNames(pParse, pTab);
   99646       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   99647         if( IsHiddenColumn(pCol) ){
   99648           nHidden++;
   99649           continue;
   99650         }
   99651         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
   99652         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
   99653         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   99654            pCol->zType ? pCol->zType : "", 0);
   99655         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
   99656         if( pCol->zDflt ){
   99657           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
   99658         }else{
   99659           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
   99660         }
   99661         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
   99662           k = 0;
   99663         }else if( pPk==0 ){
   99664           k = 1;
   99665         }else{
   99666           for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
   99667         }
   99668         sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
   99669         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
   99670       }
   99671     }
   99672   }
   99673   break;
   99674 
   99675   case PragTyp_STATS: {
   99676     Index *pIdx;
   99677     HashElem *i;
   99678     v = sqlite3GetVdbe(pParse);
   99679     sqlite3VdbeSetNumCols(v, 4);
   99680     pParse->nMem = 4;
   99681     sqlite3CodeVerifySchema(pParse, iDb);
   99682     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
   99683     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
   99684     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
   99685     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
   99686     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
   99687       Table *pTab = sqliteHashData(i);
   99688       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
   99689       sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
   99690       sqlite3VdbeAddOp2(v, OP_Integer,
   99691                            (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
   99692       sqlite3VdbeAddOp2(v, OP_Integer,
   99693           (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
   99694       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
   99695       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   99696         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
   99697         sqlite3VdbeAddOp2(v, OP_Integer,
   99698                              (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
   99699         sqlite3VdbeAddOp2(v, OP_Integer,
   99700             (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
   99701         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
   99702       }
   99703     }
   99704   }
   99705   break;
   99706 
   99707   case PragTyp_INDEX_INFO: if( zRight ){
   99708     Index *pIdx;
   99709     Table *pTab;
   99710     pIdx = sqlite3FindIndex(db, zRight, zDb);
   99711     if( pIdx ){
   99712       int i;
   99713       pTab = pIdx->pTable;
   99714       sqlite3VdbeSetNumCols(v, 3);
   99715       pParse->nMem = 3;
   99716       sqlite3CodeVerifySchema(pParse, iDb);
   99717       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
   99718       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
   99719       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
   99720       for(i=0; i<pIdx->nKeyCol; i++){
   99721         i16 cnum = pIdx->aiColumn[i];
   99722         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   99723         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
   99724         assert( pTab->nCol>cnum );
   99725         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
   99726         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   99727       }
   99728     }
   99729   }
   99730   break;
   99731 
   99732   case PragTyp_INDEX_LIST: if( zRight ){
   99733     Index *pIdx;
   99734     Table *pTab;
   99735     int i;
   99736     pTab = sqlite3FindTable(db, zRight, zDb);
   99737     if( pTab ){
   99738       v = sqlite3GetVdbe(pParse);
   99739       sqlite3VdbeSetNumCols(v, 3);
   99740       pParse->nMem = 3;
   99741       sqlite3CodeVerifySchema(pParse, iDb);
   99742       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   99743       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   99744       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
   99745       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
   99746         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   99747         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
   99748         sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
   99749         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   99750       }
   99751     }
   99752   }
   99753   break;
   99754 
   99755   case PragTyp_DATABASE_LIST: {
   99756     int i;
   99757     sqlite3VdbeSetNumCols(v, 3);
   99758     pParse->nMem = 3;
   99759     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   99760     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   99761     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
   99762     for(i=0; i<db->nDb; i++){
   99763       if( db->aDb[i].pBt==0 ) continue;
   99764       assert( db->aDb[i].zName!=0 );
   99765       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   99766       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
   99767       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   99768            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
   99769       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   99770     }
   99771   }
   99772   break;
   99773 
   99774   case PragTyp_COLLATION_LIST: {
   99775     int i = 0;
   99776     HashElem *p;
   99777     sqlite3VdbeSetNumCols(v, 2);
   99778     pParse->nMem = 2;
   99779     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   99780     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   99781     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
   99782       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
   99783       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
   99784       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
   99785       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   99786     }
   99787   }
   99788   break;
   99789 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
   99790 
   99791 #ifndef SQLITE_OMIT_FOREIGN_KEY
   99792   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
   99793     FKey *pFK;
   99794     Table *pTab;
   99795     pTab = sqlite3FindTable(db, zRight, zDb);
   99796     if( pTab ){
   99797       v = sqlite3GetVdbe(pParse);
   99798       pFK = pTab->pFKey;
   99799       if( pFK ){
   99800         int i = 0;
   99801         sqlite3VdbeSetNumCols(v, 8);
   99802         pParse->nMem = 8;
   99803         sqlite3CodeVerifySchema(pParse, iDb);
   99804         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
   99805         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
   99806         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
   99807         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
   99808         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
   99809         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
   99810         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
   99811         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
   99812         while(pFK){
   99813           int j;
   99814           for(j=0; j<pFK->nCol; j++){
   99815             char *zCol = pFK->aCol[j].zCol;
   99816             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
   99817             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
   99818             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   99819             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
   99820             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
   99821             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   99822                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
   99823             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
   99824             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
   99825             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
   99826             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
   99827             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
   99828           }
   99829           ++i;
   99830           pFK = pFK->pNextFrom;
   99831         }
   99832       }
   99833     }
   99834   }
   99835   break;
   99836 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   99837 
   99838 #ifndef SQLITE_OMIT_FOREIGN_KEY
   99839 #ifndef SQLITE_OMIT_TRIGGER
   99840   case PragTyp_FOREIGN_KEY_CHECK: {
   99841     FKey *pFK;             /* A foreign key constraint */
   99842     Table *pTab;           /* Child table contain "REFERENCES" keyword */
   99843     Table *pParent;        /* Parent table that child points to */
   99844     Index *pIdx;           /* Index in the parent table */
   99845     int i;                 /* Loop counter:  Foreign key number for pTab */
   99846     int j;                 /* Loop counter:  Field of the foreign key */
   99847     HashElem *k;           /* Loop counter:  Next table in schema */
   99848     int x;                 /* result variable */
   99849     int regResult;         /* 3 registers to hold a result row */
   99850     int regKey;            /* Register to hold key for checking the FK */
   99851     int regRow;            /* Registers to hold a row from pTab */
   99852     int addrTop;           /* Top of a loop checking foreign keys */
   99853     int addrOk;            /* Jump here if the key is OK */
   99854     int *aiCols;           /* child to parent column mapping */
   99855 
   99856     regResult = pParse->nMem+1;
   99857     pParse->nMem += 4;
   99858     regKey = ++pParse->nMem;
   99859     regRow = ++pParse->nMem;
   99860     v = sqlite3GetVdbe(pParse);
   99861     sqlite3VdbeSetNumCols(v, 4);
   99862     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
   99863     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
   99864     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
   99865     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
   99866     sqlite3CodeVerifySchema(pParse, iDb);
   99867     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
   99868     while( k ){
   99869       if( zRight ){
   99870         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
   99871         k = 0;
   99872       }else{
   99873         pTab = (Table*)sqliteHashData(k);
   99874         k = sqliteHashNext(k);
   99875       }
   99876       if( pTab==0 || pTab->pFKey==0 ) continue;
   99877       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   99878       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
   99879       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
   99880       sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
   99881                         P4_TRANSIENT);
   99882       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
   99883         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
   99884         if( pParent==0 ) continue;
   99885         pIdx = 0;
   99886         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
   99887         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
   99888         if( x==0 ){
   99889           if( pIdx==0 ){
   99890             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
   99891           }else{
   99892             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
   99893             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   99894           }
   99895         }else{
   99896           k = 0;
   99897           break;
   99898         }
   99899       }
   99900       assert( pParse->nErr>0 || pFK==0 );
   99901       if( pFK ) break;
   99902       if( pParse->nTab<i ) pParse->nTab = i;
   99903       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
   99904       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
   99905         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
   99906         pIdx = 0;
   99907         aiCols = 0;
   99908         if( pParent ){
   99909           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
   99910           assert( x==0 );
   99911         }
   99912         addrOk = sqlite3VdbeMakeLabel(v);
   99913         if( pParent && pIdx==0 ){
   99914           int iKey = pFK->aCol[0].iFrom;
   99915           assert( iKey>=0 && iKey<pTab->nCol );
   99916           if( iKey!=pTab->iPKey ){
   99917             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
   99918             sqlite3ColumnDefault(v, pTab, iKey, regRow);
   99919             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
   99920             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
   99921                sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
   99922           }else{
   99923             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
   99924           }
   99925           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
   99926           sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
   99927           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   99928         }else{
   99929           for(j=0; j<pFK->nCol; j++){
   99930             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
   99931                             aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
   99932             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
   99933           }
   99934           if( pParent ){
   99935             sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
   99936                               sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
   99937             sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
   99938             VdbeCoverage(v);
   99939           }
   99940         }
   99941         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
   99942         sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
   99943                           pFK->zTo, P4_TRANSIENT);
   99944         sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
   99945         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
   99946         sqlite3VdbeResolveLabel(v, addrOk);
   99947         sqlite3DbFree(db, aiCols);
   99948       }
   99949       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
   99950       sqlite3VdbeJumpHere(v, addrTop);
   99951     }
   99952   }
   99953   break;
   99954 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   99955 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   99956 
   99957 #ifndef NDEBUG
   99958   case PragTyp_PARSER_TRACE: {
   99959     if( zRight ){
   99960       if( sqlite3GetBoolean(zRight, 0) ){
   99961         sqlite3ParserTrace(stderr, "parser: ");
   99962       }else{
   99963         sqlite3ParserTrace(0, 0);
   99964       }
   99965     }
   99966   }
   99967   break;
   99968 #endif
   99969 
   99970   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
   99971   ** used will be case sensitive or not depending on the RHS.
   99972   */
   99973   case PragTyp_CASE_SENSITIVE_LIKE: {
   99974     if( zRight ){
   99975       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
   99976     }
   99977   }
   99978   break;
   99979 
   99980 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   99981 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
   99982 #endif
   99983 
   99984 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   99985   /* Pragma "quick_check" is reduced version of
   99986   ** integrity_check designed to detect most database corruption
   99987   ** without most of the overhead of a full integrity-check.
   99988   */
   99989   case PragTyp_INTEGRITY_CHECK: {
   99990     int i, j, addr, mxErr;
   99991 
   99992     /* Code that appears at the end of the integrity check.  If no error
   99993     ** messages have been generated, output OK.  Otherwise output the
   99994     ** error message
   99995     */
   99996     static const int iLn = VDBE_OFFSET_LINENO(2);
   99997     static const VdbeOpList endCode[] = {
   99998       { OP_IfNeg,       1, 0,        0},    /* 0 */
   99999       { OP_String8,     0, 3,        0},    /* 1 */
   100000       { OP_ResultRow,   3, 1,        0},
   100001     };
   100002 
   100003     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
   100004 
   100005     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
   100006     ** then iDb is set to the index of the database identified by <db>.
   100007     ** In this case, the integrity of database iDb only is verified by
   100008     ** the VDBE created below.
   100009     **
   100010     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
   100011     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
   100012     ** to -1 here, to indicate that the VDBE should verify the integrity
   100013     ** of all attached databases.  */
   100014     assert( iDb>=0 );
   100015     assert( iDb==0 || pId2->z );
   100016     if( pId2->z==0 ) iDb = -1;
   100017 
   100018     /* Initialize the VDBE program */
   100019     pParse->nMem = 6;
   100020     sqlite3VdbeSetNumCols(v, 1);
   100021     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
   100022 
   100023     /* Set the maximum error count */
   100024     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   100025     if( zRight ){
   100026       sqlite3GetInt32(zRight, &mxErr);
   100027       if( mxErr<=0 ){
   100028         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   100029       }
   100030     }
   100031     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
   100032 
   100033     /* Do an integrity check on each database file */
   100034     for(i=0; i<db->nDb; i++){
   100035       HashElem *x;
   100036       Hash *pTbls;
   100037       int cnt = 0;
   100038 
   100039       if( OMIT_TEMPDB && i==1 ) continue;
   100040       if( iDb>=0 && i!=iDb ) continue;
   100041 
   100042       sqlite3CodeVerifySchema(pParse, i);
   100043       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
   100044       VdbeCoverage(v);
   100045       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   100046       sqlite3VdbeJumpHere(v, addr);
   100047 
   100048       /* Do an integrity check of the B-Tree
   100049       **
   100050       ** Begin by filling registers 2, 3, ... with the root pages numbers
   100051       ** for all tables and indices in the database.
   100052       */
   100053       assert( sqlite3SchemaMutexHeld(db, i, 0) );
   100054       pTbls = &db->aDb[i].pSchema->tblHash;
   100055       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   100056         Table *pTab = sqliteHashData(x);
   100057         Index *pIdx;
   100058         if( HasRowid(pTab) ){
   100059           sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
   100060           VdbeComment((v, "%s", pTab->zName));
   100061           cnt++;
   100062         }
   100063         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   100064           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
   100065           VdbeComment((v, "%s", pIdx->zName));
   100066           cnt++;
   100067         }
   100068       }
   100069 
   100070       /* Make sure sufficient number of registers have been allocated */
   100071       pParse->nMem = MAX( pParse->nMem, cnt+8 );
   100072 
   100073       /* Do the b-tree integrity checks */
   100074       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
   100075       sqlite3VdbeChangeP5(v, (u8)i);
   100076       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
   100077       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   100078          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
   100079          P4_DYNAMIC);
   100080       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
   100081       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
   100082       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
   100083       sqlite3VdbeJumpHere(v, addr);
   100084 
   100085       /* Make sure all the indices are constructed correctly.
   100086       */
   100087       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
   100088         Table *pTab = sqliteHashData(x);
   100089         Index *pIdx, *pPk;
   100090         Index *pPrior = 0;
   100091         int loopTop;
   100092         int iDataCur, iIdxCur;
   100093         int r1 = -1;
   100094 
   100095         if( pTab->pIndex==0 ) continue;
   100096         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   100097         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
   100098         VdbeCoverage(v);
   100099         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   100100         sqlite3VdbeJumpHere(v, addr);
   100101         sqlite3ExprCacheClear(pParse);
   100102         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
   100103                                    1, 0, &iDataCur, &iIdxCur);
   100104         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
   100105         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   100106           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
   100107         }
   100108         pParse->nMem = MAX(pParse->nMem, 8+j);
   100109         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
   100110         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
   100111         /* Verify that all NOT NULL columns really are NOT NULL */
   100112         for(j=0; j<pTab->nCol; j++){
   100113           char *zErr;
   100114           int jmp2, jmp3;
   100115           if( j==pTab->iPKey ) continue;
   100116           if( pTab->aCol[j].notNull==0 ) continue;
   100117           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
   100118           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
   100119           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
   100120           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
   100121           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
   100122                               pTab->aCol[j].zName);
   100123           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
   100124           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
   100125           jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
   100126           sqlite3VdbeAddOp0(v, OP_Halt);
   100127           sqlite3VdbeJumpHere(v, jmp2);
   100128           sqlite3VdbeJumpHere(v, jmp3);
   100129         }
   100130         /* Validate index entries for the current row */
   100131         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   100132           int jmp2, jmp3, jmp4, jmp5;
   100133           int ckUniq = sqlite3VdbeMakeLabel(v);
   100134           if( pPk==pIdx ) continue;
   100135           r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
   100136                                        pPrior, r1);
   100137           pPrior = pIdx;
   100138           sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
   100139           /* Verify that an index entry exists for the current table row */
   100140           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
   100141                                       pIdx->nColumn); VdbeCoverage(v);
   100142           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
   100143           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
   100144           sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
   100145           sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   100146                             " missing from index ", P4_STATIC);
   100147           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
   100148           jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   100149                                    pIdx->zName, P4_TRANSIENT);
   100150           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
   100151           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
   100152           jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
   100153           sqlite3VdbeAddOp0(v, OP_Halt);
   100154           sqlite3VdbeJumpHere(v, jmp2);
   100155           /* For UNIQUE indexes, verify that only one entry exists with the
   100156           ** current key.  The entry is unique if (1) any column is NULL
   100157           ** or (2) the next entry has a different key */
   100158           if( IsUniqueIndex(pIdx) ){
   100159             int uniqOk = sqlite3VdbeMakeLabel(v);
   100160             int jmp6;
   100161             int kk;
   100162             for(kk=0; kk<pIdx->nKeyCol; kk++){
   100163               int iCol = pIdx->aiColumn[kk];
   100164               assert( iCol>=0 && iCol<pTab->nCol );
   100165               if( pTab->aCol[iCol].notNull ) continue;
   100166               sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
   100167               VdbeCoverage(v);
   100168             }
   100169             jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
   100170             sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
   100171             sqlite3VdbeJumpHere(v, jmp6);
   100172             sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
   100173                                  pIdx->nKeyCol); VdbeCoverage(v);
   100174             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
   100175             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   100176                               "non-unique entry in index ", P4_STATIC);
   100177             sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
   100178             sqlite3VdbeResolveLabel(v, uniqOk);
   100179           }
   100180           sqlite3VdbeJumpHere(v, jmp4);
   100181           sqlite3ResolvePartIdxLabel(pParse, jmp3);
   100182         }
   100183         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
   100184         sqlite3VdbeJumpHere(v, loopTop-1);
   100185 #ifndef SQLITE_OMIT_BTREECOUNT
   100186         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
   100187                      "wrong # of entries in index ", P4_STATIC);
   100188         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   100189           if( pPk==pIdx ) continue;
   100190           addr = sqlite3VdbeCurrentAddr(v);
   100191           sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
   100192           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   100193           sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
   100194           sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
   100195           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   100196           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   100197           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
   100198           sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
   100199           sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
   100200         }
   100201 #endif /* SQLITE_OMIT_BTREECOUNT */
   100202       }
   100203     }
   100204     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
   100205     sqlite3VdbeChangeP3(v, addr, -mxErr);
   100206     sqlite3VdbeJumpHere(v, addr);
   100207     sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
   100208   }
   100209   break;
   100210 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   100211 
   100212 #ifndef SQLITE_OMIT_UTF16
   100213   /*
   100214   **   PRAGMA encoding
   100215   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
   100216   **
   100217   ** In its first form, this pragma returns the encoding of the main
   100218   ** database. If the database is not initialized, it is initialized now.
   100219   **
   100220   ** The second form of this pragma is a no-op if the main database file
   100221   ** has not already been initialized. In this case it sets the default
   100222   ** encoding that will be used for the main database file if a new file
   100223   ** is created. If an existing main database file is opened, then the
   100224   ** default text encoding for the existing database is used.
   100225   **
   100226   ** In all cases new databases created using the ATTACH command are
   100227   ** created to use the same default text encoding as the main database. If
   100228   ** the main database has not been initialized and/or created when ATTACH
   100229   ** is executed, this is done before the ATTACH operation.
   100230   **
   100231   ** In the second form this pragma sets the text encoding to be used in
   100232   ** new database files created using this database handle. It is only
   100233   ** useful if invoked immediately after the main database i
   100234   */
   100235   case PragTyp_ENCODING: {
   100236     static const struct EncName {
   100237       char *zName;
   100238       u8 enc;
   100239     } encnames[] = {
   100240       { "UTF8",     SQLITE_UTF8        },
   100241       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
   100242       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
   100243       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
   100244       { "UTF16le",  SQLITE_UTF16LE     },
   100245       { "UTF16be",  SQLITE_UTF16BE     },
   100246       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
   100247       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
   100248       { 0, 0 }
   100249     };
   100250     const struct EncName *pEnc;
   100251     if( !zRight ){    /* "PRAGMA encoding" */
   100252       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   100253       sqlite3VdbeSetNumCols(v, 1);
   100254       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
   100255       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
   100256       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
   100257       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
   100258       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
   100259       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
   100260       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   100261     }else{                        /* "PRAGMA encoding = XXX" */
   100262       /* Only change the value of sqlite.enc if the database handle is not
   100263       ** initialized. If the main database exists, the new sqlite.enc value
   100264       ** will be overwritten when the schema is next loaded. If it does not
   100265       ** already exists, it will be created to use the new encoding value.
   100266       */
   100267       if(
   100268         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
   100269         DbHasProperty(db, 0, DB_Empty)
   100270       ){
   100271         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
   100272           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
   100273             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
   100274             break;
   100275           }
   100276         }
   100277         if( !pEnc->zName ){
   100278           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
   100279         }
   100280       }
   100281     }
   100282   }
   100283   break;
   100284 #endif /* SQLITE_OMIT_UTF16 */
   100285 
   100286 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   100287   /*
   100288   **   PRAGMA [database.]schema_version
   100289   **   PRAGMA [database.]schema_version = <integer>
   100290   **
   100291   **   PRAGMA [database.]user_version
   100292   **   PRAGMA [database.]user_version = <integer>
   100293   **
   100294   **   PRAGMA [database.]freelist_count = <integer>
   100295   **
   100296   **   PRAGMA [database.]application_id
   100297   **   PRAGMA [database.]application_id = <integer>
   100298   **
   100299   ** The pragma's schema_version and user_version are used to set or get
   100300   ** the value of the schema-version and user-version, respectively. Both
   100301   ** the schema-version and the user-version are 32-bit signed integers
   100302   ** stored in the database header.
   100303   **
   100304   ** The schema-cookie is usually only manipulated internally by SQLite. It
   100305   ** is incremented by SQLite whenever the database schema is modified (by
   100306   ** creating or dropping a table or index). The schema version is used by
   100307   ** SQLite each time a query is executed to ensure that the internal cache
   100308   ** of the schema used when compiling the SQL query matches the schema of
   100309   ** the database against which the compiled query is actually executed.
   100310   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
   100311   ** the schema-version is potentially dangerous and may lead to program
   100312   ** crashes or database corruption. Use with caution!
   100313   **
   100314   ** The user-version is not used internally by SQLite. It may be used by
   100315   ** applications for any purpose.
   100316   */
   100317   case PragTyp_HEADER_VALUE: {
   100318     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
   100319     sqlite3VdbeUsesBtree(v, iDb);
   100320     switch( zLeft[0] ){
   100321       case 'a': case 'A':
   100322         iCookie = BTREE_APPLICATION_ID;
   100323         break;
   100324       case 'f': case 'F':
   100325         iCookie = BTREE_FREE_PAGE_COUNT;
   100326         break;
   100327       case 's': case 'S':
   100328         iCookie = BTREE_SCHEMA_VERSION;
   100329         break;
   100330       default:
   100331         iCookie = BTREE_USER_VERSION;
   100332         break;
   100333     }
   100334 
   100335     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
   100336       /* Write the specified cookie value */
   100337       static const VdbeOpList setCookie[] = {
   100338         { OP_Transaction,    0,  1,  0},    /* 0 */
   100339         { OP_Integer,        0,  1,  0},    /* 1 */
   100340         { OP_SetCookie,      0,  0,  1},    /* 2 */
   100341       };
   100342       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
   100343       sqlite3VdbeChangeP1(v, addr, iDb);
   100344       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
   100345       sqlite3VdbeChangeP1(v, addr+2, iDb);
   100346       sqlite3VdbeChangeP2(v, addr+2, iCookie);
   100347     }else{
   100348       /* Read the specified cookie value */
   100349       static const VdbeOpList readCookie[] = {
   100350         { OP_Transaction,     0,  0,  0},    /* 0 */
   100351         { OP_ReadCookie,      0,  1,  0},    /* 1 */
   100352         { OP_ResultRow,       1,  1,  0}
   100353       };
   100354       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
   100355       sqlite3VdbeChangeP1(v, addr, iDb);
   100356       sqlite3VdbeChangeP1(v, addr+1, iDb);
   100357       sqlite3VdbeChangeP3(v, addr+1, iCookie);
   100358       sqlite3VdbeSetNumCols(v, 1);
   100359       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   100360     }
   100361   }
   100362   break;
   100363 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
   100364 
   100365 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   100366   /*
   100367   **   PRAGMA compile_options
   100368   **
   100369   ** Return the names of all compile-time options used in this build,
   100370   ** one option per row.
   100371   */
   100372   case PragTyp_COMPILE_OPTIONS: {
   100373     int i = 0;
   100374     const char *zOpt;
   100375     sqlite3VdbeSetNumCols(v, 1);
   100376     pParse->nMem = 1;
   100377     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
   100378     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
   100379       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
   100380       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   100381     }
   100382   }
   100383   break;
   100384 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   100385 
   100386 #ifndef SQLITE_OMIT_WAL
   100387   /*
   100388   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
   100389   **
   100390   ** Checkpoint the database.
   100391   */
   100392   case PragTyp_WAL_CHECKPOINT: {
   100393     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
   100394     int eMode = SQLITE_CHECKPOINT_PASSIVE;
   100395     if( zRight ){
   100396       if( sqlite3StrICmp(zRight, "full")==0 ){
   100397         eMode = SQLITE_CHECKPOINT_FULL;
   100398       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
   100399         eMode = SQLITE_CHECKPOINT_RESTART;
   100400       }
   100401     }
   100402     sqlite3VdbeSetNumCols(v, 3);
   100403     pParse->nMem = 3;
   100404     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
   100405     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
   100406     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
   100407 
   100408     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
   100409     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   100410   }
   100411   break;
   100412 
   100413   /*
   100414   **   PRAGMA wal_autocheckpoint
   100415   **   PRAGMA wal_autocheckpoint = N
   100416   **
   100417   ** Configure a database connection to automatically checkpoint a database
   100418   ** after accumulating N frames in the log. Or query for the current value
   100419   ** of N.
   100420   */
   100421   case PragTyp_WAL_AUTOCHECKPOINT: {
   100422     if( zRight ){
   100423       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
   100424     }
   100425     returnSingleInt(pParse, "wal_autocheckpoint",
   100426        db->xWalCallback==sqlite3WalDefaultHook ?
   100427            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
   100428   }
   100429   break;
   100430 #endif
   100431 
   100432   /*
   100433   **  PRAGMA shrink_memory
   100434   **
   100435   ** This pragma attempts to free as much memory as possible from the
   100436   ** current database connection.
   100437   */
   100438   case PragTyp_SHRINK_MEMORY: {
   100439     sqlite3_db_release_memory(db);
   100440     break;
   100441   }
   100442 
   100443   /*
   100444   **   PRAGMA busy_timeout
   100445   **   PRAGMA busy_timeout = N
   100446   **
   100447   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
   100448   ** if one is set.  If no busy handler or a different busy handler is set
   100449   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
   100450   ** disables the timeout.
   100451   */
   100452   /*case PragTyp_BUSY_TIMEOUT*/ default: {
   100453     assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
   100454     if( zRight ){
   100455       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
   100456     }
   100457     returnSingleInt(pParse, "timeout",  db->busyTimeout);
   100458     break;
   100459   }
   100460 
   100461   /*
   100462   **   PRAGMA soft_heap_limit
   100463   **   PRAGMA soft_heap_limit = N
   100464   **
   100465   ** Call sqlite3_soft_heap_limit64(N).  Return the result.  If N is omitted,
   100466   ** use -1.
   100467   */
   100468   case PragTyp_SOFT_HEAP_LIMIT: {
   100469     sqlite3_int64 N;
   100470     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
   100471       sqlite3_soft_heap_limit64(N);
   100472     }
   100473     returnSingleInt(pParse, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
   100474     break;
   100475   }
   100476 
   100477 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   100478   /*
   100479   ** Report the current state of file logs for all databases
   100480   */
   100481   case PragTyp_LOCK_STATUS: {
   100482     static const char *const azLockName[] = {
   100483       "unlocked", "shared", "reserved", "pending", "exclusive"
   100484     };
   100485     int i;
   100486     sqlite3VdbeSetNumCols(v, 2);
   100487     pParse->nMem = 2;
   100488     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
   100489     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
   100490     for(i=0; i<db->nDb; i++){
   100491       Btree *pBt;
   100492       const char *zState = "unknown";
   100493       int j;
   100494       if( db->aDb[i].zName==0 ) continue;
   100495       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
   100496       pBt = db->aDb[i].pBt;
   100497       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
   100498         zState = "closed";
   100499       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
   100500                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
   100501          zState = azLockName[j];
   100502       }
   100503       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
   100504       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   100505     }
   100506     break;
   100507   }
   100508 #endif
   100509 
   100510 #ifdef SQLITE_HAS_CODEC
   100511   case PragTyp_KEY: {
   100512     if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
   100513     break;
   100514   }
   100515   case PragTyp_REKEY: {
   100516     if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
   100517     break;
   100518   }
   100519   case PragTyp_HEXKEY: {
   100520     if( zRight ){
   100521       u8 iByte;
   100522       int i;
   100523       char zKey[40];
   100524       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
   100525         iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
   100526         if( (i&1)!=0 ) zKey[i/2] = iByte;
   100527       }
   100528       if( (zLeft[3] & 0xf)==0xb ){
   100529         sqlite3_key_v2(db, zDb, zKey, i/2);
   100530       }else{
   100531         sqlite3_rekey_v2(db, zDb, zKey, i/2);
   100532       }
   100533     }
   100534     break;
   100535   }
   100536 #endif
   100537 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   100538   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
   100539 #ifdef SQLITE_HAS_CODEC
   100540     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
   100541       sqlite3_activate_see(&zRight[4]);
   100542     }
   100543 #endif
   100544 #ifdef SQLITE_ENABLE_CEROD
   100545     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
   100546       sqlite3_activate_cerod(&zRight[6]);
   100547     }
   100548 #endif
   100549   }
   100550   break;
   100551 #endif
   100552 
   100553   } /* End of the PRAGMA switch */
   100554 
   100555 pragma_out:
   100556   sqlite3DbFree(db, zLeft);
   100557   sqlite3DbFree(db, zRight);
   100558 }
   100559 
   100560 #endif /* SQLITE_OMIT_PRAGMA */
   100561 
   100562 /************** End of pragma.c **********************************************/
   100563 /************** Begin file prepare.c *****************************************/
   100564 /*
   100565 ** 2005 May 25
   100566 **
   100567 ** The author disclaims copyright to this source code.  In place of
   100568 ** a legal notice, here is a blessing:
   100569 **
   100570 **    May you do good and not evil.
   100571 **    May you find forgiveness for yourself and forgive others.
   100572 **    May you share freely, never taking more than you give.
   100573 **
   100574 *************************************************************************
   100575 ** This file contains the implementation of the sqlite3_prepare()
   100576 ** interface, and routines that contribute to loading the database schema
   100577 ** from disk.
   100578 */
   100579 
   100580 /*
   100581 ** Fill the InitData structure with an error message that indicates
   100582 ** that the database is corrupt.
   100583 */
   100584 static void corruptSchema(
   100585   InitData *pData,     /* Initialization context */
   100586   const char *zObj,    /* Object being parsed at the point of error */
   100587   const char *zExtra   /* Error information */
   100588 ){
   100589   sqlite3 *db = pData->db;
   100590   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
   100591     if( zObj==0 ) zObj = "?";
   100592     sqlite3SetString(pData->pzErrMsg, db,
   100593       "malformed database schema (%s)", zObj);
   100594     if( zExtra ){
   100595       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
   100596                                  "%s - %s", *pData->pzErrMsg, zExtra);
   100597     }
   100598   }
   100599   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
   100600 }
   100601 
   100602 /*
   100603 ** This is the callback routine for the code that initializes the
   100604 ** database.  See sqlite3Init() below for additional information.
   100605 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
   100606 **
   100607 ** Each callback contains the following information:
   100608 **
   100609 **     argv[0] = name of thing being created
   100610 **     argv[1] = root page number for table or index. 0 for trigger or view.
   100611 **     argv[2] = SQL text for the CREATE statement.
   100612 **
   100613 */
   100614 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
   100615   InitData *pData = (InitData*)pInit;
   100616   sqlite3 *db = pData->db;
   100617   int iDb = pData->iDb;
   100618 
   100619   assert( argc==3 );
   100620   UNUSED_PARAMETER2(NotUsed, argc);
   100621   assert( sqlite3_mutex_held(db->mutex) );
   100622   DbClearProperty(db, iDb, DB_Empty);
   100623   if( db->mallocFailed ){
   100624     corruptSchema(pData, argv[0], 0);
   100625     return 1;
   100626   }
   100627 
   100628   assert( iDb>=0 && iDb<db->nDb );
   100629   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   100630   if( argv[1]==0 ){
   100631     corruptSchema(pData, argv[0], 0);
   100632   }else if( argv[2] && argv[2][0] ){
   100633     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
   100634     ** But because db->init.busy is set to 1, no VDBE code is generated
   100635     ** or executed.  All the parser does is build the internal data
   100636     ** structures that describe the table, index, or view.
   100637     */
   100638     int rc;
   100639     sqlite3_stmt *pStmt;
   100640     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
   100641 
   100642     assert( db->init.busy );
   100643     db->init.iDb = iDb;
   100644     db->init.newTnum = sqlite3Atoi(argv[1]);
   100645     db->init.orphanTrigger = 0;
   100646     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
   100647     rc = db->errCode;
   100648     assert( (rc&0xFF)==(rcp&0xFF) );
   100649     db->init.iDb = 0;
   100650     if( SQLITE_OK!=rc ){
   100651       if( db->init.orphanTrigger ){
   100652         assert( iDb==1 );
   100653       }else{
   100654         pData->rc = rc;
   100655         if( rc==SQLITE_NOMEM ){
   100656           db->mallocFailed = 1;
   100657         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
   100658           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
   100659         }
   100660       }
   100661     }
   100662     sqlite3_finalize(pStmt);
   100663   }else if( argv[0]==0 ){
   100664     corruptSchema(pData, 0, 0);
   100665   }else{
   100666     /* If the SQL column is blank it means this is an index that
   100667     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   100668     ** constraint for a CREATE TABLE.  The index should have already
   100669     ** been created when we processed the CREATE TABLE.  All we have
   100670     ** to do here is record the root page number for that index.
   100671     */
   100672     Index *pIndex;
   100673     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
   100674     if( pIndex==0 ){
   100675       /* This can occur if there exists an index on a TEMP table which
   100676       ** has the same name as another index on a permanent index.  Since
   100677       ** the permanent table is hidden by the TEMP table, we can also
   100678       ** safely ignore the index on the permanent table.
   100679       */
   100680       /* Do Nothing */;
   100681     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
   100682       corruptSchema(pData, argv[0], "invalid rootpage");
   100683     }
   100684   }
   100685   return 0;
   100686 }
   100687 
   100688 /*
   100689 ** Attempt to read the database schema and initialize internal
   100690 ** data structures for a single database file.  The index of the
   100691 ** database file is given by iDb.  iDb==0 is used for the main
   100692 ** database.  iDb==1 should never be used.  iDb>=2 is used for
   100693 ** auxiliary databases.  Return one of the SQLITE_ error codes to
   100694 ** indicate success or failure.
   100695 */
   100696 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
   100697   int rc;
   100698   int i;
   100699 #ifndef SQLITE_OMIT_DEPRECATED
   100700   int size;
   100701 #endif
   100702   Table *pTab;
   100703   Db *pDb;
   100704   char const *azArg[4];
   100705   int meta[5];
   100706   InitData initData;
   100707   char const *zMasterSchema;
   100708   char const *zMasterName;
   100709   int openedTransaction = 0;
   100710 
   100711   /*
   100712   ** The master database table has a structure like this
   100713   */
   100714   static const char master_schema[] =
   100715      "CREATE TABLE sqlite_master(\n"
   100716      "  type text,\n"
   100717      "  name text,\n"
   100718      "  tbl_name text,\n"
   100719      "  rootpage integer,\n"
   100720      "  sql text\n"
   100721      ")"
   100722   ;
   100723 #ifndef SQLITE_OMIT_TEMPDB
   100724   static const char temp_master_schema[] =
   100725      "CREATE TEMP TABLE sqlite_temp_master(\n"
   100726      "  type text,\n"
   100727      "  name text,\n"
   100728      "  tbl_name text,\n"
   100729      "  rootpage integer,\n"
   100730      "  sql text\n"
   100731      ")"
   100732   ;
   100733 #else
   100734   #define temp_master_schema 0
   100735 #endif
   100736 
   100737   assert( iDb>=0 && iDb<db->nDb );
   100738   assert( db->aDb[iDb].pSchema );
   100739   assert( sqlite3_mutex_held(db->mutex) );
   100740   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   100741 
   100742   /* zMasterSchema and zInitScript are set to point at the master schema
   100743   ** and initialisation script appropriate for the database being
   100744   ** initialized. zMasterName is the name of the master table.
   100745   */
   100746   if( !OMIT_TEMPDB && iDb==1 ){
   100747     zMasterSchema = temp_master_schema;
   100748   }else{
   100749     zMasterSchema = master_schema;
   100750   }
   100751   zMasterName = SCHEMA_TABLE(iDb);
   100752 
   100753   /* Construct the schema tables.  */
   100754   azArg[0] = zMasterName;
   100755   azArg[1] = "1";
   100756   azArg[2] = zMasterSchema;
   100757   azArg[3] = 0;
   100758   initData.db = db;
   100759   initData.iDb = iDb;
   100760   initData.rc = SQLITE_OK;
   100761   initData.pzErrMsg = pzErrMsg;
   100762   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
   100763   if( initData.rc ){
   100764     rc = initData.rc;
   100765     goto error_out;
   100766   }
   100767   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
   100768   if( ALWAYS(pTab) ){
   100769     pTab->tabFlags |= TF_Readonly;
   100770   }
   100771 
   100772   /* Create a cursor to hold the database open
   100773   */
   100774   pDb = &db->aDb[iDb];
   100775   if( pDb->pBt==0 ){
   100776     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
   100777       DbSetProperty(db, 1, DB_SchemaLoaded);
   100778     }
   100779     return SQLITE_OK;
   100780   }
   100781 
   100782   /* If there is not already a read-only (or read-write) transaction opened
   100783   ** on the b-tree database, open one now. If a transaction is opened, it
   100784   ** will be closed before this function returns.  */
   100785   sqlite3BtreeEnter(pDb->pBt);
   100786   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
   100787     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
   100788     if( rc!=SQLITE_OK ){
   100789       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
   100790       goto initone_error_out;
   100791     }
   100792     openedTransaction = 1;
   100793   }
   100794 
   100795   /* Get the database meta information.
   100796   **
   100797   ** Meta values are as follows:
   100798   **    meta[0]   Schema cookie.  Changes with each schema change.
   100799   **    meta[1]   File format of schema layer.
   100800   **    meta[2]   Size of the page cache.
   100801   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
   100802   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
   100803   **    meta[5]   User version
   100804   **    meta[6]   Incremental vacuum mode
   100805   **    meta[7]   unused
   100806   **    meta[8]   unused
   100807   **    meta[9]   unused
   100808   **
   100809   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
   100810   ** the possible values of meta[4].
   100811   */
   100812   for(i=0; i<ArraySize(meta); i++){
   100813     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
   100814   }
   100815   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
   100816 
   100817   /* If opening a non-empty database, check the text encoding. For the
   100818   ** main database, set sqlite3.enc to the encoding of the main database.
   100819   ** For an attached db, it is an error if the encoding is not the same
   100820   ** as sqlite3.enc.
   100821   */
   100822   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
   100823     if( iDb==0 ){
   100824 #ifndef SQLITE_OMIT_UTF16
   100825       u8 encoding;
   100826       /* If opening the main database, set ENC(db). */
   100827       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
   100828       if( encoding==0 ) encoding = SQLITE_UTF8;
   100829       ENC(db) = encoding;
   100830 #else
   100831       ENC(db) = SQLITE_UTF8;
   100832 #endif
   100833     }else{
   100834       /* If opening an attached database, the encoding much match ENC(db) */
   100835       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
   100836         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
   100837             " text encoding as main database");
   100838         rc = SQLITE_ERROR;
   100839         goto initone_error_out;
   100840       }
   100841     }
   100842   }else{
   100843     DbSetProperty(db, iDb, DB_Empty);
   100844   }
   100845   pDb->pSchema->enc = ENC(db);
   100846 
   100847   if( pDb->pSchema->cache_size==0 ){
   100848 #ifndef SQLITE_OMIT_DEPRECATED
   100849     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
   100850     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
   100851     pDb->pSchema->cache_size = size;
   100852 #else
   100853     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
   100854 #endif
   100855     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   100856   }
   100857 
   100858   /*
   100859   ** file_format==1    Version 3.0.0.
   100860   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
   100861   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
   100862   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
   100863   */
   100864   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
   100865   if( pDb->pSchema->file_format==0 ){
   100866     pDb->pSchema->file_format = 1;
   100867   }
   100868   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
   100869     sqlite3SetString(pzErrMsg, db, "unsupported file format");
   100870     rc = SQLITE_ERROR;
   100871     goto initone_error_out;
   100872   }
   100873 
   100874   /* Ticket #2804:  When we open a database in the newer file format,
   100875   ** clear the legacy_file_format pragma flag so that a VACUUM will
   100876   ** not downgrade the database and thus invalidate any descending
   100877   ** indices that the user might have created.
   100878   */
   100879   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
   100880     db->flags &= ~SQLITE_LegacyFileFmt;
   100881   }
   100882 
   100883   /* Read the schema information out of the schema tables
   100884   */
   100885   assert( db->init.busy );
   100886   {
   100887     char *zSql;
   100888     zSql = sqlite3MPrintf(db,
   100889         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
   100890         db->aDb[iDb].zName, zMasterName);
   100891 #ifndef SQLITE_OMIT_AUTHORIZATION
   100892     {
   100893       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   100894       xAuth = db->xAuth;
   100895       db->xAuth = 0;
   100896 #endif
   100897       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   100898 #ifndef SQLITE_OMIT_AUTHORIZATION
   100899       db->xAuth = xAuth;
   100900     }
   100901 #endif
   100902     if( rc==SQLITE_OK ) rc = initData.rc;
   100903     sqlite3DbFree(db, zSql);
   100904 #ifndef SQLITE_OMIT_ANALYZE
   100905     if( rc==SQLITE_OK ){
   100906       sqlite3AnalysisLoad(db, iDb);
   100907     }
   100908 #endif
   100909   }
   100910   if( db->mallocFailed ){
   100911     rc = SQLITE_NOMEM;
   100912     sqlite3ResetAllSchemasOfConnection(db);
   100913   }
   100914   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
   100915     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
   100916     ** the schema loaded, even if errors occurred. In this situation the
   100917     ** current sqlite3_prepare() operation will fail, but the following one
   100918     ** will attempt to compile the supplied statement against whatever subset
   100919     ** of the schema was loaded before the error occurred. The primary
   100920     ** purpose of this is to allow access to the sqlite_master table
   100921     ** even when its contents have been corrupted.
   100922     */
   100923     DbSetProperty(db, iDb, DB_SchemaLoaded);
   100924     rc = SQLITE_OK;
   100925   }
   100926 
   100927   /* Jump here for an error that occurs after successfully allocating
   100928   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
   100929   ** before that point, jump to error_out.
   100930   */
   100931 initone_error_out:
   100932   if( openedTransaction ){
   100933     sqlite3BtreeCommit(pDb->pBt);
   100934   }
   100935   sqlite3BtreeLeave(pDb->pBt);
   100936 
   100937 error_out:
   100938   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   100939     db->mallocFailed = 1;
   100940   }
   100941   return rc;
   100942 }
   100943 
   100944 /*
   100945 ** Initialize all database files - the main database file, the file
   100946 ** used to store temporary tables, and any additional database files
   100947 ** created using ATTACH statements.  Return a success code.  If an
   100948 ** error occurs, write an error message into *pzErrMsg.
   100949 **
   100950 ** After a database is initialized, the DB_SchemaLoaded bit is set
   100951 ** bit is set in the flags field of the Db structure. If the database
   100952 ** file was of zero-length, then the DB_Empty flag is also set.
   100953 */
   100954 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
   100955   int i, rc;
   100956   int commit_internal = !(db->flags&SQLITE_InternChanges);
   100957 
   100958   assert( sqlite3_mutex_held(db->mutex) );
   100959   rc = SQLITE_OK;
   100960   db->init.busy = 1;
   100961   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   100962     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
   100963     rc = sqlite3InitOne(db, i, pzErrMsg);
   100964     if( rc ){
   100965       sqlite3ResetOneSchema(db, i);
   100966     }
   100967   }
   100968 
   100969   /* Once all the other databases have been initialized, load the schema
   100970   ** for the TEMP database. This is loaded last, as the TEMP database
   100971   ** schema may contain references to objects in other databases.
   100972   */
   100973 #ifndef SQLITE_OMIT_TEMPDB
   100974   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
   100975                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
   100976     rc = sqlite3InitOne(db, 1, pzErrMsg);
   100977     if( rc ){
   100978       sqlite3ResetOneSchema(db, 1);
   100979     }
   100980   }
   100981 #endif
   100982 
   100983   db->init.busy = 0;
   100984   if( rc==SQLITE_OK && commit_internal ){
   100985     sqlite3CommitInternalChanges(db);
   100986   }
   100987 
   100988   return rc;
   100989 }
   100990 
   100991 /*
   100992 ** This routine is a no-op if the database schema is already initialized.
   100993 ** Otherwise, the schema is loaded. An error code is returned.
   100994 */
   100995 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
   100996   int rc = SQLITE_OK;
   100997   sqlite3 *db = pParse->db;
   100998   assert( sqlite3_mutex_held(db->mutex) );
   100999   if( !db->init.busy ){
   101000     rc = sqlite3Init(db, &pParse->zErrMsg);
   101001   }
   101002   if( rc!=SQLITE_OK ){
   101003     pParse->rc = rc;
   101004     pParse->nErr++;
   101005   }
   101006   return rc;
   101007 }
   101008 
   101009 
   101010 /*
   101011 ** Check schema cookies in all databases.  If any cookie is out
   101012 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
   101013 ** make no changes to pParse->rc.
   101014 */
   101015 static void schemaIsValid(Parse *pParse){
   101016   sqlite3 *db = pParse->db;
   101017   int iDb;
   101018   int rc;
   101019   int cookie;
   101020 
   101021   assert( pParse->checkSchema );
   101022   assert( sqlite3_mutex_held(db->mutex) );
   101023   for(iDb=0; iDb<db->nDb; iDb++){
   101024     int openedTransaction = 0;         /* True if a transaction is opened */
   101025     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
   101026     if( pBt==0 ) continue;
   101027 
   101028     /* If there is not already a read-only (or read-write) transaction opened
   101029     ** on the b-tree database, open one now. If a transaction is opened, it
   101030     ** will be closed immediately after reading the meta-value. */
   101031     if( !sqlite3BtreeIsInReadTrans(pBt) ){
   101032       rc = sqlite3BtreeBeginTrans(pBt, 0);
   101033       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   101034         db->mallocFailed = 1;
   101035       }
   101036       if( rc!=SQLITE_OK ) return;
   101037       openedTransaction = 1;
   101038     }
   101039 
   101040     /* Read the schema cookie from the database. If it does not match the
   101041     ** value stored as part of the in-memory schema representation,
   101042     ** set Parse.rc to SQLITE_SCHEMA. */
   101043     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
   101044     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   101045     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
   101046       sqlite3ResetOneSchema(db, iDb);
   101047       pParse->rc = SQLITE_SCHEMA;
   101048     }
   101049 
   101050     /* Close the transaction, if one was opened. */
   101051     if( openedTransaction ){
   101052       sqlite3BtreeCommit(pBt);
   101053     }
   101054   }
   101055 }
   101056 
   101057 /*
   101058 ** Convert a schema pointer into the iDb index that indicates
   101059 ** which database file in db->aDb[] the schema refers to.
   101060 **
   101061 ** If the same database is attached more than once, the first
   101062 ** attached database is returned.
   101063 */
   101064 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
   101065   int i = -1000000;
   101066 
   101067   /* If pSchema is NULL, then return -1000000. This happens when code in
   101068   ** expr.c is trying to resolve a reference to a transient table (i.e. one
   101069   ** created by a sub-select). In this case the return value of this
   101070   ** function should never be used.
   101071   **
   101072   ** We return -1000000 instead of the more usual -1 simply because using
   101073   ** -1000000 as the incorrect index into db->aDb[] is much
   101074   ** more likely to cause a segfault than -1 (of course there are assert()
   101075   ** statements too, but it never hurts to play the odds).
   101076   */
   101077   assert( sqlite3_mutex_held(db->mutex) );
   101078   if( pSchema ){
   101079     for(i=0; ALWAYS(i<db->nDb); i++){
   101080       if( db->aDb[i].pSchema==pSchema ){
   101081         break;
   101082       }
   101083     }
   101084     assert( i>=0 && i<db->nDb );
   101085   }
   101086   return i;
   101087 }
   101088 
   101089 /*
   101090 ** Free all memory allocations in the pParse object
   101091 */
   101092 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
   101093   if( pParse ){
   101094     sqlite3 *db = pParse->db;
   101095     sqlite3DbFree(db, pParse->aLabel);
   101096     sqlite3ExprListDelete(db, pParse->pConstExpr);
   101097   }
   101098 }
   101099 
   101100 /*
   101101 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   101102 */
   101103 static int sqlite3Prepare(
   101104   sqlite3 *db,              /* Database handle. */
   101105   const char *zSql,         /* UTF-8 encoded SQL statement. */
   101106   int nBytes,               /* Length of zSql in bytes. */
   101107   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   101108   Vdbe *pReprepare,         /* VM being reprepared */
   101109   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101110   const char **pzTail       /* OUT: End of parsed string */
   101111 ){
   101112   Parse *pParse;            /* Parsing context */
   101113   char *zErrMsg = 0;        /* Error message */
   101114   int rc = SQLITE_OK;       /* Result code */
   101115   int i;                    /* Loop counter */
   101116 
   101117   /* Allocate the parsing context */
   101118   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   101119   if( pParse==0 ){
   101120     rc = SQLITE_NOMEM;
   101121     goto end_prepare;
   101122   }
   101123   pParse->pReprepare = pReprepare;
   101124   assert( ppStmt && *ppStmt==0 );
   101125   assert( !db->mallocFailed );
   101126   assert( sqlite3_mutex_held(db->mutex) );
   101127 
   101128   /* Check to verify that it is possible to get a read lock on all
   101129   ** database schemas.  The inability to get a read lock indicates that
   101130   ** some other database connection is holding a write-lock, which in
   101131   ** turn means that the other connection has made uncommitted changes
   101132   ** to the schema.
   101133   **
   101134   ** Were we to proceed and prepare the statement against the uncommitted
   101135   ** schema changes and if those schema changes are subsequently rolled
   101136   ** back and different changes are made in their place, then when this
   101137   ** prepared statement goes to run the schema cookie would fail to detect
   101138   ** the schema change.  Disaster would follow.
   101139   **
   101140   ** This thread is currently holding mutexes on all Btrees (because
   101141   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
   101142   ** is not possible for another thread to start a new schema change
   101143   ** while this routine is running.  Hence, we do not need to hold
   101144   ** locks on the schema, we just need to make sure nobody else is
   101145   ** holding them.
   101146   **
   101147   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
   101148   ** but it does *not* override schema lock detection, so this all still
   101149   ** works even if READ_UNCOMMITTED is set.
   101150   */
   101151   for(i=0; i<db->nDb; i++) {
   101152     Btree *pBt = db->aDb[i].pBt;
   101153     if( pBt ){
   101154       assert( sqlite3BtreeHoldsMutex(pBt) );
   101155       rc = sqlite3BtreeSchemaLocked(pBt);
   101156       if( rc ){
   101157         const char *zDb = db->aDb[i].zName;
   101158         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
   101159         testcase( db->flags & SQLITE_ReadUncommitted );
   101160         goto end_prepare;
   101161       }
   101162     }
   101163   }
   101164 
   101165   sqlite3VtabUnlockList(db);
   101166 
   101167   pParse->db = db;
   101168   pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
   101169   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
   101170     char *zSqlCopy;
   101171     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   101172     testcase( nBytes==mxLen );
   101173     testcase( nBytes==mxLen+1 );
   101174     if( nBytes>mxLen ){
   101175       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
   101176       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
   101177       goto end_prepare;
   101178     }
   101179     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
   101180     if( zSqlCopy ){
   101181       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
   101182       sqlite3DbFree(db, zSqlCopy);
   101183       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
   101184     }else{
   101185       pParse->zTail = &zSql[nBytes];
   101186     }
   101187   }else{
   101188     sqlite3RunParser(pParse, zSql, &zErrMsg);
   101189   }
   101190   assert( 0==pParse->nQueryLoop );
   101191 
   101192   if( db->mallocFailed ){
   101193     pParse->rc = SQLITE_NOMEM;
   101194   }
   101195   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
   101196   if( pParse->checkSchema ){
   101197     schemaIsValid(pParse);
   101198   }
   101199   if( db->mallocFailed ){
   101200     pParse->rc = SQLITE_NOMEM;
   101201   }
   101202   if( pzTail ){
   101203     *pzTail = pParse->zTail;
   101204   }
   101205   rc = pParse->rc;
   101206 
   101207 #ifndef SQLITE_OMIT_EXPLAIN
   101208   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
   101209     static const char * const azColName[] = {
   101210        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
   101211        "selectid", "order", "from", "detail"
   101212     };
   101213     int iFirst, mx;
   101214     if( pParse->explain==2 ){
   101215       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
   101216       iFirst = 8;
   101217       mx = 12;
   101218     }else{
   101219       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
   101220       iFirst = 0;
   101221       mx = 8;
   101222     }
   101223     for(i=iFirst; i<mx; i++){
   101224       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
   101225                             azColName[i], SQLITE_STATIC);
   101226     }
   101227   }
   101228 #endif
   101229 
   101230   if( db->init.busy==0 ){
   101231     Vdbe *pVdbe = pParse->pVdbe;
   101232     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
   101233   }
   101234   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
   101235     sqlite3VdbeFinalize(pParse->pVdbe);
   101236     assert(!(*ppStmt));
   101237   }else{
   101238     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
   101239   }
   101240 
   101241   if( zErrMsg ){
   101242     sqlite3Error(db, rc, "%s", zErrMsg);
   101243     sqlite3DbFree(db, zErrMsg);
   101244   }else{
   101245     sqlite3Error(db, rc, 0);
   101246   }
   101247 
   101248   /* Delete any TriggerPrg structures allocated while parsing this statement. */
   101249   while( pParse->pTriggerPrg ){
   101250     TriggerPrg *pT = pParse->pTriggerPrg;
   101251     pParse->pTriggerPrg = pT->pNext;
   101252     sqlite3DbFree(db, pT);
   101253   }
   101254 
   101255 end_prepare:
   101256 
   101257   sqlite3ParserReset(pParse);
   101258   sqlite3StackFree(db, pParse);
   101259   rc = sqlite3ApiExit(db, rc);
   101260   assert( (rc&db->errMask)==rc );
   101261   return rc;
   101262 }
   101263 static int sqlite3LockAndPrepare(
   101264   sqlite3 *db,              /* Database handle. */
   101265   const char *zSql,         /* UTF-8 encoded SQL statement. */
   101266   int nBytes,               /* Length of zSql in bytes. */
   101267   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   101268   Vdbe *pOld,               /* VM being reprepared */
   101269   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101270   const char **pzTail       /* OUT: End of parsed string */
   101271 ){
   101272   int rc;
   101273   assert( ppStmt!=0 );
   101274   *ppStmt = 0;
   101275   if( !sqlite3SafetyCheckOk(db) ){
   101276     return SQLITE_MISUSE_BKPT;
   101277   }
   101278   sqlite3_mutex_enter(db->mutex);
   101279   sqlite3BtreeEnterAll(db);
   101280   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   101281   if( rc==SQLITE_SCHEMA ){
   101282     sqlite3_finalize(*ppStmt);
   101283     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   101284   }
   101285   sqlite3BtreeLeaveAll(db);
   101286   sqlite3_mutex_leave(db->mutex);
   101287   assert( rc==SQLITE_OK || *ppStmt==0 );
   101288   return rc;
   101289 }
   101290 
   101291 /*
   101292 ** Rerun the compilation of a statement after a schema change.
   101293 **
   101294 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
   101295 ** if the statement cannot be recompiled because another connection has
   101296 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
   101297 ** occurs, return SQLITE_SCHEMA.
   101298 */
   101299 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
   101300   int rc;
   101301   sqlite3_stmt *pNew;
   101302   const char *zSql;
   101303   sqlite3 *db;
   101304 
   101305   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
   101306   zSql = sqlite3_sql((sqlite3_stmt *)p);
   101307   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
   101308   db = sqlite3VdbeDb(p);
   101309   assert( sqlite3_mutex_held(db->mutex) );
   101310   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
   101311   if( rc ){
   101312     if( rc==SQLITE_NOMEM ){
   101313       db->mallocFailed = 1;
   101314     }
   101315     assert( pNew==0 );
   101316     return rc;
   101317   }else{
   101318     assert( pNew!=0 );
   101319   }
   101320   sqlite3VdbeSwap((Vdbe*)pNew, p);
   101321   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
   101322   sqlite3VdbeResetStepResult((Vdbe*)pNew);
   101323   sqlite3VdbeFinalize((Vdbe*)pNew);
   101324   return SQLITE_OK;
   101325 }
   101326 
   101327 
   101328 /*
   101329 ** Two versions of the official API.  Legacy and new use.  In the legacy
   101330 ** version, the original SQL text is not saved in the prepared statement
   101331 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   101332 ** sqlite3_step().  In the new version, the original SQL text is retained
   101333 ** and the statement is automatically recompiled if an schema change
   101334 ** occurs.
   101335 */
   101336 SQLITE_API int sqlite3_prepare(
   101337   sqlite3 *db,              /* Database handle. */
   101338   const char *zSql,         /* UTF-8 encoded SQL statement. */
   101339   int nBytes,               /* Length of zSql in bytes. */
   101340   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101341   const char **pzTail       /* OUT: End of parsed string */
   101342 ){
   101343   int rc;
   101344   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
   101345   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   101346   return rc;
   101347 }
   101348 SQLITE_API int sqlite3_prepare_v2(
   101349   sqlite3 *db,              /* Database handle. */
   101350   const char *zSql,         /* UTF-8 encoded SQL statement. */
   101351   int nBytes,               /* Length of zSql in bytes. */
   101352   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101353   const char **pzTail       /* OUT: End of parsed string */
   101354 ){
   101355   int rc;
   101356   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
   101357   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   101358   return rc;
   101359 }
   101360 
   101361 
   101362 #ifndef SQLITE_OMIT_UTF16
   101363 /*
   101364 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   101365 */
   101366 static int sqlite3Prepare16(
   101367   sqlite3 *db,              /* Database handle. */
   101368   const void *zSql,         /* UTF-16 encoded SQL statement. */
   101369   int nBytes,               /* Length of zSql in bytes. */
   101370   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
   101371   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101372   const void **pzTail       /* OUT: End of parsed string */
   101373 ){
   101374   /* This function currently works by first transforming the UTF-16
   101375   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
   101376   ** tricky bit is figuring out the pointer to return in *pzTail.
   101377   */
   101378   char *zSql8;
   101379   const char *zTail8 = 0;
   101380   int rc = SQLITE_OK;
   101381 
   101382   assert( ppStmt );
   101383   *ppStmt = 0;
   101384   if( !sqlite3SafetyCheckOk(db) ){
   101385     return SQLITE_MISUSE_BKPT;
   101386   }
   101387   if( nBytes>=0 ){
   101388     int sz;
   101389     const char *z = (const char*)zSql;
   101390     for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
   101391     nBytes = sz;
   101392   }
   101393   sqlite3_mutex_enter(db->mutex);
   101394   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
   101395   if( zSql8 ){
   101396     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
   101397   }
   101398 
   101399   if( zTail8 && pzTail ){
   101400     /* If sqlite3_prepare returns a tail pointer, we calculate the
   101401     ** equivalent pointer into the UTF-16 string by counting the unicode
   101402     ** characters between zSql8 and zTail8, and then returning a pointer
   101403     ** the same number of characters into the UTF-16 string.
   101404     */
   101405     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
   101406     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
   101407   }
   101408   sqlite3DbFree(db, zSql8);
   101409   rc = sqlite3ApiExit(db, rc);
   101410   sqlite3_mutex_leave(db->mutex);
   101411   return rc;
   101412 }
   101413 
   101414 /*
   101415 ** Two versions of the official API.  Legacy and new use.  In the legacy
   101416 ** version, the original SQL text is not saved in the prepared statement
   101417 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   101418 ** sqlite3_step().  In the new version, the original SQL text is retained
   101419 ** and the statement is automatically recompiled if an schema change
   101420 ** occurs.
   101421 */
   101422 SQLITE_API int sqlite3_prepare16(
   101423   sqlite3 *db,              /* Database handle. */
   101424   const void *zSql,         /* UTF-16 encoded SQL statement. */
   101425   int nBytes,               /* Length of zSql in bytes. */
   101426   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101427   const void **pzTail       /* OUT: End of parsed string */
   101428 ){
   101429   int rc;
   101430   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
   101431   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   101432   return rc;
   101433 }
   101434 SQLITE_API int sqlite3_prepare16_v2(
   101435   sqlite3 *db,              /* Database handle. */
   101436   const void *zSql,         /* UTF-16 encoded SQL statement. */
   101437   int nBytes,               /* Length of zSql in bytes. */
   101438   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   101439   const void **pzTail       /* OUT: End of parsed string */
   101440 ){
   101441   int rc;
   101442   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
   101443   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   101444   return rc;
   101445 }
   101446 
   101447 #endif /* SQLITE_OMIT_UTF16 */
   101448 
   101449 /************** End of prepare.c *********************************************/
   101450 /************** Begin file select.c ******************************************/
   101451 /*
   101452 ** 2001 September 15
   101453 **
   101454 ** The author disclaims copyright to this source code.  In place of
   101455 ** a legal notice, here is a blessing:
   101456 **
   101457 **    May you do good and not evil.
   101458 **    May you find forgiveness for yourself and forgive others.
   101459 **    May you share freely, never taking more than you give.
   101460 **
   101461 *************************************************************************
   101462 ** This file contains C code routines that are called by the parser
   101463 ** to handle SELECT statements in SQLite.
   101464 */
   101465 
   101466 /*
   101467 ** An instance of the following object is used to record information about
   101468 ** how to process the DISTINCT keyword, to simplify passing that information
   101469 ** into the selectInnerLoop() routine.
   101470 */
   101471 typedef struct DistinctCtx DistinctCtx;
   101472 struct DistinctCtx {
   101473   u8 isTnct;      /* True if the DISTINCT keyword is present */
   101474   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
   101475   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
   101476   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
   101477 };
   101478 
   101479 /*
   101480 ** An instance of the following object is used to record information about
   101481 ** the ORDER BY (or GROUP BY) clause of query is being coded.
   101482 */
   101483 typedef struct SortCtx SortCtx;
   101484 struct SortCtx {
   101485   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
   101486   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
   101487   int iECursor;         /* Cursor number for the sorter */
   101488   int regReturn;        /* Register holding block-output return address */
   101489   int labelBkOut;       /* Start label for the block-output subroutine */
   101490   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
   101491   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
   101492 };
   101493 #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
   101494 
   101495 /*
   101496 ** Delete all the content of a Select structure but do not deallocate
   101497 ** the select structure itself.
   101498 */
   101499 static void clearSelect(sqlite3 *db, Select *p){
   101500   sqlite3ExprListDelete(db, p->pEList);
   101501   sqlite3SrcListDelete(db, p->pSrc);
   101502   sqlite3ExprDelete(db, p->pWhere);
   101503   sqlite3ExprListDelete(db, p->pGroupBy);
   101504   sqlite3ExprDelete(db, p->pHaving);
   101505   sqlite3ExprListDelete(db, p->pOrderBy);
   101506   sqlite3SelectDelete(db, p->pPrior);
   101507   sqlite3ExprDelete(db, p->pLimit);
   101508   sqlite3ExprDelete(db, p->pOffset);
   101509   sqlite3WithDelete(db, p->pWith);
   101510 }
   101511 
   101512 /*
   101513 ** Initialize a SelectDest structure.
   101514 */
   101515 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
   101516   pDest->eDest = (u8)eDest;
   101517   pDest->iSDParm = iParm;
   101518   pDest->affSdst = 0;
   101519   pDest->iSdst = 0;
   101520   pDest->nSdst = 0;
   101521 }
   101522 
   101523 
   101524 /*
   101525 ** Allocate a new Select structure and return a pointer to that
   101526 ** structure.
   101527 */
   101528 SQLITE_PRIVATE Select *sqlite3SelectNew(
   101529   Parse *pParse,        /* Parsing context */
   101530   ExprList *pEList,     /* which columns to include in the result */
   101531   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
   101532   Expr *pWhere,         /* the WHERE clause */
   101533   ExprList *pGroupBy,   /* the GROUP BY clause */
   101534   Expr *pHaving,        /* the HAVING clause */
   101535   ExprList *pOrderBy,   /* the ORDER BY clause */
   101536   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
   101537   Expr *pLimit,         /* LIMIT value.  NULL means not used */
   101538   Expr *pOffset         /* OFFSET value.  NULL means no offset */
   101539 ){
   101540   Select *pNew;
   101541   Select standin;
   101542   sqlite3 *db = pParse->db;
   101543   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   101544   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
   101545   if( pNew==0 ){
   101546     assert( db->mallocFailed );
   101547     pNew = &standin;
   101548     memset(pNew, 0, sizeof(*pNew));
   101549   }
   101550   if( pEList==0 ){
   101551     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
   101552   }
   101553   pNew->pEList = pEList;
   101554   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
   101555   pNew->pSrc = pSrc;
   101556   pNew->pWhere = pWhere;
   101557   pNew->pGroupBy = pGroupBy;
   101558   pNew->pHaving = pHaving;
   101559   pNew->pOrderBy = pOrderBy;
   101560   pNew->selFlags = selFlags;
   101561   pNew->op = TK_SELECT;
   101562   pNew->pLimit = pLimit;
   101563   pNew->pOffset = pOffset;
   101564   assert( pOffset==0 || pLimit!=0 );
   101565   pNew->addrOpenEphm[0] = -1;
   101566   pNew->addrOpenEphm[1] = -1;
   101567   if( db->mallocFailed ) {
   101568     clearSelect(db, pNew);
   101569     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
   101570     pNew = 0;
   101571   }else{
   101572     assert( pNew->pSrc!=0 || pParse->nErr>0 );
   101573   }
   101574   assert( pNew!=&standin );
   101575   return pNew;
   101576 }
   101577 
   101578 /*
   101579 ** Delete the given Select structure and all of its substructures.
   101580 */
   101581 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
   101582   if( p ){
   101583     clearSelect(db, p);
   101584     sqlite3DbFree(db, p);
   101585   }
   101586 }
   101587 
   101588 /*
   101589 ** Return a pointer to the right-most SELECT statement in a compound.
   101590 */
   101591 static Select *findRightmost(Select *p){
   101592   while( p->pNext ) p = p->pNext;
   101593   return p;
   101594 }
   101595 
   101596 /*
   101597 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
   101598 ** type of join.  Return an integer constant that expresses that type
   101599 ** in terms of the following bit values:
   101600 **
   101601 **     JT_INNER
   101602 **     JT_CROSS
   101603 **     JT_OUTER
   101604 **     JT_NATURAL
   101605 **     JT_LEFT
   101606 **     JT_RIGHT
   101607 **
   101608 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   101609 **
   101610 ** If an illegal or unsupported join type is seen, then still return
   101611 ** a join type, but put an error in the pParse structure.
   101612 */
   101613 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   101614   int jointype = 0;
   101615   Token *apAll[3];
   101616   Token *p;
   101617                              /*   0123456789 123456789 123456789 123 */
   101618   static const char zKeyText[] = "naturaleftouterightfullinnercross";
   101619   static const struct {
   101620     u8 i;        /* Beginning of keyword text in zKeyText[] */
   101621     u8 nChar;    /* Length of the keyword in characters */
   101622     u8 code;     /* Join type mask */
   101623   } aKeyword[] = {
   101624     /* natural */ { 0,  7, JT_NATURAL                },
   101625     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
   101626     /* outer   */ { 10, 5, JT_OUTER                  },
   101627     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
   101628     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
   101629     /* inner   */ { 23, 5, JT_INNER                  },
   101630     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
   101631   };
   101632   int i, j;
   101633   apAll[0] = pA;
   101634   apAll[1] = pB;
   101635   apAll[2] = pC;
   101636   for(i=0; i<3 && apAll[i]; i++){
   101637     p = apAll[i];
   101638     for(j=0; j<ArraySize(aKeyword); j++){
   101639       if( p->n==aKeyword[j].nChar
   101640           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
   101641         jointype |= aKeyword[j].code;
   101642         break;
   101643       }
   101644     }
   101645     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
   101646     if( j>=ArraySize(aKeyword) ){
   101647       jointype |= JT_ERROR;
   101648       break;
   101649     }
   101650   }
   101651   if(
   101652      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   101653      (jointype & JT_ERROR)!=0
   101654   ){
   101655     const char *zSp = " ";
   101656     assert( pB!=0 );
   101657     if( pC==0 ){ zSp++; }
   101658     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   101659        "%T %T%s%T", pA, pB, zSp, pC);
   101660     jointype = JT_INNER;
   101661   }else if( (jointype & JT_OUTER)!=0
   101662          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
   101663     sqlite3ErrorMsg(pParse,
   101664       "RIGHT and FULL OUTER JOINs are not currently supported");
   101665     jointype = JT_INNER;
   101666   }
   101667   return jointype;
   101668 }
   101669 
   101670 /*
   101671 ** Return the index of a column in a table.  Return -1 if the column
   101672 ** is not contained in the table.
   101673 */
   101674 static int columnIndex(Table *pTab, const char *zCol){
   101675   int i;
   101676   for(i=0; i<pTab->nCol; i++){
   101677     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   101678   }
   101679   return -1;
   101680 }
   101681 
   101682 /*
   101683 ** Search the first N tables in pSrc, from left to right, looking for a
   101684 ** table that has a column named zCol.
   101685 **
   101686 ** When found, set *piTab and *piCol to the table index and column index
   101687 ** of the matching column and return TRUE.
   101688 **
   101689 ** If not found, return FALSE.
   101690 */
   101691 static int tableAndColumnIndex(
   101692   SrcList *pSrc,       /* Array of tables to search */
   101693   int N,               /* Number of tables in pSrc->a[] to search */
   101694   const char *zCol,    /* Name of the column we are looking for */
   101695   int *piTab,          /* Write index of pSrc->a[] here */
   101696   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
   101697 ){
   101698   int i;               /* For looping over tables in pSrc */
   101699   int iCol;            /* Index of column matching zCol */
   101700 
   101701   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   101702   for(i=0; i<N; i++){
   101703     iCol = columnIndex(pSrc->a[i].pTab, zCol);
   101704     if( iCol>=0 ){
   101705       if( piTab ){
   101706         *piTab = i;
   101707         *piCol = iCol;
   101708       }
   101709       return 1;
   101710     }
   101711   }
   101712   return 0;
   101713 }
   101714 
   101715 /*
   101716 ** This function is used to add terms implied by JOIN syntax to the
   101717 ** WHERE clause expression of a SELECT statement. The new term, which
   101718 ** is ANDed with the existing WHERE clause, is of the form:
   101719 **
   101720 **    (tab1.col1 = tab2.col2)
   101721 **
   101722 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
   101723 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
   101724 ** column iColRight of tab2.
   101725 */
   101726 static void addWhereTerm(
   101727   Parse *pParse,                  /* Parsing context */
   101728   SrcList *pSrc,                  /* List of tables in FROM clause */
   101729   int iLeft,                      /* Index of first table to join in pSrc */
   101730   int iColLeft,                   /* Index of column in first table */
   101731   int iRight,                     /* Index of second table in pSrc */
   101732   int iColRight,                  /* Index of column in second table */
   101733   int isOuterJoin,                /* True if this is an OUTER join */
   101734   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
   101735 ){
   101736   sqlite3 *db = pParse->db;
   101737   Expr *pE1;
   101738   Expr *pE2;
   101739   Expr *pEq;
   101740 
   101741   assert( iLeft<iRight );
   101742   assert( pSrc->nSrc>iRight );
   101743   assert( pSrc->a[iLeft].pTab );
   101744   assert( pSrc->a[iRight].pTab );
   101745 
   101746   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
   101747   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
   101748 
   101749   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
   101750   if( pEq && isOuterJoin ){
   101751     ExprSetProperty(pEq, EP_FromJoin);
   101752     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
   101753     ExprSetVVAProperty(pEq, EP_NoReduce);
   101754     pEq->iRightJoinTable = (i16)pE2->iTable;
   101755   }
   101756   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
   101757 }
   101758 
   101759 /*
   101760 ** Set the EP_FromJoin property on all terms of the given expression.
   101761 ** And set the Expr.iRightJoinTable to iTable for every term in the
   101762 ** expression.
   101763 **
   101764 ** The EP_FromJoin property is used on terms of an expression to tell
   101765 ** the LEFT OUTER JOIN processing logic that this term is part of the
   101766 ** join restriction specified in the ON or USING clause and not a part
   101767 ** of the more general WHERE clause.  These terms are moved over to the
   101768 ** WHERE clause during join processing but we need to remember that they
   101769 ** originated in the ON or USING clause.
   101770 **
   101771 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
   101772 ** expression depends on table iRightJoinTable even if that table is not
   101773 ** explicitly mentioned in the expression.  That information is needed
   101774 ** for cases like this:
   101775 **
   101776 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   101777 **
   101778 ** The where clause needs to defer the handling of the t1.x=5
   101779 ** term until after the t2 loop of the join.  In that way, a
   101780 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   101781 ** defer the handling of t1.x=5, it will be processed immediately
   101782 ** after the t1 loop and rows with t1.x!=5 will never appear in
   101783 ** the output, which is incorrect.
   101784 */
   101785 static void setJoinExpr(Expr *p, int iTable){
   101786   while( p ){
   101787     ExprSetProperty(p, EP_FromJoin);
   101788     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
   101789     ExprSetVVAProperty(p, EP_NoReduce);
   101790     p->iRightJoinTable = (i16)iTable;
   101791     setJoinExpr(p->pLeft, iTable);
   101792     p = p->pRight;
   101793   }
   101794 }
   101795 
   101796 /*
   101797 ** This routine processes the join information for a SELECT statement.
   101798 ** ON and USING clauses are converted into extra terms of the WHERE clause.
   101799 ** NATURAL joins also create extra WHERE clause terms.
   101800 **
   101801 ** The terms of a FROM clause are contained in the Select.pSrc structure.
   101802 ** The left most table is the first entry in Select.pSrc.  The right-most
   101803 ** table is the last entry.  The join operator is held in the entry to
   101804 ** the left.  Thus entry 0 contains the join operator for the join between
   101805 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
   101806 ** also attached to the left entry.
   101807 **
   101808 ** This routine returns the number of errors encountered.
   101809 */
   101810 static int sqliteProcessJoin(Parse *pParse, Select *p){
   101811   SrcList *pSrc;                  /* All tables in the FROM clause */
   101812   int i, j;                       /* Loop counters */
   101813   struct SrcList_item *pLeft;     /* Left table being joined */
   101814   struct SrcList_item *pRight;    /* Right table being joined */
   101815 
   101816   pSrc = p->pSrc;
   101817   pLeft = &pSrc->a[0];
   101818   pRight = &pLeft[1];
   101819   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   101820     Table *pLeftTab = pLeft->pTab;
   101821     Table *pRightTab = pRight->pTab;
   101822     int isOuter;
   101823 
   101824     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
   101825     isOuter = (pRight->jointype & JT_OUTER)!=0;
   101826 
   101827     /* When the NATURAL keyword is present, add WHERE clause terms for
   101828     ** every column that the two tables have in common.
   101829     */
   101830     if( pRight->jointype & JT_NATURAL ){
   101831       if( pRight->pOn || pRight->pUsing ){
   101832         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   101833            "an ON or USING clause", 0);
   101834         return 1;
   101835       }
   101836       for(j=0; j<pRightTab->nCol; j++){
   101837         char *zName;   /* Name of column in the right table */
   101838         int iLeft;     /* Matching left table */
   101839         int iLeftCol;  /* Matching column in the left table */
   101840 
   101841         zName = pRightTab->aCol[j].zName;
   101842         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
   101843           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
   101844                        isOuter, &p->pWhere);
   101845         }
   101846       }
   101847     }
   101848 
   101849     /* Disallow both ON and USING clauses in the same join
   101850     */
   101851     if( pRight->pOn && pRight->pUsing ){
   101852       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   101853         "clauses in the same join");
   101854       return 1;
   101855     }
   101856 
   101857     /* Add the ON clause to the end of the WHERE clause, connected by
   101858     ** an AND operator.
   101859     */
   101860     if( pRight->pOn ){
   101861       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
   101862       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   101863       pRight->pOn = 0;
   101864     }
   101865 
   101866     /* Create extra terms on the WHERE clause for each column named
   101867     ** in the USING clause.  Example: If the two tables to be joined are
   101868     ** A and B and the USING clause names X, Y, and Z, then add this
   101869     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   101870     ** Report an error if any column mentioned in the USING clause is
   101871     ** not contained in both tables to be joined.
   101872     */
   101873     if( pRight->pUsing ){
   101874       IdList *pList = pRight->pUsing;
   101875       for(j=0; j<pList->nId; j++){
   101876         char *zName;     /* Name of the term in the USING clause */
   101877         int iLeft;       /* Table on the left with matching column name */
   101878         int iLeftCol;    /* Column number of matching column on the left */
   101879         int iRightCol;   /* Column number of matching column on the right */
   101880 
   101881         zName = pList->a[j].zName;
   101882         iRightCol = columnIndex(pRightTab, zName);
   101883         if( iRightCol<0
   101884          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
   101885         ){
   101886           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   101887             "not present in both tables", zName);
   101888           return 1;
   101889         }
   101890         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
   101891                      isOuter, &p->pWhere);
   101892       }
   101893     }
   101894   }
   101895   return 0;
   101896 }
   101897 
   101898 /* Forward reference */
   101899 static KeyInfo *keyInfoFromExprList(
   101900   Parse *pParse,       /* Parsing context */
   101901   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
   101902   int iStart,          /* Begin with this column of pList */
   101903   int nExtra           /* Add this many extra columns to the end */
   101904 );
   101905 
   101906 /*
   101907 ** Insert code into "v" that will push the record in register regData
   101908 ** into the sorter.
   101909 */
   101910 static void pushOntoSorter(
   101911   Parse *pParse,         /* Parser context */
   101912   SortCtx *pSort,        /* Information about the ORDER BY clause */
   101913   Select *pSelect,       /* The whole SELECT statement */
   101914   int regData            /* Register holding data to be sorted */
   101915 ){
   101916   Vdbe *v = pParse->pVdbe;
   101917   int nExpr = pSort->pOrderBy->nExpr;
   101918   int regRecord = ++pParse->nMem;
   101919   int regBase = pParse->nMem+1;
   101920   int nOBSat = pSort->nOBSat;
   101921   int op;
   101922 
   101923   pParse->nMem += nExpr+2;        /* nExpr+2 registers allocated at regBase */
   101924   sqlite3ExprCacheClear(pParse);
   101925   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, 0);
   101926   sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
   101927   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
   101928   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nExpr+2-nOBSat,regRecord);
   101929   if( nOBSat>0 ){
   101930     int regPrevKey;   /* The first nOBSat columns of the previous row */
   101931     int addrFirst;    /* Address of the OP_IfNot opcode */
   101932     int addrJmp;      /* Address of the OP_Jump opcode */
   101933     VdbeOp *pOp;      /* Opcode that opens the sorter */
   101934     int nKey;         /* Number of sorting key columns, including OP_Sequence */
   101935     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
   101936 
   101937     regPrevKey = pParse->nMem+1;
   101938     pParse->nMem += pSort->nOBSat;
   101939     nKey = nExpr - pSort->nOBSat + 1;
   101940     addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); VdbeCoverage(v);
   101941     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
   101942     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
   101943     if( pParse->db->mallocFailed ) return;
   101944     pOp->p2 = nKey + 1;
   101945     pKI = pOp->p4.pKeyInfo;
   101946     memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
   101947     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
   101948     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1);
   101949     addrJmp = sqlite3VdbeCurrentAddr(v);
   101950     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
   101951     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
   101952     pSort->regReturn = ++pParse->nMem;
   101953     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
   101954     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
   101955     sqlite3VdbeJumpHere(v, addrFirst);
   101956     sqlite3VdbeAddOp3(v, OP_Move, regBase, regPrevKey, pSort->nOBSat);
   101957     sqlite3VdbeJumpHere(v, addrJmp);
   101958   }
   101959   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   101960     op = OP_SorterInsert;
   101961   }else{
   101962     op = OP_IdxInsert;
   101963   }
   101964   sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
   101965   if( pSelect->iLimit ){
   101966     int addr1, addr2;
   101967     int iLimit;
   101968     if( pSelect->iOffset ){
   101969       iLimit = pSelect->iOffset+1;
   101970     }else{
   101971       iLimit = pSelect->iLimit;
   101972     }
   101973     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
   101974     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
   101975     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
   101976     sqlite3VdbeJumpHere(v, addr1);
   101977     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
   101978     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
   101979     sqlite3VdbeJumpHere(v, addr2);
   101980   }
   101981 }
   101982 
   101983 /*
   101984 ** Add code to implement the OFFSET
   101985 */
   101986 static void codeOffset(
   101987   Vdbe *v,          /* Generate code into this VM */
   101988   int iOffset,      /* Register holding the offset counter */
   101989   int iContinue     /* Jump here to skip the current record */
   101990 ){
   101991   if( iOffset>0 ){
   101992     int addr;
   101993     addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
   101994     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
   101995     VdbeComment((v, "skip OFFSET records"));
   101996     sqlite3VdbeJumpHere(v, addr);
   101997   }
   101998 }
   101999 
   102000 /*
   102001 ** Add code that will check to make sure the N registers starting at iMem
   102002 ** form a distinct entry.  iTab is a sorting index that holds previously
   102003 ** seen combinations of the N values.  A new entry is made in iTab
   102004 ** if the current N values are new.
   102005 **
   102006 ** A jump to addrRepeat is made and the N+1 values are popped from the
   102007 ** stack if the top N elements are not distinct.
   102008 */
   102009 static void codeDistinct(
   102010   Parse *pParse,     /* Parsing and code generating context */
   102011   int iTab,          /* A sorting index used to test for distinctness */
   102012   int addrRepeat,    /* Jump to here if not distinct */
   102013   int N,             /* Number of elements */
   102014   int iMem           /* First element */
   102015 ){
   102016   Vdbe *v;
   102017   int r1;
   102018 
   102019   v = pParse->pVdbe;
   102020   r1 = sqlite3GetTempReg(pParse);
   102021   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
   102022   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   102023   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
   102024   sqlite3ReleaseTempReg(pParse, r1);
   102025 }
   102026 
   102027 #ifndef SQLITE_OMIT_SUBQUERY
   102028 /*
   102029 ** Generate an error message when a SELECT is used within a subexpression
   102030 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
   102031 ** column.  We do this in a subroutine because the error used to occur
   102032 ** in multiple places.  (The error only occurs in one place now, but we
   102033 ** retain the subroutine to minimize code disruption.)
   102034 */
   102035 static int checkForMultiColumnSelectError(
   102036   Parse *pParse,       /* Parse context. */
   102037   SelectDest *pDest,   /* Destination of SELECT results */
   102038   int nExpr            /* Number of result columns returned by SELECT */
   102039 ){
   102040   int eDest = pDest->eDest;
   102041   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
   102042     sqlite3ErrorMsg(pParse, "only a single result allowed for "
   102043        "a SELECT that is part of an expression");
   102044     return 1;
   102045   }else{
   102046     return 0;
   102047   }
   102048 }
   102049 #endif
   102050 
   102051 /*
   102052 ** This routine generates the code for the inside of the inner loop
   102053 ** of a SELECT.
   102054 **
   102055 ** If srcTab is negative, then the pEList expressions
   102056 ** are evaluated in order to get the data for this row.  If srcTab is
   102057 ** zero or more, then data is pulled from srcTab and pEList is used only
   102058 ** to get number columns and the datatype for each column.
   102059 */
   102060 static void selectInnerLoop(
   102061   Parse *pParse,          /* The parser context */
   102062   Select *p,              /* The complete select statement being coded */
   102063   ExprList *pEList,       /* List of values being extracted */
   102064   int srcTab,             /* Pull data from this table */
   102065   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
   102066   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
   102067   SelectDest *pDest,      /* How to dispose of the results */
   102068   int iContinue,          /* Jump here to continue with next row */
   102069   int iBreak              /* Jump here to break out of the inner loop */
   102070 ){
   102071   Vdbe *v = pParse->pVdbe;
   102072   int i;
   102073   int hasDistinct;        /* True if the DISTINCT keyword is present */
   102074   int regResult;              /* Start of memory holding result set */
   102075   int eDest = pDest->eDest;   /* How to dispose of results */
   102076   int iParm = pDest->iSDParm; /* First argument to disposal method */
   102077   int nResultCol;             /* Number of result columns */
   102078 
   102079   assert( v );
   102080   assert( pEList!=0 );
   102081   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
   102082   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
   102083   if( pSort==0 && !hasDistinct ){
   102084     assert( iContinue!=0 );
   102085     codeOffset(v, p->iOffset, iContinue);
   102086   }
   102087 
   102088   /* Pull the requested columns.
   102089   */
   102090   nResultCol = pEList->nExpr;
   102091 
   102092   if( pDest->iSdst==0 ){
   102093     pDest->iSdst = pParse->nMem+1;
   102094     pParse->nMem += nResultCol;
   102095   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
   102096     /* This is an error condition that can result, for example, when a SELECT
   102097     ** on the right-hand side of an INSERT contains more result columns than
   102098     ** there are columns in the table on the left.  The error will be caught
   102099     ** and reported later.  But we need to make sure enough memory is allocated
   102100     ** to avoid other spurious errors in the meantime. */
   102101     pParse->nMem += nResultCol;
   102102   }
   102103   pDest->nSdst = nResultCol;
   102104   regResult = pDest->iSdst;
   102105   if( srcTab>=0 ){
   102106     for(i=0; i<nResultCol; i++){
   102107       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   102108       VdbeComment((v, "%s", pEList->a[i].zName));
   102109     }
   102110   }else if( eDest!=SRT_Exists ){
   102111     /* If the destination is an EXISTS(...) expression, the actual
   102112     ** values returned by the SELECT are not required.
   102113     */
   102114     sqlite3ExprCodeExprList(pParse, pEList, regResult,
   102115                   (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
   102116   }
   102117 
   102118   /* If the DISTINCT keyword was present on the SELECT statement
   102119   ** and this row has been seen before, then do not make this row
   102120   ** part of the result.
   102121   */
   102122   if( hasDistinct ){
   102123     switch( pDistinct->eTnctType ){
   102124       case WHERE_DISTINCT_ORDERED: {
   102125         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
   102126         int iJump;              /* Jump destination */
   102127         int regPrev;            /* Previous row content */
   102128 
   102129         /* Allocate space for the previous row */
   102130         regPrev = pParse->nMem+1;
   102131         pParse->nMem += nResultCol;
   102132 
   102133         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
   102134         ** sets the MEM_Cleared bit on the first register of the
   102135         ** previous value.  This will cause the OP_Ne below to always
   102136         ** fail on the first iteration of the loop even if the first
   102137         ** row is all NULLs.
   102138         */
   102139         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
   102140         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
   102141         pOp->opcode = OP_Null;
   102142         pOp->p1 = 1;
   102143         pOp->p2 = regPrev;
   102144 
   102145         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
   102146         for(i=0; i<nResultCol; i++){
   102147           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
   102148           if( i<nResultCol-1 ){
   102149             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
   102150             VdbeCoverage(v);
   102151           }else{
   102152             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
   102153             VdbeCoverage(v);
   102154            }
   102155           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
   102156           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   102157         }
   102158         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
   102159         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
   102160         break;
   102161       }
   102162 
   102163       case WHERE_DISTINCT_UNIQUE: {
   102164         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
   102165         break;
   102166       }
   102167 
   102168       default: {
   102169         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
   102170         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
   102171         break;
   102172       }
   102173     }
   102174     if( pSort==0 ){
   102175       codeOffset(v, p->iOffset, iContinue);
   102176     }
   102177   }
   102178 
   102179   switch( eDest ){
   102180     /* In this mode, write each query result to the key of the temporary
   102181     ** table iParm.
   102182     */
   102183 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   102184     case SRT_Union: {
   102185       int r1;
   102186       r1 = sqlite3GetTempReg(pParse);
   102187       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
   102188       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   102189       sqlite3ReleaseTempReg(pParse, r1);
   102190       break;
   102191     }
   102192 
   102193     /* Construct a record from the query result, but instead of
   102194     ** saving that record, use it as a key to delete elements from
   102195     ** the temporary table iParm.
   102196     */
   102197     case SRT_Except: {
   102198       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
   102199       break;
   102200     }
   102201 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   102202 
   102203     /* Store the result as data using a unique key.
   102204     */
   102205     case SRT_Fifo:
   102206     case SRT_DistFifo:
   102207     case SRT_Table:
   102208     case SRT_EphemTab: {
   102209       int r1 = sqlite3GetTempReg(pParse);
   102210       testcase( eDest==SRT_Table );
   102211       testcase( eDest==SRT_EphemTab );
   102212       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
   102213 #ifndef SQLITE_OMIT_CTE
   102214       if( eDest==SRT_DistFifo ){
   102215         /* If the destination is DistFifo, then cursor (iParm+1) is open
   102216         ** on an ephemeral index. If the current row is already present
   102217         ** in the index, do not write it to the output. If not, add the
   102218         ** current row to the index and proceed with writing it to the
   102219         ** output table as well.  */
   102220         int addr = sqlite3VdbeCurrentAddr(v) + 4;
   102221         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
   102222         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
   102223         assert( pSort==0 );
   102224       }
   102225 #endif
   102226       if( pSort ){
   102227         pushOntoSorter(pParse, pSort, p, r1);
   102228       }else{
   102229         int r2 = sqlite3GetTempReg(pParse);
   102230         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
   102231         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
   102232         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   102233         sqlite3ReleaseTempReg(pParse, r2);
   102234       }
   102235       sqlite3ReleaseTempReg(pParse, r1);
   102236       break;
   102237     }
   102238 
   102239 #ifndef SQLITE_OMIT_SUBQUERY
   102240     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   102241     ** then there should be a single item on the stack.  Write this
   102242     ** item into the set table with bogus data.
   102243     */
   102244     case SRT_Set: {
   102245       assert( nResultCol==1 );
   102246       pDest->affSdst =
   102247                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
   102248       if( pSort ){
   102249         /* At first glance you would think we could optimize out the
   102250         ** ORDER BY in this case since the order of entries in the set
   102251         ** does not matter.  But there might be a LIMIT clause, in which
   102252         ** case the order does matter */
   102253         pushOntoSorter(pParse, pSort, p, regResult);
   102254       }else{
   102255         int r1 = sqlite3GetTempReg(pParse);
   102256         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
   102257         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
   102258         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   102259         sqlite3ReleaseTempReg(pParse, r1);
   102260       }
   102261       break;
   102262     }
   102263 
   102264     /* If any row exist in the result set, record that fact and abort.
   102265     */
   102266     case SRT_Exists: {
   102267       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
   102268       /* The LIMIT clause will terminate the loop for us */
   102269       break;
   102270     }
   102271 
   102272     /* If this is a scalar select that is part of an expression, then
   102273     ** store the results in the appropriate memory cell and break out
   102274     ** of the scan loop.
   102275     */
   102276     case SRT_Mem: {
   102277       assert( nResultCol==1 );
   102278       if( pSort ){
   102279         pushOntoSorter(pParse, pSort, p, regResult);
   102280       }else{
   102281         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
   102282         /* The LIMIT clause will jump out of the loop for us */
   102283       }
   102284       break;
   102285     }
   102286 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   102287 
   102288     case SRT_Coroutine:       /* Send data to a co-routine */
   102289     case SRT_Output: {        /* Return the results */
   102290       testcase( eDest==SRT_Coroutine );
   102291       testcase( eDest==SRT_Output );
   102292       if( pSort ){
   102293         int r1 = sqlite3GetTempReg(pParse);
   102294         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
   102295         pushOntoSorter(pParse, pSort, p, r1);
   102296         sqlite3ReleaseTempReg(pParse, r1);
   102297       }else if( eDest==SRT_Coroutine ){
   102298         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   102299       }else{
   102300         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
   102301         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
   102302       }
   102303       break;
   102304     }
   102305 
   102306 #ifndef SQLITE_OMIT_CTE
   102307     /* Write the results into a priority queue that is order according to
   102308     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
   102309     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
   102310     ** pSO->nExpr columns, then make sure all keys are unique by adding a
   102311     ** final OP_Sequence column.  The last column is the record as a blob.
   102312     */
   102313     case SRT_DistQueue:
   102314     case SRT_Queue: {
   102315       int nKey;
   102316       int r1, r2, r3;
   102317       int addrTest = 0;
   102318       ExprList *pSO;
   102319       pSO = pDest->pOrderBy;
   102320       assert( pSO );
   102321       nKey = pSO->nExpr;
   102322       r1 = sqlite3GetTempReg(pParse);
   102323       r2 = sqlite3GetTempRange(pParse, nKey+2);
   102324       r3 = r2+nKey+1;
   102325       if( eDest==SRT_DistQueue ){
   102326         /* If the destination is DistQueue, then cursor (iParm+1) is open
   102327         ** on a second ephemeral index that holds all values every previously
   102328         ** added to the queue. */
   102329         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
   102330                                         regResult, nResultCol);
   102331         VdbeCoverage(v);
   102332       }
   102333       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
   102334       if( eDest==SRT_DistQueue ){
   102335         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
   102336         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   102337       }
   102338       for(i=0; i<nKey; i++){
   102339         sqlite3VdbeAddOp2(v, OP_SCopy,
   102340                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
   102341                           r2+i);
   102342       }
   102343       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
   102344       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
   102345       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   102346       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
   102347       sqlite3ReleaseTempReg(pParse, r1);
   102348       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
   102349       break;
   102350     }
   102351 #endif /* SQLITE_OMIT_CTE */
   102352 
   102353 
   102354 
   102355 #if !defined(SQLITE_OMIT_TRIGGER)
   102356     /* Discard the results.  This is used for SELECT statements inside
   102357     ** the body of a TRIGGER.  The purpose of such selects is to call
   102358     ** user-defined functions that have side effects.  We do not care
   102359     ** about the actual results of the select.
   102360     */
   102361     default: {
   102362       assert( eDest==SRT_Discard );
   102363       break;
   102364     }
   102365 #endif
   102366   }
   102367 
   102368   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
   102369   ** there is a sorter, in which case the sorter has already limited
   102370   ** the output for us.
   102371   */
   102372   if( pSort==0 && p->iLimit ){
   102373     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
   102374   }
   102375 }
   102376 
   102377 /*
   102378 ** Allocate a KeyInfo object sufficient for an index of N key columns and
   102379 ** X extra columns.
   102380 */
   102381 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
   102382   KeyInfo *p = sqlite3DbMallocZero(0,
   102383                    sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
   102384   if( p ){
   102385     p->aSortOrder = (u8*)&p->aColl[N+X];
   102386     p->nField = (u16)N;
   102387     p->nXField = (u16)X;
   102388     p->enc = ENC(db);
   102389     p->db = db;
   102390     p->nRef = 1;
   102391   }else{
   102392     db->mallocFailed = 1;
   102393   }
   102394   return p;
   102395 }
   102396 
   102397 /*
   102398 ** Deallocate a KeyInfo object
   102399 */
   102400 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
   102401   if( p ){
   102402     assert( p->nRef>0 );
   102403     p->nRef--;
   102404     if( p->nRef==0 ) sqlite3DbFree(0, p);
   102405   }
   102406 }
   102407 
   102408 /*
   102409 ** Make a new pointer to a KeyInfo object
   102410 */
   102411 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
   102412   if( p ){
   102413     assert( p->nRef>0 );
   102414     p->nRef++;
   102415   }
   102416   return p;
   102417 }
   102418 
   102419 #ifdef SQLITE_DEBUG
   102420 /*
   102421 ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
   102422 ** can only be changed if this is just a single reference to the object.
   102423 **
   102424 ** This routine is used only inside of assert() statements.
   102425 */
   102426 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
   102427 #endif /* SQLITE_DEBUG */
   102428 
   102429 /*
   102430 ** Given an expression list, generate a KeyInfo structure that records
   102431 ** the collating sequence for each expression in that expression list.
   102432 **
   102433 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   102434 ** KeyInfo structure is appropriate for initializing a virtual index to
   102435 ** implement that clause.  If the ExprList is the result set of a SELECT
   102436 ** then the KeyInfo structure is appropriate for initializing a virtual
   102437 ** index to implement a DISTINCT test.
   102438 **
   102439 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   102440 ** function is responsible for seeing that this structure is eventually
   102441 ** freed.
   102442 */
   102443 static KeyInfo *keyInfoFromExprList(
   102444   Parse *pParse,       /* Parsing context */
   102445   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
   102446   int iStart,          /* Begin with this column of pList */
   102447   int nExtra           /* Add this many extra columns to the end */
   102448 ){
   102449   int nExpr;
   102450   KeyInfo *pInfo;
   102451   struct ExprList_item *pItem;
   102452   sqlite3 *db = pParse->db;
   102453   int i;
   102454 
   102455   nExpr = pList->nExpr;
   102456   pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1);
   102457   if( pInfo ){
   102458     assert( sqlite3KeyInfoIsWriteable(pInfo) );
   102459     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
   102460       CollSeq *pColl;
   102461       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   102462       if( !pColl ) pColl = db->pDfltColl;
   102463       pInfo->aColl[i-iStart] = pColl;
   102464       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
   102465     }
   102466   }
   102467   return pInfo;
   102468 }
   102469 
   102470 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   102471 /*
   102472 ** Name of the connection operator, used for error messages.
   102473 */
   102474 static const char *selectOpName(int id){
   102475   char *z;
   102476   switch( id ){
   102477     case TK_ALL:       z = "UNION ALL";   break;
   102478     case TK_INTERSECT: z = "INTERSECT";   break;
   102479     case TK_EXCEPT:    z = "EXCEPT";      break;
   102480     default:           z = "UNION";       break;
   102481   }
   102482   return z;
   102483 }
   102484 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   102485 
   102486 #ifndef SQLITE_OMIT_EXPLAIN
   102487 /*
   102488 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   102489 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   102490 ** where the caption is of the form:
   102491 **
   102492 **   "USE TEMP B-TREE FOR xxx"
   102493 **
   102494 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
   102495 ** is determined by the zUsage argument.
   102496 */
   102497 static void explainTempTable(Parse *pParse, const char *zUsage){
   102498   if( pParse->explain==2 ){
   102499     Vdbe *v = pParse->pVdbe;
   102500     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
   102501     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   102502   }
   102503 }
   102504 
   102505 /*
   102506 ** Assign expression b to lvalue a. A second, no-op, version of this macro
   102507 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
   102508 ** in sqlite3Select() to assign values to structure member variables that
   102509 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
   102510 ** code with #ifndef directives.
   102511 */
   102512 # define explainSetInteger(a, b) a = b
   102513 
   102514 #else
   102515 /* No-op versions of the explainXXX() functions and macros. */
   102516 # define explainTempTable(y,z)
   102517 # define explainSetInteger(y,z)
   102518 #endif
   102519 
   102520 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
   102521 /*
   102522 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   102523 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   102524 ** where the caption is of one of the two forms:
   102525 **
   102526 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
   102527 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
   102528 **
   102529 ** where iSub1 and iSub2 are the integers passed as the corresponding
   102530 ** function parameters, and op is the text representation of the parameter
   102531 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
   102532 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
   102533 ** false, or the second form if it is true.
   102534 */
   102535 static void explainComposite(
   102536   Parse *pParse,                  /* Parse context */
   102537   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
   102538   int iSub1,                      /* Subquery id 1 */
   102539   int iSub2,                      /* Subquery id 2 */
   102540   int bUseTmp                     /* True if a temp table was used */
   102541 ){
   102542   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
   102543   if( pParse->explain==2 ){
   102544     Vdbe *v = pParse->pVdbe;
   102545     char *zMsg = sqlite3MPrintf(
   102546         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
   102547         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
   102548     );
   102549     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   102550   }
   102551 }
   102552 #else
   102553 /* No-op versions of the explainXXX() functions and macros. */
   102554 # define explainComposite(v,w,x,y,z)
   102555 #endif
   102556 
   102557 /*
   102558 ** If the inner loop was generated using a non-null pOrderBy argument,
   102559 ** then the results were placed in a sorter.  After the loop is terminated
   102560 ** we need to run the sorter and output the results.  The following
   102561 ** routine generates the code needed to do that.
   102562 */
   102563 static void generateSortTail(
   102564   Parse *pParse,    /* Parsing context */
   102565   Select *p,        /* The SELECT statement */
   102566   SortCtx *pSort,   /* Information on the ORDER BY clause */
   102567   int nColumn,      /* Number of columns of data */
   102568   SelectDest *pDest /* Write the sorted results here */
   102569 ){
   102570   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
   102571   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
   102572   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
   102573   int addr;
   102574   int addrOnce = 0;
   102575   int iTab;
   102576   int pseudoTab = 0;
   102577   ExprList *pOrderBy = pSort->pOrderBy;
   102578   int eDest = pDest->eDest;
   102579   int iParm = pDest->iSDParm;
   102580   int regRow;
   102581   int regRowid;
   102582   int nKey;
   102583 
   102584   if( pSort->labelBkOut ){
   102585     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
   102586     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
   102587     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
   102588     addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   102589   }
   102590   iTab = pSort->iECursor;
   102591   regRow = sqlite3GetTempReg(pParse);
   102592   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   102593     pseudoTab = pParse->nTab++;
   102594     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
   102595     regRowid = 0;
   102596   }else{
   102597     regRowid = sqlite3GetTempReg(pParse);
   102598   }
   102599   nKey = pOrderBy->nExpr - pSort->nOBSat;
   102600   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   102601     int regSortOut = ++pParse->nMem;
   102602     int ptab2 = pParse->nTab++;
   102603     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, nKey+2);
   102604     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
   102605     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
   102606     VdbeCoverage(v);
   102607     codeOffset(v, p->iOffset, addrContinue);
   102608     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
   102609     sqlite3VdbeAddOp3(v, OP_Column, ptab2, nKey+1, regRow);
   102610     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   102611   }else{
   102612     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
   102613     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
   102614     codeOffset(v, p->iOffset, addrContinue);
   102615     sqlite3VdbeAddOp3(v, OP_Column, iTab, nKey+1, regRow);
   102616   }
   102617   switch( eDest ){
   102618     case SRT_Table:
   102619     case SRT_EphemTab: {
   102620       testcase( eDest==SRT_Table );
   102621       testcase( eDest==SRT_EphemTab );
   102622       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
   102623       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
   102624       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   102625       break;
   102626     }
   102627 #ifndef SQLITE_OMIT_SUBQUERY
   102628     case SRT_Set: {
   102629       assert( nColumn==1 );
   102630       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
   102631                         &pDest->affSdst, 1);
   102632       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
   102633       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
   102634       break;
   102635     }
   102636     case SRT_Mem: {
   102637       assert( nColumn==1 );
   102638       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
   102639       /* The LIMIT clause will terminate the loop for us */
   102640       break;
   102641     }
   102642 #endif
   102643     default: {
   102644       int i;
   102645       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
   102646       testcase( eDest==SRT_Output );
   102647       testcase( eDest==SRT_Coroutine );
   102648       for(i=0; i<nColumn; i++){
   102649         assert( regRow!=pDest->iSdst+i );
   102650         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
   102651         if( i==0 ){
   102652           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   102653         }
   102654       }
   102655       if( eDest==SRT_Output ){
   102656         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
   102657         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
   102658       }else{
   102659         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   102660       }
   102661       break;
   102662     }
   102663   }
   102664   sqlite3ReleaseTempReg(pParse, regRow);
   102665   sqlite3ReleaseTempReg(pParse, regRowid);
   102666 
   102667   /* The bottom of the loop
   102668   */
   102669   sqlite3VdbeResolveLabel(v, addrContinue);
   102670   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   102671     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
   102672   }else{
   102673     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
   102674   }
   102675   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
   102676   sqlite3VdbeResolveLabel(v, addrBreak);
   102677 }
   102678 
   102679 /*
   102680 ** Return a pointer to a string containing the 'declaration type' of the
   102681 ** expression pExpr. The string may be treated as static by the caller.
   102682 **
   102683 ** Also try to estimate the size of the returned value and return that
   102684 ** result in *pEstWidth.
   102685 **
   102686 ** The declaration type is the exact datatype definition extracted from the
   102687 ** original CREATE TABLE statement if the expression is a column. The
   102688 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
   102689 ** is considered a column can be complex in the presence of subqueries. The
   102690 ** result-set expression in all of the following SELECT statements is
   102691 ** considered a column by this function.
   102692 **
   102693 **   SELECT col FROM tbl;
   102694 **   SELECT (SELECT col FROM tbl;
   102695 **   SELECT (SELECT col FROM tbl);
   102696 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
   102697 **
   102698 ** The declaration type for any expression other than a column is NULL.
   102699 **
   102700 ** This routine has either 3 or 6 parameters depending on whether or not
   102701 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
   102702 */
   102703 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   102704 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
   102705 static const char *columnTypeImpl(
   102706   NameContext *pNC,
   102707   Expr *pExpr,
   102708   const char **pzOrigDb,
   102709   const char **pzOrigTab,
   102710   const char **pzOrigCol,
   102711   u8 *pEstWidth
   102712 ){
   102713   char const *zOrigDb = 0;
   102714   char const *zOrigTab = 0;
   102715   char const *zOrigCol = 0;
   102716 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
   102717 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
   102718 static const char *columnTypeImpl(
   102719   NameContext *pNC,
   102720   Expr *pExpr,
   102721   u8 *pEstWidth
   102722 ){
   102723 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
   102724   char const *zType = 0;
   102725   int j;
   102726   u8 estWidth = 1;
   102727 
   102728   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
   102729   switch( pExpr->op ){
   102730     case TK_AGG_COLUMN:
   102731     case TK_COLUMN: {
   102732       /* The expression is a column. Locate the table the column is being
   102733       ** extracted from in NameContext.pSrcList. This table may be real
   102734       ** database table or a subquery.
   102735       */
   102736       Table *pTab = 0;            /* Table structure column is extracted from */
   102737       Select *pS = 0;             /* Select the column is extracted from */
   102738       int iCol = pExpr->iColumn;  /* Index of column in pTab */
   102739       testcase( pExpr->op==TK_AGG_COLUMN );
   102740       testcase( pExpr->op==TK_COLUMN );
   102741       while( pNC && !pTab ){
   102742         SrcList *pTabList = pNC->pSrcList;
   102743         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   102744         if( j<pTabList->nSrc ){
   102745           pTab = pTabList->a[j].pTab;
   102746           pS = pTabList->a[j].pSelect;
   102747         }else{
   102748           pNC = pNC->pNext;
   102749         }
   102750       }
   102751 
   102752       if( pTab==0 ){
   102753         /* At one time, code such as "SELECT new.x" within a trigger would
   102754         ** cause this condition to run.  Since then, we have restructured how
   102755         ** trigger code is generated and so this condition is no longer
   102756         ** possible. However, it can still be true for statements like
   102757         ** the following:
   102758         **
   102759         **   CREATE TABLE t1(col INTEGER);
   102760         **   SELECT (SELECT t1.col) FROM FROM t1;
   102761         **
   102762         ** when columnType() is called on the expression "t1.col" in the
   102763         ** sub-select. In this case, set the column type to NULL, even
   102764         ** though it should really be "INTEGER".
   102765         **
   102766         ** This is not a problem, as the column type of "t1.col" is never
   102767         ** used. When columnType() is called on the expression
   102768         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
   102769         ** branch below.  */
   102770         break;
   102771       }
   102772 
   102773       assert( pTab && pExpr->pTab==pTab );
   102774       if( pS ){
   102775         /* The "table" is actually a sub-select or a view in the FROM clause
   102776         ** of the SELECT statement. Return the declaration type and origin
   102777         ** data for the result-set column of the sub-select.
   102778         */
   102779         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
   102780           /* If iCol is less than zero, then the expression requests the
   102781           ** rowid of the sub-select or view. This expression is legal (see
   102782           ** test case misc2.2.2) - it always evaluates to NULL.
   102783           */
   102784           NameContext sNC;
   102785           Expr *p = pS->pEList->a[iCol].pExpr;
   102786           sNC.pSrcList = pS->pSrc;
   102787           sNC.pNext = pNC;
   102788           sNC.pParse = pNC->pParse;
   102789           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
   102790         }
   102791       }else if( pTab->pSchema ){
   102792         /* A real table */
   102793         assert( !pS );
   102794         if( iCol<0 ) iCol = pTab->iPKey;
   102795         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   102796 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   102797         if( iCol<0 ){
   102798           zType = "INTEGER";
   102799           zOrigCol = "rowid";
   102800         }else{
   102801           zType = pTab->aCol[iCol].zType;
   102802           zOrigCol = pTab->aCol[iCol].zName;
   102803           estWidth = pTab->aCol[iCol].szEst;
   102804         }
   102805         zOrigTab = pTab->zName;
   102806         if( pNC->pParse ){
   102807           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   102808           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
   102809         }
   102810 #else
   102811         if( iCol<0 ){
   102812           zType = "INTEGER";
   102813         }else{
   102814           zType = pTab->aCol[iCol].zType;
   102815           estWidth = pTab->aCol[iCol].szEst;
   102816         }
   102817 #endif
   102818       }
   102819       break;
   102820     }
   102821 #ifndef SQLITE_OMIT_SUBQUERY
   102822     case TK_SELECT: {
   102823       /* The expression is a sub-select. Return the declaration type and
   102824       ** origin info for the single column in the result set of the SELECT
   102825       ** statement.
   102826       */
   102827       NameContext sNC;
   102828       Select *pS = pExpr->x.pSelect;
   102829       Expr *p = pS->pEList->a[0].pExpr;
   102830       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   102831       sNC.pSrcList = pS->pSrc;
   102832       sNC.pNext = pNC;
   102833       sNC.pParse = pNC->pParse;
   102834       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
   102835       break;
   102836     }
   102837 #endif
   102838   }
   102839 
   102840 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   102841   if( pzOrigDb ){
   102842     assert( pzOrigTab && pzOrigCol );
   102843     *pzOrigDb = zOrigDb;
   102844     *pzOrigTab = zOrigTab;
   102845     *pzOrigCol = zOrigCol;
   102846   }
   102847 #endif
   102848   if( pEstWidth ) *pEstWidth = estWidth;
   102849   return zType;
   102850 }
   102851 
   102852 /*
   102853 ** Generate code that will tell the VDBE the declaration types of columns
   102854 ** in the result set.
   102855 */
   102856 static void generateColumnTypes(
   102857   Parse *pParse,      /* Parser context */
   102858   SrcList *pTabList,  /* List of tables */
   102859   ExprList *pEList    /* Expressions defining the result set */
   102860 ){
   102861 #ifndef SQLITE_OMIT_DECLTYPE
   102862   Vdbe *v = pParse->pVdbe;
   102863   int i;
   102864   NameContext sNC;
   102865   sNC.pSrcList = pTabList;
   102866   sNC.pParse = pParse;
   102867   for(i=0; i<pEList->nExpr; i++){
   102868     Expr *p = pEList->a[i].pExpr;
   102869     const char *zType;
   102870 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   102871     const char *zOrigDb = 0;
   102872     const char *zOrigTab = 0;
   102873     const char *zOrigCol = 0;
   102874     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
   102875 
   102876     /* The vdbe must make its own copy of the column-type and other
   102877     ** column specific strings, in case the schema is reset before this
   102878     ** virtual machine is deleted.
   102879     */
   102880     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
   102881     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
   102882     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
   102883 #else
   102884     zType = columnType(&sNC, p, 0, 0, 0, 0);
   102885 #endif
   102886     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
   102887   }
   102888 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
   102889 }
   102890 
   102891 /*
   102892 ** Generate code that will tell the VDBE the names of columns
   102893 ** in the result set.  This information is used to provide the
   102894 ** azCol[] values in the callback.
   102895 */
   102896 static void generateColumnNames(
   102897   Parse *pParse,      /* Parser context */
   102898   SrcList *pTabList,  /* List of tables */
   102899   ExprList *pEList    /* Expressions defining the result set */
   102900 ){
   102901   Vdbe *v = pParse->pVdbe;
   102902   int i, j;
   102903   sqlite3 *db = pParse->db;
   102904   int fullNames, shortNames;
   102905 
   102906 #ifndef SQLITE_OMIT_EXPLAIN
   102907   /* If this is an EXPLAIN, skip this step */
   102908   if( pParse->explain ){
   102909     return;
   102910   }
   102911 #endif
   102912 
   102913   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
   102914   pParse->colNamesSet = 1;
   102915   fullNames = (db->flags & SQLITE_FullColNames)!=0;
   102916   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
   102917   sqlite3VdbeSetNumCols(v, pEList->nExpr);
   102918   for(i=0; i<pEList->nExpr; i++){
   102919     Expr *p;
   102920     p = pEList->a[i].pExpr;
   102921     if( NEVER(p==0) ) continue;
   102922     if( pEList->a[i].zName ){
   102923       char *zName = pEList->a[i].zName;
   102924       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
   102925     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
   102926       Table *pTab;
   102927       char *zCol;
   102928       int iCol = p->iColumn;
   102929       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
   102930         if( pTabList->a[j].iCursor==p->iTable ) break;
   102931       }
   102932       assert( j<pTabList->nSrc );
   102933       pTab = pTabList->a[j].pTab;
   102934       if( iCol<0 ) iCol = pTab->iPKey;
   102935       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   102936       if( iCol<0 ){
   102937         zCol = "rowid";
   102938       }else{
   102939         zCol = pTab->aCol[iCol].zName;
   102940       }
   102941       if( !shortNames && !fullNames ){
   102942         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   102943             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   102944       }else if( fullNames ){
   102945         char *zName = 0;
   102946         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
   102947         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
   102948       }else{
   102949         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
   102950       }
   102951     }else{
   102952       const char *z = pEList->a[i].zSpan;
   102953       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
   102954       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
   102955     }
   102956   }
   102957   generateColumnTypes(pParse, pTabList, pEList);
   102958 }
   102959 
   102960 /*
   102961 ** Given a an expression list (which is really the list of expressions
   102962 ** that form the result set of a SELECT statement) compute appropriate
   102963 ** column names for a table that would hold the expression list.
   102964 **
   102965 ** All column names will be unique.
   102966 **
   102967 ** Only the column names are computed.  Column.zType, Column.zColl,
   102968 ** and other fields of Column are zeroed.
   102969 **
   102970 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
   102971 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
   102972 */
   102973 static int selectColumnsFromExprList(
   102974   Parse *pParse,          /* Parsing context */
   102975   ExprList *pEList,       /* Expr list from which to derive column names */
   102976   i16 *pnCol,             /* Write the number of columns here */
   102977   Column **paCol          /* Write the new column list here */
   102978 ){
   102979   sqlite3 *db = pParse->db;   /* Database connection */
   102980   int i, j;                   /* Loop counters */
   102981   int cnt;                    /* Index added to make the name unique */
   102982   Column *aCol, *pCol;        /* For looping over result columns */
   102983   int nCol;                   /* Number of columns in the result set */
   102984   Expr *p;                    /* Expression for a single result column */
   102985   char *zName;                /* Column name */
   102986   int nName;                  /* Size of name in zName[] */
   102987 
   102988   if( pEList ){
   102989     nCol = pEList->nExpr;
   102990     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
   102991     testcase( aCol==0 );
   102992   }else{
   102993     nCol = 0;
   102994     aCol = 0;
   102995   }
   102996   *pnCol = nCol;
   102997   *paCol = aCol;
   102998 
   102999   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   103000     /* Get an appropriate name for the column
   103001     */
   103002     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
   103003     if( (zName = pEList->a[i].zName)!=0 ){
   103004       /* If the column contains an "AS <name>" phrase, use <name> as the name */
   103005       zName = sqlite3DbStrDup(db, zName);
   103006     }else{
   103007       Expr *pColExpr = p;  /* The expression that is the result column name */
   103008       Table *pTab;         /* Table associated with this expression */
   103009       while( pColExpr->op==TK_DOT ){
   103010         pColExpr = pColExpr->pRight;
   103011         assert( pColExpr!=0 );
   103012       }
   103013       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
   103014         /* For columns use the column name name */
   103015         int iCol = pColExpr->iColumn;
   103016         pTab = pColExpr->pTab;
   103017         if( iCol<0 ) iCol = pTab->iPKey;
   103018         zName = sqlite3MPrintf(db, "%s",
   103019                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
   103020       }else if( pColExpr->op==TK_ID ){
   103021         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
   103022         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
   103023       }else{
   103024         /* Use the original text of the column expression as its name */
   103025         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
   103026       }
   103027     }
   103028     if( db->mallocFailed ){
   103029       sqlite3DbFree(db, zName);
   103030       break;
   103031     }
   103032 
   103033     /* Make sure the column name is unique.  If the name is not unique,
   103034     ** append a integer to the name so that it becomes unique.
   103035     */
   103036     nName = sqlite3Strlen30(zName);
   103037     for(j=cnt=0; j<i; j++){
   103038       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
   103039         char *zNewName;
   103040         int k;
   103041         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
   103042         if( k>=0 && zName[k]==':' ) nName = k;
   103043         zName[nName] = 0;
   103044         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
   103045         sqlite3DbFree(db, zName);
   103046         zName = zNewName;
   103047         j = -1;
   103048         if( zName==0 ) break;
   103049       }
   103050     }
   103051     pCol->zName = zName;
   103052   }
   103053   if( db->mallocFailed ){
   103054     for(j=0; j<i; j++){
   103055       sqlite3DbFree(db, aCol[j].zName);
   103056     }
   103057     sqlite3DbFree(db, aCol);
   103058     *paCol = 0;
   103059     *pnCol = 0;
   103060     return SQLITE_NOMEM;
   103061   }
   103062   return SQLITE_OK;
   103063 }
   103064 
   103065 /*
   103066 ** Add type and collation information to a column list based on
   103067 ** a SELECT statement.
   103068 **
   103069 ** The column list presumably came from selectColumnNamesFromExprList().
   103070 ** The column list has only names, not types or collations.  This
   103071 ** routine goes through and adds the types and collations.
   103072 **
   103073 ** This routine requires that all identifiers in the SELECT
   103074 ** statement be resolved.
   103075 */
   103076 static void selectAddColumnTypeAndCollation(
   103077   Parse *pParse,        /* Parsing contexts */
   103078   Table *pTab,          /* Add column type information to this table */
   103079   Select *pSelect       /* SELECT used to determine types and collations */
   103080 ){
   103081   sqlite3 *db = pParse->db;
   103082   NameContext sNC;
   103083   Column *pCol;
   103084   CollSeq *pColl;
   103085   int i;
   103086   Expr *p;
   103087   struct ExprList_item *a;
   103088   u64 szAll = 0;
   103089 
   103090   assert( pSelect!=0 );
   103091   assert( (pSelect->selFlags & SF_Resolved)!=0 );
   103092   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
   103093   if( db->mallocFailed ) return;
   103094   memset(&sNC, 0, sizeof(sNC));
   103095   sNC.pSrcList = pSelect->pSrc;
   103096   a = pSelect->pEList->a;
   103097   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   103098     p = a[i].pExpr;
   103099     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
   103100     szAll += pCol->szEst;
   103101     pCol->affinity = sqlite3ExprAffinity(p);
   103102     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
   103103     pColl = sqlite3ExprCollSeq(pParse, p);
   103104     if( pColl ){
   103105       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
   103106     }
   103107   }
   103108   pTab->szTabRow = sqlite3LogEst(szAll*4);
   103109 }
   103110 
   103111 /*
   103112 ** Given a SELECT statement, generate a Table structure that describes
   103113 ** the result set of that SELECT.
   103114 */
   103115 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
   103116   Table *pTab;
   103117   sqlite3 *db = pParse->db;
   103118   int savedFlags;
   103119 
   103120   savedFlags = db->flags;
   103121   db->flags &= ~SQLITE_FullColNames;
   103122   db->flags |= SQLITE_ShortColNames;
   103123   sqlite3SelectPrep(pParse, pSelect, 0);
   103124   if( pParse->nErr ) return 0;
   103125   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
   103126   db->flags = savedFlags;
   103127   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
   103128   if( pTab==0 ){
   103129     return 0;
   103130   }
   103131   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
   103132   ** is disabled */
   103133   assert( db->lookaside.bEnabled==0 );
   103134   pTab->nRef = 1;
   103135   pTab->zName = 0;
   103136   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   103137   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
   103138   selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
   103139   pTab->iPKey = -1;
   103140   if( db->mallocFailed ){
   103141     sqlite3DeleteTable(db, pTab);
   103142     return 0;
   103143   }
   103144   return pTab;
   103145 }
   103146 
   103147 /*
   103148 ** Get a VDBE for the given parser context.  Create a new one if necessary.
   103149 ** If an error occurs, return NULL and leave a message in pParse.
   103150 */
   103151 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
   103152   Vdbe *v = pParse->pVdbe;
   103153   if( v==0 ){
   103154     v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
   103155     if( v ) sqlite3VdbeAddOp0(v, OP_Init);
   103156     if( pParse->pToplevel==0
   103157      && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
   103158     ){
   103159       pParse->okConstFactor = 1;
   103160     }
   103161 
   103162   }
   103163   return v;
   103164 }
   103165 
   103166 
   103167 /*
   103168 ** Compute the iLimit and iOffset fields of the SELECT based on the
   103169 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
   103170 ** that appear in the original SQL statement after the LIMIT and OFFSET
   103171 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
   103172 ** are the integer memory register numbers for counters used to compute
   103173 ** the limit and offset.  If there is no limit and/or offset, then
   103174 ** iLimit and iOffset are negative.
   103175 **
   103176 ** This routine changes the values of iLimit and iOffset only if
   103177 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
   103178 ** iOffset should have been preset to appropriate default values (zero)
   103179 ** prior to calling this routine.
   103180 **
   103181 ** The iOffset register (if it exists) is initialized to the value
   103182 ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
   103183 ** iOffset+1 is initialized to LIMIT+OFFSET.
   103184 **
   103185 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
   103186 ** redefined.  The UNION ALL operator uses this property to force
   103187 ** the reuse of the same limit and offset registers across multiple
   103188 ** SELECT statements.
   103189 */
   103190 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
   103191   Vdbe *v = 0;
   103192   int iLimit = 0;
   103193   int iOffset;
   103194   int addr1, n;
   103195   if( p->iLimit ) return;
   103196 
   103197   /*
   103198   ** "LIMIT -1" always shows all rows.  There is some
   103199   ** controversy about what the correct behavior should be.
   103200   ** The current implementation interprets "LIMIT 0" to mean
   103201   ** no rows.
   103202   */
   103203   sqlite3ExprCacheClear(pParse);
   103204   assert( p->pOffset==0 || p->pLimit!=0 );
   103205   if( p->pLimit ){
   103206     p->iLimit = iLimit = ++pParse->nMem;
   103207     v = sqlite3GetVdbe(pParse);
   103208     assert( v!=0 );
   103209     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
   103210       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
   103211       VdbeComment((v, "LIMIT counter"));
   103212       if( n==0 ){
   103213         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
   103214       }else if( n>=0 && p->nSelectRow>(u64)n ){
   103215         p->nSelectRow = n;
   103216       }
   103217     }else{
   103218       sqlite3ExprCode(pParse, p->pLimit, iLimit);
   103219       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
   103220       VdbeComment((v, "LIMIT counter"));
   103221       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
   103222     }
   103223     if( p->pOffset ){
   103224       p->iOffset = iOffset = ++pParse->nMem;
   103225       pParse->nMem++;   /* Allocate an extra register for limit+offset */
   103226       sqlite3ExprCode(pParse, p->pOffset, iOffset);
   103227       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
   103228       VdbeComment((v, "OFFSET counter"));
   103229       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
   103230       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
   103231       sqlite3VdbeJumpHere(v, addr1);
   103232       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
   103233       VdbeComment((v, "LIMIT+OFFSET"));
   103234       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
   103235       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
   103236       sqlite3VdbeJumpHere(v, addr1);
   103237     }
   103238   }
   103239 }
   103240 
   103241 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   103242 /*
   103243 ** Return the appropriate collating sequence for the iCol-th column of
   103244 ** the result set for the compound-select statement "p".  Return NULL if
   103245 ** the column has no default collating sequence.
   103246 **
   103247 ** The collating sequence for the compound select is taken from the
   103248 ** left-most term of the select that has a collating sequence.
   103249 */
   103250 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
   103251   CollSeq *pRet;
   103252   if( p->pPrior ){
   103253     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
   103254   }else{
   103255     pRet = 0;
   103256   }
   103257   assert( iCol>=0 );
   103258   if( pRet==0 && iCol<p->pEList->nExpr ){
   103259     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
   103260   }
   103261   return pRet;
   103262 }
   103263 
   103264 /*
   103265 ** The select statement passed as the second parameter is a compound SELECT
   103266 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
   103267 ** structure suitable for implementing the ORDER BY.
   103268 **
   103269 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
   103270 ** function is responsible for ensuring that this structure is eventually
   103271 ** freed.
   103272 */
   103273 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
   103274   ExprList *pOrderBy = p->pOrderBy;
   103275   int nOrderBy = p->pOrderBy->nExpr;
   103276   sqlite3 *db = pParse->db;
   103277   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
   103278   if( pRet ){
   103279     int i;
   103280     for(i=0; i<nOrderBy; i++){
   103281       struct ExprList_item *pItem = &pOrderBy->a[i];
   103282       Expr *pTerm = pItem->pExpr;
   103283       CollSeq *pColl;
   103284 
   103285       if( pTerm->flags & EP_Collate ){
   103286         pColl = sqlite3ExprCollSeq(pParse, pTerm);
   103287       }else{
   103288         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
   103289         if( pColl==0 ) pColl = db->pDfltColl;
   103290         pOrderBy->a[i].pExpr =
   103291           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
   103292       }
   103293       assert( sqlite3KeyInfoIsWriteable(pRet) );
   103294       pRet->aColl[i] = pColl;
   103295       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
   103296     }
   103297   }
   103298 
   103299   return pRet;
   103300 }
   103301 
   103302 #ifndef SQLITE_OMIT_CTE
   103303 /*
   103304 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
   103305 ** query of the form:
   103306 **
   103307 **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
   103308 **                         \___________/             \_______________/
   103309 **                           p->pPrior                      p
   103310 **
   103311 **
   103312 ** There is exactly one reference to the recursive-table in the FROM clause
   103313 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
   103314 **
   103315 ** The setup-query runs once to generate an initial set of rows that go
   103316 ** into a Queue table.  Rows are extracted from the Queue table one by
   103317 ** one.  Each row extracted from Queue is output to pDest.  Then the single
   103318 ** extracted row (now in the iCurrent table) becomes the content of the
   103319 ** recursive-table for a recursive-query run.  The output of the recursive-query
   103320 ** is added back into the Queue table.  Then another row is extracted from Queue
   103321 ** and the iteration continues until the Queue table is empty.
   103322 **
   103323 ** If the compound query operator is UNION then no duplicate rows are ever
   103324 ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
   103325 ** that have ever been inserted into Queue and causes duplicates to be
   103326 ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
   103327 **
   103328 ** If the query has an ORDER BY, then entries in the Queue table are kept in
   103329 ** ORDER BY order and the first entry is extracted for each cycle.  Without
   103330 ** an ORDER BY, the Queue table is just a FIFO.
   103331 **
   103332 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
   103333 ** have been output to pDest.  A LIMIT of zero means to output no rows and a
   103334 ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
   103335 ** with a positive value, then the first OFFSET outputs are discarded rather
   103336 ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
   103337 ** rows have been skipped.
   103338 */
   103339 static void generateWithRecursiveQuery(
   103340   Parse *pParse,        /* Parsing context */
   103341   Select *p,            /* The recursive SELECT to be coded */
   103342   SelectDest *pDest     /* What to do with query results */
   103343 ){
   103344   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
   103345   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
   103346   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
   103347   Select *pSetup = p->pPrior;   /* The setup query */
   103348   int addrTop;                  /* Top of the loop */
   103349   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
   103350   int iCurrent = 0;             /* The Current table */
   103351   int regCurrent;               /* Register holding Current table */
   103352   int iQueue;                   /* The Queue table */
   103353   int iDistinct = 0;            /* To ensure unique results if UNION */
   103354   int eDest = SRT_Fifo;         /* How to write to Queue */
   103355   SelectDest destQueue;         /* SelectDest targetting the Queue table */
   103356   int i;                        /* Loop counter */
   103357   int rc;                       /* Result code */
   103358   ExprList *pOrderBy;           /* The ORDER BY clause */
   103359   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
   103360   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
   103361 
   103362   /* Obtain authorization to do a recursive query */
   103363   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
   103364 
   103365   /* Process the LIMIT and OFFSET clauses, if they exist */
   103366   addrBreak = sqlite3VdbeMakeLabel(v);
   103367   computeLimitRegisters(pParse, p, addrBreak);
   103368   pLimit = p->pLimit;
   103369   pOffset = p->pOffset;
   103370   regLimit = p->iLimit;
   103371   regOffset = p->iOffset;
   103372   p->pLimit = p->pOffset = 0;
   103373   p->iLimit = p->iOffset = 0;
   103374   pOrderBy = p->pOrderBy;
   103375 
   103376   /* Locate the cursor number of the Current table */
   103377   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
   103378     if( pSrc->a[i].isRecursive ){
   103379       iCurrent = pSrc->a[i].iCursor;
   103380       break;
   103381     }
   103382   }
   103383 
   103384   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
   103385   ** the Distinct table must be exactly one greater than Queue in order
   103386   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
   103387   iQueue = pParse->nTab++;
   103388   if( p->op==TK_UNION ){
   103389     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
   103390     iDistinct = pParse->nTab++;
   103391   }else{
   103392     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
   103393   }
   103394   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
   103395 
   103396   /* Allocate cursors for Current, Queue, and Distinct. */
   103397   regCurrent = ++pParse->nMem;
   103398   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
   103399   if( pOrderBy ){
   103400     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
   103401     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
   103402                       (char*)pKeyInfo, P4_KEYINFO);
   103403     destQueue.pOrderBy = pOrderBy;
   103404   }else{
   103405     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
   103406   }
   103407   VdbeComment((v, "Queue table"));
   103408   if( iDistinct ){
   103409     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
   103410     p->selFlags |= SF_UsesEphemeral;
   103411   }
   103412 
   103413   /* Detach the ORDER BY clause from the compound SELECT */
   103414   p->pOrderBy = 0;
   103415 
   103416   /* Store the results of the setup-query in Queue. */
   103417   pSetup->pNext = 0;
   103418   rc = sqlite3Select(pParse, pSetup, &destQueue);
   103419   pSetup->pNext = p;
   103420   if( rc ) goto end_of_recursive_query;
   103421 
   103422   /* Find the next row in the Queue and output that row */
   103423   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
   103424 
   103425   /* Transfer the next row in Queue over to Current */
   103426   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
   103427   if( pOrderBy ){
   103428     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
   103429   }else{
   103430     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
   103431   }
   103432   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
   103433 
   103434   /* Output the single row in Current */
   103435   addrCont = sqlite3VdbeMakeLabel(v);
   103436   codeOffset(v, regOffset, addrCont);
   103437   selectInnerLoop(pParse, p, p->pEList, iCurrent,
   103438       0, 0, pDest, addrCont, addrBreak);
   103439   if( regLimit ){
   103440     sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
   103441     VdbeCoverage(v);
   103442   }
   103443   sqlite3VdbeResolveLabel(v, addrCont);
   103444 
   103445   /* Execute the recursive SELECT taking the single row in Current as
   103446   ** the value for the recursive-table. Store the results in the Queue.
   103447   */
   103448   p->pPrior = 0;
   103449   sqlite3Select(pParse, p, &destQueue);
   103450   assert( p->pPrior==0 );
   103451   p->pPrior = pSetup;
   103452 
   103453   /* Keep running the loop until the Queue is empty */
   103454   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
   103455   sqlite3VdbeResolveLabel(v, addrBreak);
   103456 
   103457 end_of_recursive_query:
   103458   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
   103459   p->pOrderBy = pOrderBy;
   103460   p->pLimit = pLimit;
   103461   p->pOffset = pOffset;
   103462   return;
   103463 }
   103464 #endif /* SQLITE_OMIT_CTE */
   103465 
   103466 /* Forward references */
   103467 static int multiSelectOrderBy(
   103468   Parse *pParse,        /* Parsing context */
   103469   Select *p,            /* The right-most of SELECTs to be coded */
   103470   SelectDest *pDest     /* What to do with query results */
   103471 );
   103472 
   103473 
   103474 /*
   103475 ** This routine is called to process a compound query form from
   103476 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
   103477 ** INTERSECT
   103478 **
   103479 ** "p" points to the right-most of the two queries.  the query on the
   103480 ** left is p->pPrior.  The left query could also be a compound query
   103481 ** in which case this routine will be called recursively.
   103482 **
   103483 ** The results of the total query are to be written into a destination
   103484 ** of type eDest with parameter iParm.
   103485 **
   103486 ** Example 1:  Consider a three-way compound SQL statement.
   103487 **
   103488 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
   103489 **
   103490 ** This statement is parsed up as follows:
   103491 **
   103492 **     SELECT c FROM t3
   103493 **      |
   103494 **      `----->  SELECT b FROM t2
   103495 **                |
   103496 **                `------>  SELECT a FROM t1
   103497 **
   103498 ** The arrows in the diagram above represent the Select.pPrior pointer.
   103499 ** So if this routine is called with p equal to the t3 query, then
   103500 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
   103501 **
   103502 ** Notice that because of the way SQLite parses compound SELECTs, the
   103503 ** individual selects always group from left to right.
   103504 */
   103505 static int multiSelect(
   103506   Parse *pParse,        /* Parsing context */
   103507   Select *p,            /* The right-most of SELECTs to be coded */
   103508   SelectDest *pDest     /* What to do with query results */
   103509 ){
   103510   int rc = SQLITE_OK;   /* Success code from a subroutine */
   103511   Select *pPrior;       /* Another SELECT immediately to our left */
   103512   Vdbe *v;              /* Generate code to this VDBE */
   103513   SelectDest dest;      /* Alternative data destination */
   103514   Select *pDelete = 0;  /* Chain of simple selects to delete */
   103515   sqlite3 *db;          /* Database connection */
   103516 #ifndef SQLITE_OMIT_EXPLAIN
   103517   int iSub1 = 0;        /* EQP id of left-hand query */
   103518   int iSub2 = 0;        /* EQP id of right-hand query */
   103519 #endif
   103520 
   103521   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
   103522   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
   103523   */
   103524   assert( p && p->pPrior );  /* Calling function guarantees this much */
   103525   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
   103526   db = pParse->db;
   103527   pPrior = p->pPrior;
   103528   dest = *pDest;
   103529   if( pPrior->pOrderBy ){
   103530     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
   103531       selectOpName(p->op));
   103532     rc = 1;
   103533     goto multi_select_end;
   103534   }
   103535   if( pPrior->pLimit ){
   103536     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
   103537       selectOpName(p->op));
   103538     rc = 1;
   103539     goto multi_select_end;
   103540   }
   103541 
   103542   v = sqlite3GetVdbe(pParse);
   103543   assert( v!=0 );  /* The VDBE already created by calling function */
   103544 
   103545   /* Create the destination temporary table if necessary
   103546   */
   103547   if( dest.eDest==SRT_EphemTab ){
   103548     assert( p->pEList );
   103549     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
   103550     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   103551     dest.eDest = SRT_Table;
   103552   }
   103553 
   103554   /* Make sure all SELECTs in the statement have the same number of elements
   103555   ** in their result sets.
   103556   */
   103557   assert( p->pEList && pPrior->pEList );
   103558   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
   103559     if( p->selFlags & SF_Values ){
   103560       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
   103561     }else{
   103562       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
   103563         " do not have the same number of result columns", selectOpName(p->op));
   103564     }
   103565     rc = 1;
   103566     goto multi_select_end;
   103567   }
   103568 
   103569 #ifndef SQLITE_OMIT_CTE
   103570   if( p->selFlags & SF_Recursive ){
   103571     generateWithRecursiveQuery(pParse, p, &dest);
   103572   }else
   103573 #endif
   103574 
   103575   /* Compound SELECTs that have an ORDER BY clause are handled separately.
   103576   */
   103577   if( p->pOrderBy ){
   103578     return multiSelectOrderBy(pParse, p, pDest);
   103579   }else
   103580 
   103581   /* Generate code for the left and right SELECT statements.
   103582   */
   103583   switch( p->op ){
   103584     case TK_ALL: {
   103585       int addr = 0;
   103586       int nLimit;
   103587       assert( !pPrior->pLimit );
   103588       pPrior->iLimit = p->iLimit;
   103589       pPrior->iOffset = p->iOffset;
   103590       pPrior->pLimit = p->pLimit;
   103591       pPrior->pOffset = p->pOffset;
   103592       explainSetInteger(iSub1, pParse->iNextSelectId);
   103593       rc = sqlite3Select(pParse, pPrior, &dest);
   103594       p->pLimit = 0;
   103595       p->pOffset = 0;
   103596       if( rc ){
   103597         goto multi_select_end;
   103598       }
   103599       p->pPrior = 0;
   103600       p->iLimit = pPrior->iLimit;
   103601       p->iOffset = pPrior->iOffset;
   103602       if( p->iLimit ){
   103603         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
   103604         VdbeComment((v, "Jump ahead if LIMIT reached"));
   103605       }
   103606       explainSetInteger(iSub2, pParse->iNextSelectId);
   103607       rc = sqlite3Select(pParse, p, &dest);
   103608       testcase( rc!=SQLITE_OK );
   103609       pDelete = p->pPrior;
   103610       p->pPrior = pPrior;
   103611       p->nSelectRow += pPrior->nSelectRow;
   103612       if( pPrior->pLimit
   103613        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
   103614        && nLimit>0 && p->nSelectRow > (u64)nLimit
   103615       ){
   103616         p->nSelectRow = nLimit;
   103617       }
   103618       if( addr ){
   103619         sqlite3VdbeJumpHere(v, addr);
   103620       }
   103621       break;
   103622     }
   103623     case TK_EXCEPT:
   103624     case TK_UNION: {
   103625       int unionTab;    /* Cursor number of the temporary table holding result */
   103626       u8 op = 0;       /* One of the SRT_ operations to apply to self */
   103627       int priorOp;     /* The SRT_ operation to apply to prior selects */
   103628       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
   103629       int addr;
   103630       SelectDest uniondest;
   103631 
   103632       testcase( p->op==TK_EXCEPT );
   103633       testcase( p->op==TK_UNION );
   103634       priorOp = SRT_Union;
   103635       if( dest.eDest==priorOp ){
   103636         /* We can reuse a temporary table generated by a SELECT to our
   103637         ** right.
   103638         */
   103639         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
   103640         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
   103641         unionTab = dest.iSDParm;
   103642       }else{
   103643         /* We will need to create our own temporary table to hold the
   103644         ** intermediate results.
   103645         */
   103646         unionTab = pParse->nTab++;
   103647         assert( p->pOrderBy==0 );
   103648         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
   103649         assert( p->addrOpenEphm[0] == -1 );
   103650         p->addrOpenEphm[0] = addr;
   103651         findRightmost(p)->selFlags |= SF_UsesEphemeral;
   103652         assert( p->pEList );
   103653       }
   103654 
   103655       /* Code the SELECT statements to our left
   103656       */
   103657       assert( !pPrior->pOrderBy );
   103658       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
   103659       explainSetInteger(iSub1, pParse->iNextSelectId);
   103660       rc = sqlite3Select(pParse, pPrior, &uniondest);
   103661       if( rc ){
   103662         goto multi_select_end;
   103663       }
   103664 
   103665       /* Code the current SELECT statement
   103666       */
   103667       if( p->op==TK_EXCEPT ){
   103668         op = SRT_Except;
   103669       }else{
   103670         assert( p->op==TK_UNION );
   103671         op = SRT_Union;
   103672       }
   103673       p->pPrior = 0;
   103674       pLimit = p->pLimit;
   103675       p->pLimit = 0;
   103676       pOffset = p->pOffset;
   103677       p->pOffset = 0;
   103678       uniondest.eDest = op;
   103679       explainSetInteger(iSub2, pParse->iNextSelectId);
   103680       rc = sqlite3Select(pParse, p, &uniondest);
   103681       testcase( rc!=SQLITE_OK );
   103682       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
   103683       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
   103684       sqlite3ExprListDelete(db, p->pOrderBy);
   103685       pDelete = p->pPrior;
   103686       p->pPrior = pPrior;
   103687       p->pOrderBy = 0;
   103688       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
   103689       sqlite3ExprDelete(db, p->pLimit);
   103690       p->pLimit = pLimit;
   103691       p->pOffset = pOffset;
   103692       p->iLimit = 0;
   103693       p->iOffset = 0;
   103694 
   103695       /* Convert the data in the temporary table into whatever form
   103696       ** it is that we currently need.
   103697       */
   103698       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
   103699       if( dest.eDest!=priorOp ){
   103700         int iCont, iBreak, iStart;
   103701         assert( p->pEList );
   103702         if( dest.eDest==SRT_Output ){
   103703           Select *pFirst = p;
   103704           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   103705           generateColumnNames(pParse, 0, pFirst->pEList);
   103706         }
   103707         iBreak = sqlite3VdbeMakeLabel(v);
   103708         iCont = sqlite3VdbeMakeLabel(v);
   103709         computeLimitRegisters(pParse, p, iBreak);
   103710         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
   103711         iStart = sqlite3VdbeCurrentAddr(v);
   103712         selectInnerLoop(pParse, p, p->pEList, unionTab,
   103713                         0, 0, &dest, iCont, iBreak);
   103714         sqlite3VdbeResolveLabel(v, iCont);
   103715         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
   103716         sqlite3VdbeResolveLabel(v, iBreak);
   103717         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
   103718       }
   103719       break;
   103720     }
   103721     default: assert( p->op==TK_INTERSECT ); {
   103722       int tab1, tab2;
   103723       int iCont, iBreak, iStart;
   103724       Expr *pLimit, *pOffset;
   103725       int addr;
   103726       SelectDest intersectdest;
   103727       int r1;
   103728 
   103729       /* INTERSECT is different from the others since it requires
   103730       ** two temporary tables.  Hence it has its own case.  Begin
   103731       ** by allocating the tables we will need.
   103732       */
   103733       tab1 = pParse->nTab++;
   103734       tab2 = pParse->nTab++;
   103735       assert( p->pOrderBy==0 );
   103736 
   103737       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
   103738       assert( p->addrOpenEphm[0] == -1 );
   103739       p->addrOpenEphm[0] = addr;
   103740       findRightmost(p)->selFlags |= SF_UsesEphemeral;
   103741       assert( p->pEList );
   103742 
   103743       /* Code the SELECTs to our left into temporary table "tab1".
   103744       */
   103745       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
   103746       explainSetInteger(iSub1, pParse->iNextSelectId);
   103747       rc = sqlite3Select(pParse, pPrior, &intersectdest);
   103748       if( rc ){
   103749         goto multi_select_end;
   103750       }
   103751 
   103752       /* Code the current SELECT into temporary table "tab2"
   103753       */
   103754       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
   103755       assert( p->addrOpenEphm[1] == -1 );
   103756       p->addrOpenEphm[1] = addr;
   103757       p->pPrior = 0;
   103758       pLimit = p->pLimit;
   103759       p->pLimit = 0;
   103760       pOffset = p->pOffset;
   103761       p->pOffset = 0;
   103762       intersectdest.iSDParm = tab2;
   103763       explainSetInteger(iSub2, pParse->iNextSelectId);
   103764       rc = sqlite3Select(pParse, p, &intersectdest);
   103765       testcase( rc!=SQLITE_OK );
   103766       pDelete = p->pPrior;
   103767       p->pPrior = pPrior;
   103768       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   103769       sqlite3ExprDelete(db, p->pLimit);
   103770       p->pLimit = pLimit;
   103771       p->pOffset = pOffset;
   103772 
   103773       /* Generate code to take the intersection of the two temporary
   103774       ** tables.
   103775       */
   103776       assert( p->pEList );
   103777       if( dest.eDest==SRT_Output ){
   103778         Select *pFirst = p;
   103779         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   103780         generateColumnNames(pParse, 0, pFirst->pEList);
   103781       }
   103782       iBreak = sqlite3VdbeMakeLabel(v);
   103783       iCont = sqlite3VdbeMakeLabel(v);
   103784       computeLimitRegisters(pParse, p, iBreak);
   103785       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
   103786       r1 = sqlite3GetTempReg(pParse);
   103787       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
   103788       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
   103789       sqlite3ReleaseTempReg(pParse, r1);
   103790       selectInnerLoop(pParse, p, p->pEList, tab1,
   103791                       0, 0, &dest, iCont, iBreak);
   103792       sqlite3VdbeResolveLabel(v, iCont);
   103793       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
   103794       sqlite3VdbeResolveLabel(v, iBreak);
   103795       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
   103796       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
   103797       break;
   103798     }
   103799   }
   103800 
   103801   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
   103802 
   103803   /* Compute collating sequences used by
   103804   ** temporary tables needed to implement the compound select.
   103805   ** Attach the KeyInfo structure to all temporary tables.
   103806   **
   103807   ** This section is run by the right-most SELECT statement only.
   103808   ** SELECT statements to the left always skip this part.  The right-most
   103809   ** SELECT might also skip this part if it has no ORDER BY clause and
   103810   ** no temp tables are required.
   103811   */
   103812   if( p->selFlags & SF_UsesEphemeral ){
   103813     int i;                        /* Loop counter */
   103814     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
   103815     Select *pLoop;                /* For looping through SELECT statements */
   103816     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
   103817     int nCol;                     /* Number of columns in result set */
   103818 
   103819     assert( p->pNext==0 );
   103820     nCol = p->pEList->nExpr;
   103821     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
   103822     if( !pKeyInfo ){
   103823       rc = SQLITE_NOMEM;
   103824       goto multi_select_end;
   103825     }
   103826     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
   103827       *apColl = multiSelectCollSeq(pParse, p, i);
   103828       if( 0==*apColl ){
   103829         *apColl = db->pDfltColl;
   103830       }
   103831     }
   103832 
   103833     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
   103834       for(i=0; i<2; i++){
   103835         int addr = pLoop->addrOpenEphm[i];
   103836         if( addr<0 ){
   103837           /* If [0] is unused then [1] is also unused.  So we can
   103838           ** always safely abort as soon as the first unused slot is found */
   103839           assert( pLoop->addrOpenEphm[1]<0 );
   103840           break;
   103841         }
   103842         sqlite3VdbeChangeP2(v, addr, nCol);
   103843         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
   103844                             P4_KEYINFO);
   103845         pLoop->addrOpenEphm[i] = -1;
   103846       }
   103847     }
   103848     sqlite3KeyInfoUnref(pKeyInfo);
   103849   }
   103850 
   103851 multi_select_end:
   103852   pDest->iSdst = dest.iSdst;
   103853   pDest->nSdst = dest.nSdst;
   103854   sqlite3SelectDelete(db, pDelete);
   103855   return rc;
   103856 }
   103857 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   103858 
   103859 /*
   103860 ** Code an output subroutine for a coroutine implementation of a
   103861 ** SELECT statment.
   103862 **
   103863 ** The data to be output is contained in pIn->iSdst.  There are
   103864 ** pIn->nSdst columns to be output.  pDest is where the output should
   103865 ** be sent.
   103866 **
   103867 ** regReturn is the number of the register holding the subroutine
   103868 ** return address.
   103869 **
   103870 ** If regPrev>0 then it is the first register in a vector that
   103871 ** records the previous output.  mem[regPrev] is a flag that is false
   103872 ** if there has been no previous output.  If regPrev>0 then code is
   103873 ** generated to suppress duplicates.  pKeyInfo is used for comparing
   103874 ** keys.
   103875 **
   103876 ** If the LIMIT found in p->iLimit is reached, jump immediately to
   103877 ** iBreak.
   103878 */
   103879 static int generateOutputSubroutine(
   103880   Parse *pParse,          /* Parsing context */
   103881   Select *p,              /* The SELECT statement */
   103882   SelectDest *pIn,        /* Coroutine supplying data */
   103883   SelectDest *pDest,      /* Where to send the data */
   103884   int regReturn,          /* The return address register */
   103885   int regPrev,            /* Previous result register.  No uniqueness if 0 */
   103886   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
   103887   int iBreak              /* Jump here if we hit the LIMIT */
   103888 ){
   103889   Vdbe *v = pParse->pVdbe;
   103890   int iContinue;
   103891   int addr;
   103892 
   103893   addr = sqlite3VdbeCurrentAddr(v);
   103894   iContinue = sqlite3VdbeMakeLabel(v);
   103895 
   103896   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
   103897   */
   103898   if( regPrev ){
   103899     int j1, j2;
   103900     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
   103901     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
   103902                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
   103903     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
   103904     sqlite3VdbeJumpHere(v, j1);
   103905     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
   103906     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
   103907   }
   103908   if( pParse->db->mallocFailed ) return 0;
   103909 
   103910   /* Suppress the first OFFSET entries if there is an OFFSET clause
   103911   */
   103912   codeOffset(v, p->iOffset, iContinue);
   103913 
   103914   switch( pDest->eDest ){
   103915     /* Store the result as data using a unique key.
   103916     */
   103917     case SRT_Table:
   103918     case SRT_EphemTab: {
   103919       int r1 = sqlite3GetTempReg(pParse);
   103920       int r2 = sqlite3GetTempReg(pParse);
   103921       testcase( pDest->eDest==SRT_Table );
   103922       testcase( pDest->eDest==SRT_EphemTab );
   103923       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
   103924       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
   103925       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
   103926       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   103927       sqlite3ReleaseTempReg(pParse, r2);
   103928       sqlite3ReleaseTempReg(pParse, r1);
   103929       break;
   103930     }
   103931 
   103932 #ifndef SQLITE_OMIT_SUBQUERY
   103933     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   103934     ** then there should be a single item on the stack.  Write this
   103935     ** item into the set table with bogus data.
   103936     */
   103937     case SRT_Set: {
   103938       int r1;
   103939       assert( pIn->nSdst==1 );
   103940       pDest->affSdst =
   103941          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
   103942       r1 = sqlite3GetTempReg(pParse);
   103943       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
   103944       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
   103945       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
   103946       sqlite3ReleaseTempReg(pParse, r1);
   103947       break;
   103948     }
   103949 
   103950 #if 0  /* Never occurs on an ORDER BY query */
   103951     /* If any row exist in the result set, record that fact and abort.
   103952     */
   103953     case SRT_Exists: {
   103954       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
   103955       /* The LIMIT clause will terminate the loop for us */
   103956       break;
   103957     }
   103958 #endif
   103959 
   103960     /* If this is a scalar select that is part of an expression, then
   103961     ** store the results in the appropriate memory cell and break out
   103962     ** of the scan loop.
   103963     */
   103964     case SRT_Mem: {
   103965       assert( pIn->nSdst==1 );
   103966       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
   103967       /* The LIMIT clause will jump out of the loop for us */
   103968       break;
   103969     }
   103970 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   103971 
   103972     /* The results are stored in a sequence of registers
   103973     ** starting at pDest->iSdst.  Then the co-routine yields.
   103974     */
   103975     case SRT_Coroutine: {
   103976       if( pDest->iSdst==0 ){
   103977         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
   103978         pDest->nSdst = pIn->nSdst;
   103979       }
   103980       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
   103981       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   103982       break;
   103983     }
   103984 
   103985     /* If none of the above, then the result destination must be
   103986     ** SRT_Output.  This routine is never called with any other
   103987     ** destination other than the ones handled above or SRT_Output.
   103988     **
   103989     ** For SRT_Output, results are stored in a sequence of registers.
   103990     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
   103991     ** return the next row of result.
   103992     */
   103993     default: {
   103994       assert( pDest->eDest==SRT_Output );
   103995       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
   103996       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
   103997       break;
   103998     }
   103999   }
   104000 
   104001   /* Jump to the end of the loop if the LIMIT is reached.
   104002   */
   104003   if( p->iLimit ){
   104004     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
   104005   }
   104006 
   104007   /* Generate the subroutine return
   104008   */
   104009   sqlite3VdbeResolveLabel(v, iContinue);
   104010   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
   104011 
   104012   return addr;
   104013 }
   104014 
   104015 /*
   104016 ** Alternative compound select code generator for cases when there
   104017 ** is an ORDER BY clause.
   104018 **
   104019 ** We assume a query of the following form:
   104020 **
   104021 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
   104022 **
   104023 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
   104024 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
   104025 ** co-routines.  Then run the co-routines in parallel and merge the results
   104026 ** into the output.  In addition to the two coroutines (called selectA and
   104027 ** selectB) there are 7 subroutines:
   104028 **
   104029 **    outA:    Move the output of the selectA coroutine into the output
   104030 **             of the compound query.
   104031 **
   104032 **    outB:    Move the output of the selectB coroutine into the output
   104033 **             of the compound query.  (Only generated for UNION and
   104034 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
   104035 **             appears only in B.)
   104036 **
   104037 **    AltB:    Called when there is data from both coroutines and A<B.
   104038 **
   104039 **    AeqB:    Called when there is data from both coroutines and A==B.
   104040 **
   104041 **    AgtB:    Called when there is data from both coroutines and A>B.
   104042 **
   104043 **    EofA:    Called when data is exhausted from selectA.
   104044 **
   104045 **    EofB:    Called when data is exhausted from selectB.
   104046 **
   104047 ** The implementation of the latter five subroutines depend on which
   104048 ** <operator> is used:
   104049 **
   104050 **
   104051 **             UNION ALL         UNION            EXCEPT          INTERSECT
   104052 **          -------------  -----------------  --------------  -----------------
   104053 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
   104054 **
   104055 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
   104056 **
   104057 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
   104058 **
   104059 **   EofA:   outB, nextB      outB, nextB          halt             halt
   104060 **
   104061 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
   104062 **
   104063 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
   104064 ** causes an immediate jump to EofA and an EOF on B following nextB causes
   104065 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
   104066 ** following nextX causes a jump to the end of the select processing.
   104067 **
   104068 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
   104069 ** within the output subroutine.  The regPrev register set holds the previously
   104070 ** output value.  A comparison is made against this value and the output
   104071 ** is skipped if the next results would be the same as the previous.
   104072 **
   104073 ** The implementation plan is to implement the two coroutines and seven
   104074 ** subroutines first, then put the control logic at the bottom.  Like this:
   104075 **
   104076 **          goto Init
   104077 **     coA: coroutine for left query (A)
   104078 **     coB: coroutine for right query (B)
   104079 **    outA: output one row of A
   104080 **    outB: output one row of B (UNION and UNION ALL only)
   104081 **    EofA: ...
   104082 **    EofB: ...
   104083 **    AltB: ...
   104084 **    AeqB: ...
   104085 **    AgtB: ...
   104086 **    Init: initialize coroutine registers
   104087 **          yield coA
   104088 **          if eof(A) goto EofA
   104089 **          yield coB
   104090 **          if eof(B) goto EofB
   104091 **    Cmpr: Compare A, B
   104092 **          Jump AltB, AeqB, AgtB
   104093 **     End: ...
   104094 **
   104095 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
   104096 ** actually called using Gosub and they do not Return.  EofA and EofB loop
   104097 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
   104098 ** and AgtB jump to either L2 or to one of EofA or EofB.
   104099 */
   104100 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   104101 static int multiSelectOrderBy(
   104102   Parse *pParse,        /* Parsing context */
   104103   Select *p,            /* The right-most of SELECTs to be coded */
   104104   SelectDest *pDest     /* What to do with query results */
   104105 ){
   104106   int i, j;             /* Loop counters */
   104107   Select *pPrior;       /* Another SELECT immediately to our left */
   104108   Vdbe *v;              /* Generate code to this VDBE */
   104109   SelectDest destA;     /* Destination for coroutine A */
   104110   SelectDest destB;     /* Destination for coroutine B */
   104111   int regAddrA;         /* Address register for select-A coroutine */
   104112   int regAddrB;         /* Address register for select-B coroutine */
   104113   int addrSelectA;      /* Address of the select-A coroutine */
   104114   int addrSelectB;      /* Address of the select-B coroutine */
   104115   int regOutA;          /* Address register for the output-A subroutine */
   104116   int regOutB;          /* Address register for the output-B subroutine */
   104117   int addrOutA;         /* Address of the output-A subroutine */
   104118   int addrOutB = 0;     /* Address of the output-B subroutine */
   104119   int addrEofA;         /* Address of the select-A-exhausted subroutine */
   104120   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
   104121   int addrEofB;         /* Address of the select-B-exhausted subroutine */
   104122   int addrAltB;         /* Address of the A<B subroutine */
   104123   int addrAeqB;         /* Address of the A==B subroutine */
   104124   int addrAgtB;         /* Address of the A>B subroutine */
   104125   int regLimitA;        /* Limit register for select-A */
   104126   int regLimitB;        /* Limit register for select-A */
   104127   int regPrev;          /* A range of registers to hold previous output */
   104128   int savedLimit;       /* Saved value of p->iLimit */
   104129   int savedOffset;      /* Saved value of p->iOffset */
   104130   int labelCmpr;        /* Label for the start of the merge algorithm */
   104131   int labelEnd;         /* Label for the end of the overall SELECT stmt */
   104132   int j1;               /* Jump instructions that get retargetted */
   104133   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
   104134   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
   104135   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
   104136   sqlite3 *db;          /* Database connection */
   104137   ExprList *pOrderBy;   /* The ORDER BY clause */
   104138   int nOrderBy;         /* Number of terms in the ORDER BY clause */
   104139   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
   104140 #ifndef SQLITE_OMIT_EXPLAIN
   104141   int iSub1;            /* EQP id of left-hand query */
   104142   int iSub2;            /* EQP id of right-hand query */
   104143 #endif
   104144 
   104145   assert( p->pOrderBy!=0 );
   104146   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
   104147   db = pParse->db;
   104148   v = pParse->pVdbe;
   104149   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
   104150   labelEnd = sqlite3VdbeMakeLabel(v);
   104151   labelCmpr = sqlite3VdbeMakeLabel(v);
   104152 
   104153 
   104154   /* Patch up the ORDER BY clause
   104155   */
   104156   op = p->op;
   104157   pPrior = p->pPrior;
   104158   assert( pPrior->pOrderBy==0 );
   104159   pOrderBy = p->pOrderBy;
   104160   assert( pOrderBy );
   104161   nOrderBy = pOrderBy->nExpr;
   104162 
   104163   /* For operators other than UNION ALL we have to make sure that
   104164   ** the ORDER BY clause covers every term of the result set.  Add
   104165   ** terms to the ORDER BY clause as necessary.
   104166   */
   104167   if( op!=TK_ALL ){
   104168     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
   104169       struct ExprList_item *pItem;
   104170       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
   104171         assert( pItem->u.x.iOrderByCol>0 );
   104172         if( pItem->u.x.iOrderByCol==i ) break;
   104173       }
   104174       if( j==nOrderBy ){
   104175         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   104176         if( pNew==0 ) return SQLITE_NOMEM;
   104177         pNew->flags |= EP_IntValue;
   104178         pNew->u.iValue = i;
   104179         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
   104180         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
   104181       }
   104182     }
   104183   }
   104184 
   104185   /* Compute the comparison permutation and keyinfo that is used with
   104186   ** the permutation used to determine if the next
   104187   ** row of results comes from selectA or selectB.  Also add explicit
   104188   ** collations to the ORDER BY clause terms so that when the subqueries
   104189   ** to the right and the left are evaluated, they use the correct
   104190   ** collation.
   104191   */
   104192   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
   104193   if( aPermute ){
   104194     struct ExprList_item *pItem;
   104195     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
   104196       assert( pItem->u.x.iOrderByCol>0
   104197           && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
   104198       aPermute[i] = pItem->u.x.iOrderByCol - 1;
   104199     }
   104200     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
   104201   }else{
   104202     pKeyMerge = 0;
   104203   }
   104204 
   104205   /* Reattach the ORDER BY clause to the query.
   104206   */
   104207   p->pOrderBy = pOrderBy;
   104208   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
   104209 
   104210   /* Allocate a range of temporary registers and the KeyInfo needed
   104211   ** for the logic that removes duplicate result rows when the
   104212   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
   104213   */
   104214   if( op==TK_ALL ){
   104215     regPrev = 0;
   104216   }else{
   104217     int nExpr = p->pEList->nExpr;
   104218     assert( nOrderBy>=nExpr || db->mallocFailed );
   104219     regPrev = pParse->nMem+1;
   104220     pParse->nMem += nExpr+1;
   104221     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
   104222     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
   104223     if( pKeyDup ){
   104224       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
   104225       for(i=0; i<nExpr; i++){
   104226         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
   104227         pKeyDup->aSortOrder[i] = 0;
   104228       }
   104229     }
   104230   }
   104231 
   104232   /* Separate the left and the right query from one another
   104233   */
   104234   p->pPrior = 0;
   104235   pPrior->pNext = 0;
   104236   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
   104237   if( pPrior->pPrior==0 ){
   104238     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
   104239   }
   104240 
   104241   /* Compute the limit registers */
   104242   computeLimitRegisters(pParse, p, labelEnd);
   104243   if( p->iLimit && op==TK_ALL ){
   104244     regLimitA = ++pParse->nMem;
   104245     regLimitB = ++pParse->nMem;
   104246     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
   104247                                   regLimitA);
   104248     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
   104249   }else{
   104250     regLimitA = regLimitB = 0;
   104251   }
   104252   sqlite3ExprDelete(db, p->pLimit);
   104253   p->pLimit = 0;
   104254   sqlite3ExprDelete(db, p->pOffset);
   104255   p->pOffset = 0;
   104256 
   104257   regAddrA = ++pParse->nMem;
   104258   regAddrB = ++pParse->nMem;
   104259   regOutA = ++pParse->nMem;
   104260   regOutB = ++pParse->nMem;
   104261   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
   104262   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
   104263 
   104264   /* Generate a coroutine to evaluate the SELECT statement to the
   104265   ** left of the compound operator - the "A" select.
   104266   */
   104267   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
   104268   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
   104269   VdbeComment((v, "left SELECT"));
   104270   pPrior->iLimit = regLimitA;
   104271   explainSetInteger(iSub1, pParse->iNextSelectId);
   104272   sqlite3Select(pParse, pPrior, &destA);
   104273   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
   104274   sqlite3VdbeJumpHere(v, j1);
   104275 
   104276   /* Generate a coroutine to evaluate the SELECT statement on
   104277   ** the right - the "B" select
   104278   */
   104279   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
   104280   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
   104281   VdbeComment((v, "right SELECT"));
   104282   savedLimit = p->iLimit;
   104283   savedOffset = p->iOffset;
   104284   p->iLimit = regLimitB;
   104285   p->iOffset = 0;
   104286   explainSetInteger(iSub2, pParse->iNextSelectId);
   104287   sqlite3Select(pParse, p, &destB);
   104288   p->iLimit = savedLimit;
   104289   p->iOffset = savedOffset;
   104290   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
   104291 
   104292   /* Generate a subroutine that outputs the current row of the A
   104293   ** select as the next output row of the compound select.
   104294   */
   104295   VdbeNoopComment((v, "Output routine for A"));
   104296   addrOutA = generateOutputSubroutine(pParse,
   104297                  p, &destA, pDest, regOutA,
   104298                  regPrev, pKeyDup, labelEnd);
   104299 
   104300   /* Generate a subroutine that outputs the current row of the B
   104301   ** select as the next output row of the compound select.
   104302   */
   104303   if( op==TK_ALL || op==TK_UNION ){
   104304     VdbeNoopComment((v, "Output routine for B"));
   104305     addrOutB = generateOutputSubroutine(pParse,
   104306                  p, &destB, pDest, regOutB,
   104307                  regPrev, pKeyDup, labelEnd);
   104308   }
   104309   sqlite3KeyInfoUnref(pKeyDup);
   104310 
   104311   /* Generate a subroutine to run when the results from select A
   104312   ** are exhausted and only data in select B remains.
   104313   */
   104314   if( op==TK_EXCEPT || op==TK_INTERSECT ){
   104315     addrEofA_noB = addrEofA = labelEnd;
   104316   }else{
   104317     VdbeNoopComment((v, "eof-A subroutine"));
   104318     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   104319     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
   104320                                      VdbeCoverage(v);
   104321     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
   104322     p->nSelectRow += pPrior->nSelectRow;
   104323   }
   104324 
   104325   /* Generate a subroutine to run when the results from select B
   104326   ** are exhausted and only data in select A remains.
   104327   */
   104328   if( op==TK_INTERSECT ){
   104329     addrEofB = addrEofA;
   104330     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   104331   }else{
   104332     VdbeNoopComment((v, "eof-B subroutine"));
   104333     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   104334     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
   104335     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
   104336   }
   104337 
   104338   /* Generate code to handle the case of A<B
   104339   */
   104340   VdbeNoopComment((v, "A-lt-B subroutine"));
   104341   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   104342   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
   104343   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   104344 
   104345   /* Generate code to handle the case of A==B
   104346   */
   104347   if( op==TK_ALL ){
   104348     addrAeqB = addrAltB;
   104349   }else if( op==TK_INTERSECT ){
   104350     addrAeqB = addrAltB;
   104351     addrAltB++;
   104352   }else{
   104353     VdbeNoopComment((v, "A-eq-B subroutine"));
   104354     addrAeqB =
   104355     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
   104356     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   104357   }
   104358 
   104359   /* Generate code to handle the case of A>B
   104360   */
   104361   VdbeNoopComment((v, "A-gt-B subroutine"));
   104362   addrAgtB = sqlite3VdbeCurrentAddr(v);
   104363   if( op==TK_ALL || op==TK_UNION ){
   104364     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   104365   }
   104366   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
   104367   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   104368 
   104369   /* This code runs once to initialize everything.
   104370   */
   104371   sqlite3VdbeJumpHere(v, j1);
   104372   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
   104373   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
   104374 
   104375   /* Implement the main merge loop
   104376   */
   104377   sqlite3VdbeResolveLabel(v, labelCmpr);
   104378   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
   104379   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
   104380                          (char*)pKeyMerge, P4_KEYINFO);
   104381   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
   104382   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
   104383 
   104384   /* Jump to the this point in order to terminate the query.
   104385   */
   104386   sqlite3VdbeResolveLabel(v, labelEnd);
   104387 
   104388   /* Set the number of output columns
   104389   */
   104390   if( pDest->eDest==SRT_Output ){
   104391     Select *pFirst = pPrior;
   104392     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   104393     generateColumnNames(pParse, 0, pFirst->pEList);
   104394   }
   104395 
   104396   /* Reassembly the compound query so that it will be freed correctly
   104397   ** by the calling function */
   104398   if( p->pPrior ){
   104399     sqlite3SelectDelete(db, p->pPrior);
   104400   }
   104401   p->pPrior = pPrior;
   104402   pPrior->pNext = p;
   104403 
   104404   /*** TBD:  Insert subroutine calls to close cursors on incomplete
   104405   **** subqueries ****/
   104406   explainComposite(pParse, p->op, iSub1, iSub2, 0);
   104407   return SQLITE_OK;
   104408 }
   104409 #endif
   104410 
   104411 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   104412 /* Forward Declarations */
   104413 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
   104414 static void substSelect(sqlite3*, Select *, int, ExprList *);
   104415 
   104416 /*
   104417 ** Scan through the expression pExpr.  Replace every reference to
   104418 ** a column in table number iTable with a copy of the iColumn-th
   104419 ** entry in pEList.  (But leave references to the ROWID column
   104420 ** unchanged.)
   104421 **
   104422 ** This routine is part of the flattening procedure.  A subquery
   104423 ** whose result set is defined by pEList appears as entry in the
   104424 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
   104425 ** FORM clause entry is iTable.  This routine make the necessary
   104426 ** changes to pExpr so that it refers directly to the source table
   104427 ** of the subquery rather the result set of the subquery.
   104428 */
   104429 static Expr *substExpr(
   104430   sqlite3 *db,        /* Report malloc errors to this connection */
   104431   Expr *pExpr,        /* Expr in which substitution occurs */
   104432   int iTable,         /* Table to be substituted */
   104433   ExprList *pEList    /* Substitute expressions */
   104434 ){
   104435   if( pExpr==0 ) return 0;
   104436   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
   104437     if( pExpr->iColumn<0 ){
   104438       pExpr->op = TK_NULL;
   104439     }else{
   104440       Expr *pNew;
   104441       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
   104442       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   104443       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
   104444       sqlite3ExprDelete(db, pExpr);
   104445       pExpr = pNew;
   104446     }
   104447   }else{
   104448     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
   104449     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
   104450     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   104451       substSelect(db, pExpr->x.pSelect, iTable, pEList);
   104452     }else{
   104453       substExprList(db, pExpr->x.pList, iTable, pEList);
   104454     }
   104455   }
   104456   return pExpr;
   104457 }
   104458 static void substExprList(
   104459   sqlite3 *db,         /* Report malloc errors here */
   104460   ExprList *pList,     /* List to scan and in which to make substitutes */
   104461   int iTable,          /* Table to be substituted */
   104462   ExprList *pEList     /* Substitute values */
   104463 ){
   104464   int i;
   104465   if( pList==0 ) return;
   104466   for(i=0; i<pList->nExpr; i++){
   104467     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
   104468   }
   104469 }
   104470 static void substSelect(
   104471   sqlite3 *db,         /* Report malloc errors here */
   104472   Select *p,           /* SELECT statement in which to make substitutions */
   104473   int iTable,          /* Table to be replaced */
   104474   ExprList *pEList     /* Substitute values */
   104475 ){
   104476   SrcList *pSrc;
   104477   struct SrcList_item *pItem;
   104478   int i;
   104479   if( !p ) return;
   104480   substExprList(db, p->pEList, iTable, pEList);
   104481   substExprList(db, p->pGroupBy, iTable, pEList);
   104482   substExprList(db, p->pOrderBy, iTable, pEList);
   104483   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
   104484   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
   104485   substSelect(db, p->pPrior, iTable, pEList);
   104486   pSrc = p->pSrc;
   104487   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
   104488   if( ALWAYS(pSrc) ){
   104489     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   104490       substSelect(db, pItem->pSelect, iTable, pEList);
   104491     }
   104492   }
   104493 }
   104494 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   104495 
   104496 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   104497 /*
   104498 ** This routine attempts to flatten subqueries as a performance optimization.
   104499 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
   104500 **
   104501 ** To understand the concept of flattening, consider the following
   104502 ** query:
   104503 **
   104504 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
   104505 **
   104506 ** The default way of implementing this query is to execute the
   104507 ** subquery first and store the results in a temporary table, then
   104508 ** run the outer query on that temporary table.  This requires two
   104509 ** passes over the data.  Furthermore, because the temporary table
   104510 ** has no indices, the WHERE clause on the outer query cannot be
   104511 ** optimized.
   104512 **
   104513 ** This routine attempts to rewrite queries such as the above into
   104514 ** a single flat select, like this:
   104515 **
   104516 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
   104517 **
   104518 ** The code generated for this simpification gives the same result
   104519 ** but only has to scan the data once.  And because indices might
   104520 ** exist on the table t1, a complete scan of the data might be
   104521 ** avoided.
   104522 **
   104523 ** Flattening is only attempted if all of the following are true:
   104524 **
   104525 **   (1)  The subquery and the outer query do not both use aggregates.
   104526 **
   104527 **   (2)  The subquery is not an aggregate or the outer query is not a join.
   104528 **
   104529 **   (3)  The subquery is not the right operand of a left outer join
   104530 **        (Originally ticket #306.  Strengthened by ticket #3300)
   104531 **
   104532 **   (4)  The subquery is not DISTINCT.
   104533 **
   104534 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
   104535 **        sub-queries that were excluded from this optimization. Restriction
   104536 **        (4) has since been expanded to exclude all DISTINCT subqueries.
   104537 **
   104538 **   (6)  The subquery does not use aggregates or the outer query is not
   104539 **        DISTINCT.
   104540 **
   104541 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
   104542 **        A FROM clause, consider adding a FROM close with the special
   104543 **        table sqlite_once that consists of a single row containing a
   104544 **        single NULL.
   104545 **
   104546 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
   104547 **
   104548 **   (9)  The subquery does not use LIMIT or the outer query does not use
   104549 **        aggregates.
   104550 **
   104551 **  (10)  The subquery does not use aggregates or the outer query does not
   104552 **        use LIMIT.
   104553 **
   104554 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
   104555 **
   104556 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
   104557 **        a separate restriction deriving from ticket #350.
   104558 **
   104559 **  (13)  The subquery and outer query do not both use LIMIT.
   104560 **
   104561 **  (14)  The subquery does not use OFFSET.
   104562 **
   104563 **  (15)  The outer query is not part of a compound select or the
   104564 **        subquery does not have a LIMIT clause.
   104565 **        (See ticket #2339 and ticket [02a8e81d44]).
   104566 **
   104567 **  (16)  The outer query is not an aggregate or the subquery does
   104568 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
   104569 **        until we introduced the group_concat() function.
   104570 **
   104571 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
   104572 **        compound clause made up entirely of non-aggregate queries, and
   104573 **        the parent query:
   104574 **
   104575 **          * is not itself part of a compound select,
   104576 **          * is not an aggregate or DISTINCT query, and
   104577 **          * is not a join
   104578 **
   104579 **        The parent and sub-query may contain WHERE clauses. Subject to
   104580 **        rules (11), (13) and (14), they may also contain ORDER BY,
   104581 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
   104582 **        operator other than UNION ALL because all the other compound
   104583 **        operators have an implied DISTINCT which is disallowed by
   104584 **        restriction (4).
   104585 **
   104586 **        Also, each component of the sub-query must return the same number
   104587 **        of result columns. This is actually a requirement for any compound
   104588 **        SELECT statement, but all the code here does is make sure that no
   104589 **        such (illegal) sub-query is flattened. The caller will detect the
   104590 **        syntax error and return a detailed message.
   104591 **
   104592 **  (18)  If the sub-query is a compound select, then all terms of the
   104593 **        ORDER by clause of the parent must be simple references to
   104594 **        columns of the sub-query.
   104595 **
   104596 **  (19)  The subquery does not use LIMIT or the outer query does not
   104597 **        have a WHERE clause.
   104598 **
   104599 **  (20)  If the sub-query is a compound select, then it must not use
   104600 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
   104601 **        somewhat by saying that the terms of the ORDER BY clause must
   104602 **        appear as unmodified result columns in the outer query.  But we
   104603 **        have other optimizations in mind to deal with that case.
   104604 **
   104605 **  (21)  The subquery does not use LIMIT or the outer query is not
   104606 **        DISTINCT.  (See ticket [752e1646fc]).
   104607 **
   104608 **  (22)  The subquery is not a recursive CTE.
   104609 **
   104610 **  (23)  The parent is not a recursive CTE, or the sub-query is not a
   104611 **        compound query. This restriction is because transforming the
   104612 **        parent to a compound query confuses the code that handles
   104613 **        recursive queries in multiSelect().
   104614 **
   104615 **
   104616 ** In this routine, the "p" parameter is a pointer to the outer query.
   104617 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
   104618 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
   104619 **
   104620 ** If flattening is not attempted, this routine is a no-op and returns 0.
   104621 ** If flattening is attempted this routine returns 1.
   104622 **
   104623 ** All of the expression analysis must occur on both the outer query and
   104624 ** the subquery before this routine runs.
   104625 */
   104626 static int flattenSubquery(
   104627   Parse *pParse,       /* Parsing context */
   104628   Select *p,           /* The parent or outer SELECT statement */
   104629   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
   104630   int isAgg,           /* True if outer SELECT uses aggregate functions */
   104631   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
   104632 ){
   104633   const char *zSavedAuthContext = pParse->zAuthContext;
   104634   Select *pParent;
   104635   Select *pSub;       /* The inner query or "subquery" */
   104636   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
   104637   SrcList *pSrc;      /* The FROM clause of the outer query */
   104638   SrcList *pSubSrc;   /* The FROM clause of the subquery */
   104639   ExprList *pList;    /* The result set of the outer query */
   104640   int iParent;        /* VDBE cursor number of the pSub result set temp table */
   104641   int i;              /* Loop counter */
   104642   Expr *pWhere;                    /* The WHERE clause */
   104643   struct SrcList_item *pSubitem;   /* The subquery */
   104644   sqlite3 *db = pParse->db;
   104645 
   104646   /* Check to see if flattening is permitted.  Return 0 if not.
   104647   */
   104648   assert( p!=0 );
   104649   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
   104650   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
   104651   pSrc = p->pSrc;
   104652   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
   104653   pSubitem = &pSrc->a[iFrom];
   104654   iParent = pSubitem->iCursor;
   104655   pSub = pSubitem->pSelect;
   104656   assert( pSub!=0 );
   104657   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
   104658   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
   104659   pSubSrc = pSub->pSrc;
   104660   assert( pSubSrc );
   104661   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
   104662   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
   104663   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
   104664   ** became arbitrary expressions, we were forced to add restrictions (13)
   104665   ** and (14). */
   104666   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
   104667   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
   104668   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
   104669     return 0;                                            /* Restriction (15) */
   104670   }
   104671   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
   104672   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
   104673   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
   104674      return 0;         /* Restrictions (8)(9) */
   104675   }
   104676   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
   104677      return 0;         /* Restriction (6)  */
   104678   }
   104679   if( p->pOrderBy && pSub->pOrderBy ){
   104680      return 0;                                           /* Restriction (11) */
   104681   }
   104682   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
   104683   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
   104684   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
   104685      return 0;         /* Restriction (21) */
   104686   }
   104687   if( pSub->selFlags & SF_Recursive ) return 0;          /* Restriction (22)  */
   104688   if( (p->selFlags & SF_Recursive) && pSub->pPrior ) return 0;       /* (23)  */
   104689 
   104690   /* OBSOLETE COMMENT 1:
   104691   ** Restriction 3:  If the subquery is a join, make sure the subquery is
   104692   ** not used as the right operand of an outer join.  Examples of why this
   104693   ** is not allowed:
   104694   **
   104695   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
   104696   **
   104697   ** If we flatten the above, we would get
   104698   **
   104699   **         (t1 LEFT OUTER JOIN t2) JOIN t3
   104700   **
   104701   ** which is not at all the same thing.
   104702   **
   104703   ** OBSOLETE COMMENT 2:
   104704   ** Restriction 12:  If the subquery is the right operand of a left outer
   104705   ** join, make sure the subquery has no WHERE clause.
   104706   ** An examples of why this is not allowed:
   104707   **
   104708   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
   104709   **
   104710   ** If we flatten the above, we would get
   104711   **
   104712   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
   104713   **
   104714   ** But the t2.x>0 test will always fail on a NULL row of t2, which
   104715   ** effectively converts the OUTER JOIN into an INNER JOIN.
   104716   **
   104717   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
   104718   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
   104719   ** is fraught with danger.  Best to avoid the whole thing.  If the
   104720   ** subquery is the right term of a LEFT JOIN, then do not flatten.
   104721   */
   104722   if( (pSubitem->jointype & JT_OUTER)!=0 ){
   104723     return 0;
   104724   }
   104725 
   104726   /* Restriction 17: If the sub-query is a compound SELECT, then it must
   104727   ** use only the UNION ALL operator. And none of the simple select queries
   104728   ** that make up the compound SELECT are allowed to be aggregate or distinct
   104729   ** queries.
   104730   */
   104731   if( pSub->pPrior ){
   104732     if( pSub->pOrderBy ){
   104733       return 0;  /* Restriction 20 */
   104734     }
   104735     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
   104736       return 0;
   104737     }
   104738     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
   104739       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   104740       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   104741       assert( pSub->pSrc!=0 );
   104742       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
   104743        || (pSub1->pPrior && pSub1->op!=TK_ALL)
   104744        || pSub1->pSrc->nSrc<1
   104745        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
   104746       ){
   104747         return 0;
   104748       }
   104749       testcase( pSub1->pSrc->nSrc>1 );
   104750     }
   104751 
   104752     /* Restriction 18. */
   104753     if( p->pOrderBy ){
   104754       int ii;
   104755       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
   104756         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
   104757       }
   104758     }
   104759   }
   104760 
   104761   /***** If we reach this point, flattening is permitted. *****/
   104762 
   104763   /* Authorize the subquery */
   104764   pParse->zAuthContext = pSubitem->zName;
   104765   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
   104766   testcase( i==SQLITE_DENY );
   104767   pParse->zAuthContext = zSavedAuthContext;
   104768 
   104769   /* If the sub-query is a compound SELECT statement, then (by restrictions
   104770   ** 17 and 18 above) it must be a UNION ALL and the parent query must
   104771   ** be of the form:
   104772   **
   104773   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
   104774   **
   104775   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
   104776   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
   104777   ** OFFSET clauses and joins them to the left-hand-side of the original
   104778   ** using UNION ALL operators. In this case N is the number of simple
   104779   ** select statements in the compound sub-query.
   104780   **
   104781   ** Example:
   104782   **
   104783   **     SELECT a+1 FROM (
   104784   **        SELECT x FROM tab
   104785   **        UNION ALL
   104786   **        SELECT y FROM tab
   104787   **        UNION ALL
   104788   **        SELECT abs(z*2) FROM tab2
   104789   **     ) WHERE a!=5 ORDER BY 1
   104790   **
   104791   ** Transformed into:
   104792   **
   104793   **     SELECT x+1 FROM tab WHERE x+1!=5
   104794   **     UNION ALL
   104795   **     SELECT y+1 FROM tab WHERE y+1!=5
   104796   **     UNION ALL
   104797   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
   104798   **     ORDER BY 1
   104799   **
   104800   ** We call this the "compound-subquery flattening".
   104801   */
   104802   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
   104803     Select *pNew;
   104804     ExprList *pOrderBy = p->pOrderBy;
   104805     Expr *pLimit = p->pLimit;
   104806     Expr *pOffset = p->pOffset;
   104807     Select *pPrior = p->pPrior;
   104808     p->pOrderBy = 0;
   104809     p->pSrc = 0;
   104810     p->pPrior = 0;
   104811     p->pLimit = 0;
   104812     p->pOffset = 0;
   104813     pNew = sqlite3SelectDup(db, p, 0);
   104814     p->pOffset = pOffset;
   104815     p->pLimit = pLimit;
   104816     p->pOrderBy = pOrderBy;
   104817     p->pSrc = pSrc;
   104818     p->op = TK_ALL;
   104819     if( pNew==0 ){
   104820       p->pPrior = pPrior;
   104821     }else{
   104822       pNew->pPrior = pPrior;
   104823       if( pPrior ) pPrior->pNext = pNew;
   104824       pNew->pNext = p;
   104825       p->pPrior = pNew;
   104826     }
   104827     if( db->mallocFailed ) return 1;
   104828   }
   104829 
   104830   /* Begin flattening the iFrom-th entry of the FROM clause
   104831   ** in the outer query.
   104832   */
   104833   pSub = pSub1 = pSubitem->pSelect;
   104834 
   104835   /* Delete the transient table structure associated with the
   104836   ** subquery
   104837   */
   104838   sqlite3DbFree(db, pSubitem->zDatabase);
   104839   sqlite3DbFree(db, pSubitem->zName);
   104840   sqlite3DbFree(db, pSubitem->zAlias);
   104841   pSubitem->zDatabase = 0;
   104842   pSubitem->zName = 0;
   104843   pSubitem->zAlias = 0;
   104844   pSubitem->pSelect = 0;
   104845 
   104846   /* Defer deleting the Table object associated with the
   104847   ** subquery until code generation is
   104848   ** complete, since there may still exist Expr.pTab entries that
   104849   ** refer to the subquery even after flattening.  Ticket #3346.
   104850   **
   104851   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
   104852   */
   104853   if( ALWAYS(pSubitem->pTab!=0) ){
   104854     Table *pTabToDel = pSubitem->pTab;
   104855     if( pTabToDel->nRef==1 ){
   104856       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   104857       pTabToDel->pNextZombie = pToplevel->pZombieTab;
   104858       pToplevel->pZombieTab = pTabToDel;
   104859     }else{
   104860       pTabToDel->nRef--;
   104861     }
   104862     pSubitem->pTab = 0;
   104863   }
   104864 
   104865   /* The following loop runs once for each term in a compound-subquery
   104866   ** flattening (as described above).  If we are doing a different kind
   104867   ** of flattening - a flattening other than a compound-subquery flattening -
   104868   ** then this loop only runs once.
   104869   **
   104870   ** This loop moves all of the FROM elements of the subquery into the
   104871   ** the FROM clause of the outer query.  Before doing this, remember
   104872   ** the cursor number for the original outer query FROM element in
   104873   ** iParent.  The iParent cursor will never be used.  Subsequent code
   104874   ** will scan expressions looking for iParent references and replace
   104875   ** those references with expressions that resolve to the subquery FROM
   104876   ** elements we are now copying in.
   104877   */
   104878   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
   104879     int nSubSrc;
   104880     u8 jointype = 0;
   104881     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
   104882     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
   104883     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
   104884 
   104885     if( pSrc ){
   104886       assert( pParent==p );  /* First time through the loop */
   104887       jointype = pSubitem->jointype;
   104888     }else{
   104889       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
   104890       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   104891       if( pSrc==0 ){
   104892         assert( db->mallocFailed );
   104893         break;
   104894       }
   104895     }
   104896 
   104897     /* The subquery uses a single slot of the FROM clause of the outer
   104898     ** query.  If the subquery has more than one element in its FROM clause,
   104899     ** then expand the outer query to make space for it to hold all elements
   104900     ** of the subquery.
   104901     **
   104902     ** Example:
   104903     **
   104904     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
   104905     **
   104906     ** The outer query has 3 slots in its FROM clause.  One slot of the
   104907     ** outer query (the middle slot) is used by the subquery.  The next
   104908     ** block of code will expand the out query to 4 slots.  The middle
   104909     ** slot is expanded to two slots in order to make space for the
   104910     ** two elements in the FROM clause of the subquery.
   104911     */
   104912     if( nSubSrc>1 ){
   104913       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
   104914       if( db->mallocFailed ){
   104915         break;
   104916       }
   104917     }
   104918 
   104919     /* Transfer the FROM clause terms from the subquery into the
   104920     ** outer query.
   104921     */
   104922     for(i=0; i<nSubSrc; i++){
   104923       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
   104924       pSrc->a[i+iFrom] = pSubSrc->a[i];
   104925       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
   104926     }
   104927     pSrc->a[iFrom].jointype = jointype;
   104928 
   104929     /* Now begin substituting subquery result set expressions for
   104930     ** references to the iParent in the outer query.
   104931     **
   104932     ** Example:
   104933     **
   104934     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
   104935     **   \                     \_____________ subquery __________/          /
   104936     **    \_____________________ outer query ______________________________/
   104937     **
   104938     ** We look at every expression in the outer query and every place we see
   104939     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
   104940     */
   104941     pList = pParent->pEList;
   104942     for(i=0; i<pList->nExpr; i++){
   104943       if( pList->a[i].zName==0 ){
   104944         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
   104945         sqlite3Dequote(zName);
   104946         pList->a[i].zName = zName;
   104947       }
   104948     }
   104949     substExprList(db, pParent->pEList, iParent, pSub->pEList);
   104950     if( isAgg ){
   104951       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
   104952       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   104953     }
   104954     if( pSub->pOrderBy ){
   104955       assert( pParent->pOrderBy==0 );
   104956       pParent->pOrderBy = pSub->pOrderBy;
   104957       pSub->pOrderBy = 0;
   104958     }else if( pParent->pOrderBy ){
   104959       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
   104960     }
   104961     if( pSub->pWhere ){
   104962       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
   104963     }else{
   104964       pWhere = 0;
   104965     }
   104966     if( subqueryIsAgg ){
   104967       assert( pParent->pHaving==0 );
   104968       pParent->pHaving = pParent->pWhere;
   104969       pParent->pWhere = pWhere;
   104970       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   104971       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
   104972                                   sqlite3ExprDup(db, pSub->pHaving, 0));
   104973       assert( pParent->pGroupBy==0 );
   104974       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
   104975     }else{
   104976       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
   104977       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
   104978     }
   104979 
   104980     /* The flattened query is distinct if either the inner or the
   104981     ** outer query is distinct.
   104982     */
   104983     pParent->selFlags |= pSub->selFlags & SF_Distinct;
   104984 
   104985     /*
   104986     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
   104987     **
   104988     ** One is tempted to try to add a and b to combine the limits.  But this
   104989     ** does not work if either limit is negative.
   104990     */
   104991     if( pSub->pLimit ){
   104992       pParent->pLimit = pSub->pLimit;
   104993       pSub->pLimit = 0;
   104994     }
   104995   }
   104996 
   104997   /* Finially, delete what is left of the subquery and return
   104998   ** success.
   104999   */
   105000   sqlite3SelectDelete(db, pSub1);
   105001 
   105002   return 1;
   105003 }
   105004 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   105005 
   105006 /*
   105007 ** Based on the contents of the AggInfo structure indicated by the first
   105008 ** argument, this function checks if the following are true:
   105009 **
   105010 **    * the query contains just a single aggregate function,
   105011 **    * the aggregate function is either min() or max(), and
   105012 **    * the argument to the aggregate function is a column value.
   105013 **
   105014 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
   105015 ** is returned as appropriate. Also, *ppMinMax is set to point to the
   105016 ** list of arguments passed to the aggregate before returning.
   105017 **
   105018 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
   105019 ** WHERE_ORDERBY_NORMAL is returned.
   105020 */
   105021 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
   105022   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
   105023 
   105024   *ppMinMax = 0;
   105025   if( pAggInfo->nFunc==1 ){
   105026     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
   105027     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
   105028 
   105029     assert( pExpr->op==TK_AGG_FUNCTION );
   105030     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
   105031       const char *zFunc = pExpr->u.zToken;
   105032       if( sqlite3StrICmp(zFunc, "min")==0 ){
   105033         eRet = WHERE_ORDERBY_MIN;
   105034         *ppMinMax = pEList;
   105035       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
   105036         eRet = WHERE_ORDERBY_MAX;
   105037         *ppMinMax = pEList;
   105038       }
   105039     }
   105040   }
   105041 
   105042   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
   105043   return eRet;
   105044 }
   105045 
   105046 /*
   105047 ** The select statement passed as the first argument is an aggregate query.
   105048 ** The second argment is the associated aggregate-info object. This
   105049 ** function tests if the SELECT is of the form:
   105050 **
   105051 **   SELECT count(*) FROM <tbl>
   105052 **
   105053 ** where table is a database table, not a sub-select or view. If the query
   105054 ** does match this pattern, then a pointer to the Table object representing
   105055 ** <tbl> is returned. Otherwise, 0 is returned.
   105056 */
   105057 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
   105058   Table *pTab;
   105059   Expr *pExpr;
   105060 
   105061   assert( !p->pGroupBy );
   105062 
   105063   if( p->pWhere || p->pEList->nExpr!=1
   105064    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
   105065   ){
   105066     return 0;
   105067   }
   105068   pTab = p->pSrc->a[0].pTab;
   105069   pExpr = p->pEList->a[0].pExpr;
   105070   assert( pTab && !pTab->pSelect && pExpr );
   105071 
   105072   if( IsVirtual(pTab) ) return 0;
   105073   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   105074   if( NEVER(pAggInfo->nFunc==0) ) return 0;
   105075   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
   105076   if( pExpr->flags&EP_Distinct ) return 0;
   105077 
   105078   return pTab;
   105079 }
   105080 
   105081 /*
   105082 ** If the source-list item passed as an argument was augmented with an
   105083 ** INDEXED BY clause, then try to locate the specified index. If there
   105084 ** was such a clause and the named index cannot be found, return
   105085 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
   105086 ** pFrom->pIndex and return SQLITE_OK.
   105087 */
   105088 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
   105089   if( pFrom->pTab && pFrom->zIndex ){
   105090     Table *pTab = pFrom->pTab;
   105091     char *zIndex = pFrom->zIndex;
   105092     Index *pIdx;
   105093     for(pIdx=pTab->pIndex;
   105094         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
   105095         pIdx=pIdx->pNext
   105096     );
   105097     if( !pIdx ){
   105098       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
   105099       pParse->checkSchema = 1;
   105100       return SQLITE_ERROR;
   105101     }
   105102     pFrom->pIndex = pIdx;
   105103   }
   105104   return SQLITE_OK;
   105105 }
   105106 /*
   105107 ** Detect compound SELECT statements that use an ORDER BY clause with
   105108 ** an alternative collating sequence.
   105109 **
   105110 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
   105111 **
   105112 ** These are rewritten as a subquery:
   105113 **
   105114 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
   105115 **     ORDER BY ... COLLATE ...
   105116 **
   105117 ** This transformation is necessary because the multiSelectOrderBy() routine
   105118 ** above that generates the code for a compound SELECT with an ORDER BY clause
   105119 ** uses a merge algorithm that requires the same collating sequence on the
   105120 ** result columns as on the ORDER BY clause.  See ticket
   105121 ** http://www.sqlite.org/src/info/6709574d2a
   105122 **
   105123 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
   105124 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
   105125 ** there are COLLATE terms in the ORDER BY.
   105126 */
   105127 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
   105128   int i;
   105129   Select *pNew;
   105130   Select *pX;
   105131   sqlite3 *db;
   105132   struct ExprList_item *a;
   105133   SrcList *pNewSrc;
   105134   Parse *pParse;
   105135   Token dummy;
   105136 
   105137   if( p->pPrior==0 ) return WRC_Continue;
   105138   if( p->pOrderBy==0 ) return WRC_Continue;
   105139   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
   105140   if( pX==0 ) return WRC_Continue;
   105141   a = p->pOrderBy->a;
   105142   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
   105143     if( a[i].pExpr->flags & EP_Collate ) break;
   105144   }
   105145   if( i<0 ) return WRC_Continue;
   105146 
   105147   /* If we reach this point, that means the transformation is required. */
   105148 
   105149   pParse = pWalker->pParse;
   105150   db = pParse->db;
   105151   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   105152   if( pNew==0 ) return WRC_Abort;
   105153   memset(&dummy, 0, sizeof(dummy));
   105154   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
   105155   if( pNewSrc==0 ) return WRC_Abort;
   105156   *pNew = *p;
   105157   p->pSrc = pNewSrc;
   105158   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
   105159   p->op = TK_SELECT;
   105160   p->pWhere = 0;
   105161   pNew->pGroupBy = 0;
   105162   pNew->pHaving = 0;
   105163   pNew->pOrderBy = 0;
   105164   p->pPrior = 0;
   105165   p->pNext = 0;
   105166   p->selFlags &= ~SF_Compound;
   105167   assert( pNew->pPrior!=0 );
   105168   pNew->pPrior->pNext = pNew;
   105169   pNew->pLimit = 0;
   105170   pNew->pOffset = 0;
   105171   return WRC_Continue;
   105172 }
   105173 
   105174 #ifndef SQLITE_OMIT_CTE
   105175 /*
   105176 ** Argument pWith (which may be NULL) points to a linked list of nested
   105177 ** WITH contexts, from inner to outermost. If the table identified by
   105178 ** FROM clause element pItem is really a common-table-expression (CTE)
   105179 ** then return a pointer to the CTE definition for that table. Otherwise
   105180 ** return NULL.
   105181 **
   105182 ** If a non-NULL value is returned, set *ppContext to point to the With
   105183 ** object that the returned CTE belongs to.
   105184 */
   105185 static struct Cte *searchWith(
   105186   With *pWith,                    /* Current outermost WITH clause */
   105187   struct SrcList_item *pItem,     /* FROM clause element to resolve */
   105188   With **ppContext                /* OUT: WITH clause return value belongs to */
   105189 ){
   105190   const char *zName;
   105191   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
   105192     With *p;
   105193     for(p=pWith; p; p=p->pOuter){
   105194       int i;
   105195       for(i=0; i<p->nCte; i++){
   105196         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
   105197           *ppContext = p;
   105198           return &p->a[i];
   105199         }
   105200       }
   105201     }
   105202   }
   105203   return 0;
   105204 }
   105205 
   105206 /* The code generator maintains a stack of active WITH clauses
   105207 ** with the inner-most WITH clause being at the top of the stack.
   105208 **
   105209 ** This routine pushes the WITH clause passed as the second argument
   105210 ** onto the top of the stack. If argument bFree is true, then this
   105211 ** WITH clause will never be popped from the stack. In this case it
   105212 ** should be freed along with the Parse object. In other cases, when
   105213 ** bFree==0, the With object will be freed along with the SELECT
   105214 ** statement with which it is associated.
   105215 */
   105216 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
   105217   assert( bFree==0 || pParse->pWith==0 );
   105218   if( pWith ){
   105219     pWith->pOuter = pParse->pWith;
   105220     pParse->pWith = pWith;
   105221     pParse->bFreeWith = bFree;
   105222   }
   105223 }
   105224 
   105225 /*
   105226 ** This function checks if argument pFrom refers to a CTE declared by
   105227 ** a WITH clause on the stack currently maintained by the parser. And,
   105228 ** if currently processing a CTE expression, if it is a recursive
   105229 ** reference to the current CTE.
   105230 **
   105231 ** If pFrom falls into either of the two categories above, pFrom->pTab
   105232 ** and other fields are populated accordingly. The caller should check
   105233 ** (pFrom->pTab!=0) to determine whether or not a successful match
   105234 ** was found.
   105235 **
   105236 ** Whether or not a match is found, SQLITE_OK is returned if no error
   105237 ** occurs. If an error does occur, an error message is stored in the
   105238 ** parser and some error code other than SQLITE_OK returned.
   105239 */
   105240 static int withExpand(
   105241   Walker *pWalker,
   105242   struct SrcList_item *pFrom
   105243 ){
   105244   Parse *pParse = pWalker->pParse;
   105245   sqlite3 *db = pParse->db;
   105246   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
   105247   With *pWith;                    /* WITH clause that pCte belongs to */
   105248 
   105249   assert( pFrom->pTab==0 );
   105250 
   105251   pCte = searchWith(pParse->pWith, pFrom, &pWith);
   105252   if( pCte ){
   105253     Table *pTab;
   105254     ExprList *pEList;
   105255     Select *pSel;
   105256     Select *pLeft;                /* Left-most SELECT statement */
   105257     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
   105258     With *pSavedWith;             /* Initial value of pParse->pWith */
   105259 
   105260     /* If pCte->zErr is non-NULL at this point, then this is an illegal
   105261     ** recursive reference to CTE pCte. Leave an error in pParse and return
   105262     ** early. If pCte->zErr is NULL, then this is not a recursive reference.
   105263     ** In this case, proceed.  */
   105264     if( pCte->zErr ){
   105265       sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
   105266       return SQLITE_ERROR;
   105267     }
   105268 
   105269     assert( pFrom->pTab==0 );
   105270     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   105271     if( pTab==0 ) return WRC_Abort;
   105272     pTab->nRef = 1;
   105273     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
   105274     pTab->iPKey = -1;
   105275     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   105276     pTab->tabFlags |= TF_Ephemeral;
   105277     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
   105278     if( db->mallocFailed ) return SQLITE_NOMEM;
   105279     assert( pFrom->pSelect );
   105280 
   105281     /* Check if this is a recursive CTE. */
   105282     pSel = pFrom->pSelect;
   105283     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
   105284     if( bMayRecursive ){
   105285       int i;
   105286       SrcList *pSrc = pFrom->pSelect->pSrc;
   105287       for(i=0; i<pSrc->nSrc; i++){
   105288         struct SrcList_item *pItem = &pSrc->a[i];
   105289         if( pItem->zDatabase==0
   105290          && pItem->zName!=0
   105291          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
   105292           ){
   105293           pItem->pTab = pTab;
   105294           pItem->isRecursive = 1;
   105295           pTab->nRef++;
   105296           pSel->selFlags |= SF_Recursive;
   105297         }
   105298       }
   105299     }
   105300 
   105301     /* Only one recursive reference is permitted. */
   105302     if( pTab->nRef>2 ){
   105303       sqlite3ErrorMsg(
   105304           pParse, "multiple references to recursive table: %s", pCte->zName
   105305       );
   105306       return SQLITE_ERROR;
   105307     }
   105308     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
   105309 
   105310     pCte->zErr = "circular reference: %s";
   105311     pSavedWith = pParse->pWith;
   105312     pParse->pWith = pWith;
   105313     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
   105314 
   105315     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
   105316     pEList = pLeft->pEList;
   105317     if( pCte->pCols ){
   105318       if( pEList->nExpr!=pCte->pCols->nExpr ){
   105319         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
   105320             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
   105321         );
   105322         pParse->pWith = pSavedWith;
   105323         return SQLITE_ERROR;
   105324       }
   105325       pEList = pCte->pCols;
   105326     }
   105327 
   105328     selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
   105329     if( bMayRecursive ){
   105330       if( pSel->selFlags & SF_Recursive ){
   105331         pCte->zErr = "multiple recursive references: %s";
   105332       }else{
   105333         pCte->zErr = "recursive reference in a subquery: %s";
   105334       }
   105335       sqlite3WalkSelect(pWalker, pSel);
   105336     }
   105337     pCte->zErr = 0;
   105338     pParse->pWith = pSavedWith;
   105339   }
   105340 
   105341   return SQLITE_OK;
   105342 }
   105343 #endif
   105344 
   105345 #ifndef SQLITE_OMIT_CTE
   105346 /*
   105347 ** If the SELECT passed as the second argument has an associated WITH
   105348 ** clause, pop it from the stack stored as part of the Parse object.
   105349 **
   105350 ** This function is used as the xSelectCallback2() callback by
   105351 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
   105352 ** names and other FROM clause elements.
   105353 */
   105354 static void selectPopWith(Walker *pWalker, Select *p){
   105355   Parse *pParse = pWalker->pParse;
   105356   With *pWith = findRightmost(p)->pWith;
   105357   if( pWith!=0 ){
   105358     assert( pParse->pWith==pWith );
   105359     pParse->pWith = pWith->pOuter;
   105360   }
   105361 }
   105362 #else
   105363 #define selectPopWith 0
   105364 #endif
   105365 
   105366 /*
   105367 ** This routine is a Walker callback for "expanding" a SELECT statement.
   105368 ** "Expanding" means to do the following:
   105369 **
   105370 **    (1)  Make sure VDBE cursor numbers have been assigned to every
   105371 **         element of the FROM clause.
   105372 **
   105373 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
   105374 **         defines FROM clause.  When views appear in the FROM clause,
   105375 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
   105376 **         that implements the view.  A copy is made of the view's SELECT
   105377 **         statement so that we can freely modify or delete that statement
   105378 **         without worrying about messing up the presistent representation
   105379 **         of the view.
   105380 **
   105381 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
   105382 **         on joins and the ON and USING clause of joins.
   105383 **
   105384 **    (4)  Scan the list of columns in the result set (pEList) looking
   105385 **         for instances of the "*" operator or the TABLE.* operator.
   105386 **         If found, expand each "*" to be every column in every table
   105387 **         and TABLE.* to be every column in TABLE.
   105388 **
   105389 */
   105390 static int selectExpander(Walker *pWalker, Select *p){
   105391   Parse *pParse = pWalker->pParse;
   105392   int i, j, k;
   105393   SrcList *pTabList;
   105394   ExprList *pEList;
   105395   struct SrcList_item *pFrom;
   105396   sqlite3 *db = pParse->db;
   105397   Expr *pE, *pRight, *pExpr;
   105398   u16 selFlags = p->selFlags;
   105399 
   105400   p->selFlags |= SF_Expanded;
   105401   if( db->mallocFailed  ){
   105402     return WRC_Abort;
   105403   }
   105404   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
   105405     return WRC_Prune;
   105406   }
   105407   pTabList = p->pSrc;
   105408   pEList = p->pEList;
   105409   sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
   105410 
   105411   /* Make sure cursor numbers have been assigned to all entries in
   105412   ** the FROM clause of the SELECT statement.
   105413   */
   105414   sqlite3SrcListAssignCursors(pParse, pTabList);
   105415 
   105416   /* Look up every table named in the FROM clause of the select.  If
   105417   ** an entry of the FROM clause is a subquery instead of a table or view,
   105418   ** then create a transient table structure to describe the subquery.
   105419   */
   105420   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   105421     Table *pTab;
   105422     assert( pFrom->isRecursive==0 || pFrom->pTab );
   105423     if( pFrom->isRecursive ) continue;
   105424     if( pFrom->pTab!=0 ){
   105425       /* This statement has already been prepared.  There is no need
   105426       ** to go further. */
   105427       assert( i==0 );
   105428 #ifndef SQLITE_OMIT_CTE
   105429       selectPopWith(pWalker, p);
   105430 #endif
   105431       return WRC_Prune;
   105432     }
   105433 #ifndef SQLITE_OMIT_CTE
   105434     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
   105435     if( pFrom->pTab ) {} else
   105436 #endif
   105437     if( pFrom->zName==0 ){
   105438 #ifndef SQLITE_OMIT_SUBQUERY
   105439       Select *pSel = pFrom->pSelect;
   105440       /* A sub-query in the FROM clause of a SELECT */
   105441       assert( pSel!=0 );
   105442       assert( pFrom->pTab==0 );
   105443       sqlite3WalkSelect(pWalker, pSel);
   105444       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   105445       if( pTab==0 ) return WRC_Abort;
   105446       pTab->nRef = 1;
   105447       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
   105448       while( pSel->pPrior ){ pSel = pSel->pPrior; }
   105449       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
   105450       pTab->iPKey = -1;
   105451       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   105452       pTab->tabFlags |= TF_Ephemeral;
   105453 #endif
   105454     }else{
   105455       /* An ordinary table or view name in the FROM clause */
   105456       assert( pFrom->pTab==0 );
   105457       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
   105458       if( pTab==0 ) return WRC_Abort;
   105459       if( pTab->nRef==0xffff ){
   105460         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
   105461            pTab->zName);
   105462         pFrom->pTab = 0;
   105463         return WRC_Abort;
   105464       }
   105465       pTab->nRef++;
   105466 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
   105467       if( pTab->pSelect || IsVirtual(pTab) ){
   105468         /* We reach here if the named table is a really a view */
   105469         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
   105470         assert( pFrom->pSelect==0 );
   105471         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
   105472         sqlite3WalkSelect(pWalker, pFrom->pSelect);
   105473       }
   105474 #endif
   105475     }
   105476 
   105477     /* Locate the index named by the INDEXED BY clause, if any. */
   105478     if( sqlite3IndexedByLookup(pParse, pFrom) ){
   105479       return WRC_Abort;
   105480     }
   105481   }
   105482 
   105483   /* Process NATURAL keywords, and ON and USING clauses of joins.
   105484   */
   105485   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
   105486     return WRC_Abort;
   105487   }
   105488 
   105489   /* For every "*" that occurs in the column list, insert the names of
   105490   ** all columns in all tables.  And for every TABLE.* insert the names
   105491   ** of all columns in TABLE.  The parser inserted a special expression
   105492   ** with the TK_ALL operator for each "*" that it found in the column list.
   105493   ** The following code just has to locate the TK_ALL expressions and expand
   105494   ** each one to the list of all columns in all tables.
   105495   **
   105496   ** The first loop just checks to see if there are any "*" operators
   105497   ** that need expanding.
   105498   */
   105499   for(k=0; k<pEList->nExpr; k++){
   105500     pE = pEList->a[k].pExpr;
   105501     if( pE->op==TK_ALL ) break;
   105502     assert( pE->op!=TK_DOT || pE->pRight!=0 );
   105503     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
   105504     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
   105505   }
   105506   if( k<pEList->nExpr ){
   105507     /*
   105508     ** If we get here it means the result set contains one or more "*"
   105509     ** operators that need to be expanded.  Loop through each expression
   105510     ** in the result set and expand them one by one.
   105511     */
   105512     struct ExprList_item *a = pEList->a;
   105513     ExprList *pNew = 0;
   105514     int flags = pParse->db->flags;
   105515     int longNames = (flags & SQLITE_FullColNames)!=0
   105516                       && (flags & SQLITE_ShortColNames)==0;
   105517 
   105518     /* When processing FROM-clause subqueries, it is always the case
   105519     ** that full_column_names=OFF and short_column_names=ON.  The
   105520     ** sqlite3ResultSetOfSelect() routine makes it so. */
   105521     assert( (p->selFlags & SF_NestedFrom)==0
   105522           || ((flags & SQLITE_FullColNames)==0 &&
   105523               (flags & SQLITE_ShortColNames)!=0) );
   105524 
   105525     for(k=0; k<pEList->nExpr; k++){
   105526       pE = a[k].pExpr;
   105527       pRight = pE->pRight;
   105528       assert( pE->op!=TK_DOT || pRight!=0 );
   105529       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
   105530         /* This particular expression does not need to be expanded.
   105531         */
   105532         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
   105533         if( pNew ){
   105534           pNew->a[pNew->nExpr-1].zName = a[k].zName;
   105535           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
   105536           a[k].zName = 0;
   105537           a[k].zSpan = 0;
   105538         }
   105539         a[k].pExpr = 0;
   105540       }else{
   105541         /* This expression is a "*" or a "TABLE.*" and needs to be
   105542         ** expanded. */
   105543         int tableSeen = 0;      /* Set to 1 when TABLE matches */
   105544         char *zTName = 0;       /* text of name of TABLE */
   105545         if( pE->op==TK_DOT ){
   105546           assert( pE->pLeft!=0 );
   105547           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
   105548           zTName = pE->pLeft->u.zToken;
   105549         }
   105550         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   105551           Table *pTab = pFrom->pTab;
   105552           Select *pSub = pFrom->pSelect;
   105553           char *zTabName = pFrom->zAlias;
   105554           const char *zSchemaName = 0;
   105555           int iDb;
   105556           if( zTabName==0 ){
   105557             zTabName = pTab->zName;
   105558           }
   105559           if( db->mallocFailed ) break;
   105560           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
   105561             pSub = 0;
   105562             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
   105563               continue;
   105564             }
   105565             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   105566             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
   105567           }
   105568           for(j=0; j<pTab->nCol; j++){
   105569             char *zName = pTab->aCol[j].zName;
   105570             char *zColname;  /* The computed column name */
   105571             char *zToFree;   /* Malloced string that needs to be freed */
   105572             Token sColname;  /* Computed column name as a token */
   105573 
   105574             assert( zName );
   105575             if( zTName && pSub
   105576              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
   105577             ){
   105578               continue;
   105579             }
   105580 
   105581             /* If a column is marked as 'hidden' (currently only possible
   105582             ** for virtual tables), do not include it in the expanded
   105583             ** result-set list.
   105584             */
   105585             if( IsHiddenColumn(&pTab->aCol[j]) ){
   105586               assert(IsVirtual(pTab));
   105587               continue;
   105588             }
   105589             tableSeen = 1;
   105590 
   105591             if( i>0 && zTName==0 ){
   105592               if( (pFrom->jointype & JT_NATURAL)!=0
   105593                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
   105594               ){
   105595                 /* In a NATURAL join, omit the join columns from the
   105596                 ** table to the right of the join */
   105597                 continue;
   105598               }
   105599               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
   105600                 /* In a join with a USING clause, omit columns in the
   105601                 ** using clause from the table on the right. */
   105602                 continue;
   105603               }
   105604             }
   105605             pRight = sqlite3Expr(db, TK_ID, zName);
   105606             zColname = zName;
   105607             zToFree = 0;
   105608             if( longNames || pTabList->nSrc>1 ){
   105609               Expr *pLeft;
   105610               pLeft = sqlite3Expr(db, TK_ID, zTabName);
   105611               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   105612               if( zSchemaName ){
   105613                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
   105614                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
   105615               }
   105616               if( longNames ){
   105617                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
   105618                 zToFree = zColname;
   105619               }
   105620             }else{
   105621               pExpr = pRight;
   105622             }
   105623             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
   105624             sColname.z = zColname;
   105625             sColname.n = sqlite3Strlen30(zColname);
   105626             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
   105627             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
   105628               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
   105629               if( pSub ){
   105630                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
   105631                 testcase( pX->zSpan==0 );
   105632               }else{
   105633                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
   105634                                            zSchemaName, zTabName, zColname);
   105635                 testcase( pX->zSpan==0 );
   105636               }
   105637               pX->bSpanIsTab = 1;
   105638             }
   105639             sqlite3DbFree(db, zToFree);
   105640           }
   105641         }
   105642         if( !tableSeen ){
   105643           if( zTName ){
   105644             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
   105645           }else{
   105646             sqlite3ErrorMsg(pParse, "no tables specified");
   105647           }
   105648         }
   105649       }
   105650     }
   105651     sqlite3ExprListDelete(db, pEList);
   105652     p->pEList = pNew;
   105653   }
   105654 #if SQLITE_MAX_COLUMN
   105655   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   105656     sqlite3ErrorMsg(pParse, "too many columns in result set");
   105657   }
   105658 #endif
   105659   return WRC_Continue;
   105660 }
   105661 
   105662 /*
   105663 ** No-op routine for the parse-tree walker.
   105664 **
   105665 ** When this routine is the Walker.xExprCallback then expression trees
   105666 ** are walked without any actions being taken at each node.  Presumably,
   105667 ** when this routine is used for Walker.xExprCallback then
   105668 ** Walker.xSelectCallback is set to do something useful for every
   105669 ** subquery in the parser tree.
   105670 */
   105671 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
   105672   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   105673   return WRC_Continue;
   105674 }
   105675 
   105676 /*
   105677 ** This routine "expands" a SELECT statement and all of its subqueries.
   105678 ** For additional information on what it means to "expand" a SELECT
   105679 ** statement, see the comment on the selectExpand worker callback above.
   105680 **
   105681 ** Expanding a SELECT statement is the first step in processing a
   105682 ** SELECT statement.  The SELECT statement must be expanded before
   105683 ** name resolution is performed.
   105684 **
   105685 ** If anything goes wrong, an error message is written into pParse.
   105686 ** The calling function can detect the problem by looking at pParse->nErr
   105687 ** and/or pParse->db->mallocFailed.
   105688 */
   105689 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
   105690   Walker w;
   105691   memset(&w, 0, sizeof(w));
   105692   w.xExprCallback = exprWalkNoop;
   105693   w.pParse = pParse;
   105694   if( pParse->hasCompound ){
   105695     w.xSelectCallback = convertCompoundSelectToSubquery;
   105696     sqlite3WalkSelect(&w, pSelect);
   105697   }
   105698   w.xSelectCallback = selectExpander;
   105699   w.xSelectCallback2 = selectPopWith;
   105700   sqlite3WalkSelect(&w, pSelect);
   105701 }
   105702 
   105703 
   105704 #ifndef SQLITE_OMIT_SUBQUERY
   105705 /*
   105706 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
   105707 ** interface.
   105708 **
   105709 ** For each FROM-clause subquery, add Column.zType and Column.zColl
   105710 ** information to the Table structure that represents the result set
   105711 ** of that subquery.
   105712 **
   105713 ** The Table structure that represents the result set was constructed
   105714 ** by selectExpander() but the type and collation information was omitted
   105715 ** at that point because identifiers had not yet been resolved.  This
   105716 ** routine is called after identifier resolution.
   105717 */
   105718 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
   105719   Parse *pParse;
   105720   int i;
   105721   SrcList *pTabList;
   105722   struct SrcList_item *pFrom;
   105723 
   105724   assert( p->selFlags & SF_Resolved );
   105725   if( (p->selFlags & SF_HasTypeInfo)==0 ){
   105726     p->selFlags |= SF_HasTypeInfo;
   105727     pParse = pWalker->pParse;
   105728     pTabList = p->pSrc;
   105729     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   105730       Table *pTab = pFrom->pTab;
   105731       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
   105732         /* A sub-query in the FROM clause of a SELECT */
   105733         Select *pSel = pFrom->pSelect;
   105734         if( pSel ){
   105735           while( pSel->pPrior ) pSel = pSel->pPrior;
   105736           selectAddColumnTypeAndCollation(pParse, pTab, pSel);
   105737         }
   105738       }
   105739     }
   105740   }
   105741 }
   105742 #endif
   105743 
   105744 
   105745 /*
   105746 ** This routine adds datatype and collating sequence information to
   105747 ** the Table structures of all FROM-clause subqueries in a
   105748 ** SELECT statement.
   105749 **
   105750 ** Use this routine after name resolution.
   105751 */
   105752 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
   105753 #ifndef SQLITE_OMIT_SUBQUERY
   105754   Walker w;
   105755   memset(&w, 0, sizeof(w));
   105756   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
   105757   w.xExprCallback = exprWalkNoop;
   105758   w.pParse = pParse;
   105759   sqlite3WalkSelect(&w, pSelect);
   105760 #endif
   105761 }
   105762 
   105763 
   105764 /*
   105765 ** This routine sets up a SELECT statement for processing.  The
   105766 ** following is accomplished:
   105767 **
   105768 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
   105769 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
   105770 **     *  ON and USING clauses are shifted into WHERE statements
   105771 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
   105772 **     *  Identifiers in expression are matched to tables.
   105773 **
   105774 ** This routine acts recursively on all subqueries within the SELECT.
   105775 */
   105776 SQLITE_PRIVATE void sqlite3SelectPrep(
   105777   Parse *pParse,         /* The parser context */
   105778   Select *p,             /* The SELECT statement being coded. */
   105779   NameContext *pOuterNC  /* Name context for container */
   105780 ){
   105781   sqlite3 *db;
   105782   if( NEVER(p==0) ) return;
   105783   db = pParse->db;
   105784   if( db->mallocFailed ) return;
   105785   if( p->selFlags & SF_HasTypeInfo ) return;
   105786   sqlite3SelectExpand(pParse, p);
   105787   if( pParse->nErr || db->mallocFailed ) return;
   105788   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
   105789   if( pParse->nErr || db->mallocFailed ) return;
   105790   sqlite3SelectAddTypeInfo(pParse, p);
   105791 }
   105792 
   105793 /*
   105794 ** Reset the aggregate accumulator.
   105795 **
   105796 ** The aggregate accumulator is a set of memory cells that hold
   105797 ** intermediate results while calculating an aggregate.  This
   105798 ** routine generates code that stores NULLs in all of those memory
   105799 ** cells.
   105800 */
   105801 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   105802   Vdbe *v = pParse->pVdbe;
   105803   int i;
   105804   struct AggInfo_func *pFunc;
   105805   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
   105806   if( nReg==0 ) return;
   105807 #ifdef SQLITE_DEBUG
   105808   /* Verify that all AggInfo registers are within the range specified by
   105809   ** AggInfo.mnReg..AggInfo.mxReg */
   105810   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
   105811   for(i=0; i<pAggInfo->nColumn; i++){
   105812     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
   105813          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
   105814   }
   105815   for(i=0; i<pAggInfo->nFunc; i++){
   105816     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
   105817          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
   105818   }
   105819 #endif
   105820   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
   105821   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
   105822     if( pFunc->iDistinct>=0 ){
   105823       Expr *pE = pFunc->pExpr;
   105824       assert( !ExprHasProperty(pE, EP_xIsSelect) );
   105825       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
   105826         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
   105827            "argument");
   105828         pFunc->iDistinct = -1;
   105829       }else{
   105830         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
   105831         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
   105832                           (char*)pKeyInfo, P4_KEYINFO);
   105833       }
   105834     }
   105835   }
   105836 }
   105837 
   105838 /*
   105839 ** Invoke the OP_AggFinalize opcode for every aggregate function
   105840 ** in the AggInfo structure.
   105841 */
   105842 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   105843   Vdbe *v = pParse->pVdbe;
   105844   int i;
   105845   struct AggInfo_func *pF;
   105846   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   105847     ExprList *pList = pF->pExpr->x.pList;
   105848     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   105849     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
   105850                       (void*)pF->pFunc, P4_FUNCDEF);
   105851   }
   105852 }
   105853 
   105854 /*
   105855 ** Update the accumulator memory cells for an aggregate based on
   105856 ** the current cursor position.
   105857 */
   105858 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
   105859   Vdbe *v = pParse->pVdbe;
   105860   int i;
   105861   int regHit = 0;
   105862   int addrHitTest = 0;
   105863   struct AggInfo_func *pF;
   105864   struct AggInfo_col *pC;
   105865 
   105866   pAggInfo->directMode = 1;
   105867   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   105868     int nArg;
   105869     int addrNext = 0;
   105870     int regAgg;
   105871     ExprList *pList = pF->pExpr->x.pList;
   105872     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   105873     if( pList ){
   105874       nArg = pList->nExpr;
   105875       regAgg = sqlite3GetTempRange(pParse, nArg);
   105876       sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
   105877     }else{
   105878       nArg = 0;
   105879       regAgg = 0;
   105880     }
   105881     if( pF->iDistinct>=0 ){
   105882       addrNext = sqlite3VdbeMakeLabel(v);
   105883       assert( nArg==1 );
   105884       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
   105885     }
   105886     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   105887       CollSeq *pColl = 0;
   105888       struct ExprList_item *pItem;
   105889       int j;
   105890       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
   105891       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
   105892         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   105893       }
   105894       if( !pColl ){
   105895         pColl = pParse->db->pDfltColl;
   105896       }
   105897       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
   105898       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
   105899     }
   105900     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
   105901                       (void*)pF->pFunc, P4_FUNCDEF);
   105902     sqlite3VdbeChangeP5(v, (u8)nArg);
   105903     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
   105904     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
   105905     if( addrNext ){
   105906       sqlite3VdbeResolveLabel(v, addrNext);
   105907       sqlite3ExprCacheClear(pParse);
   105908     }
   105909   }
   105910 
   105911   /* Before populating the accumulator registers, clear the column cache.
   105912   ** Otherwise, if any of the required column values are already present
   105913   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
   105914   ** to pC->iMem. But by the time the value is used, the original register
   105915   ** may have been used, invalidating the underlying buffer holding the
   105916   ** text or blob value. See ticket [883034dcb5].
   105917   **
   105918   ** Another solution would be to change the OP_SCopy used to copy cached
   105919   ** values to an OP_Copy.
   105920   */
   105921   if( regHit ){
   105922     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
   105923   }
   105924   sqlite3ExprCacheClear(pParse);
   105925   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
   105926     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
   105927   }
   105928   pAggInfo->directMode = 0;
   105929   sqlite3ExprCacheClear(pParse);
   105930   if( addrHitTest ){
   105931     sqlite3VdbeJumpHere(v, addrHitTest);
   105932   }
   105933 }
   105934 
   105935 /*
   105936 ** Add a single OP_Explain instruction to the VDBE to explain a simple
   105937 ** count(*) query ("SELECT count(*) FROM pTab").
   105938 */
   105939 #ifndef SQLITE_OMIT_EXPLAIN
   105940 static void explainSimpleCount(
   105941   Parse *pParse,                  /* Parse context */
   105942   Table *pTab,                    /* Table being queried */
   105943   Index *pIdx                     /* Index used to optimize scan, or NULL */
   105944 ){
   105945   if( pParse->explain==2 ){
   105946     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
   105947     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
   105948         pTab->zName,
   105949         bCover ? " USING COVERING INDEX " : "",
   105950         bCover ? pIdx->zName : ""
   105951     );
   105952     sqlite3VdbeAddOp4(
   105953         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
   105954     );
   105955   }
   105956 }
   105957 #else
   105958 # define explainSimpleCount(a,b,c)
   105959 #endif
   105960 
   105961 /*
   105962 ** Generate code for the SELECT statement given in the p argument.
   105963 **
   105964 ** The results are returned according to the SelectDest structure.
   105965 ** See comments in sqliteInt.h for further information.
   105966 **
   105967 ** This routine returns the number of errors.  If any errors are
   105968 ** encountered, then an appropriate error message is left in
   105969 ** pParse->zErrMsg.
   105970 **
   105971 ** This routine does NOT free the Select structure passed in.  The
   105972 ** calling function needs to do that.
   105973 */
   105974 SQLITE_PRIVATE int sqlite3Select(
   105975   Parse *pParse,         /* The parser context */
   105976   Select *p,             /* The SELECT statement being coded. */
   105977   SelectDest *pDest      /* What to do with the query results */
   105978 ){
   105979   int i, j;              /* Loop counters */
   105980   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
   105981   Vdbe *v;               /* The virtual machine under construction */
   105982   int isAgg;             /* True for select lists like "count(*)" */
   105983   ExprList *pEList;      /* List of columns to extract. */
   105984   SrcList *pTabList;     /* List of tables to select from */
   105985   Expr *pWhere;          /* The WHERE clause.  May be NULL */
   105986   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   105987   Expr *pHaving;         /* The HAVING clause.  May be NULL */
   105988   int rc = 1;            /* Value to return from this function */
   105989   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
   105990   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
   105991   AggInfo sAggInfo;      /* Information used by aggregate queries */
   105992   int iEnd;              /* Address of the end of the query */
   105993   sqlite3 *db;           /* The database connection */
   105994 
   105995 #ifndef SQLITE_OMIT_EXPLAIN
   105996   int iRestoreSelectId = pParse->iSelectId;
   105997   pParse->iSelectId = pParse->iNextSelectId++;
   105998 #endif
   105999 
   106000   db = pParse->db;
   106001   if( p==0 || db->mallocFailed || pParse->nErr ){
   106002     return 1;
   106003   }
   106004   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
   106005   memset(&sAggInfo, 0, sizeof(sAggInfo));
   106006 
   106007   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
   106008   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
   106009   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
   106010   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
   106011   if( IgnorableOrderby(pDest) ){
   106012     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
   106013            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
   106014            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
   106015            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
   106016     /* If ORDER BY makes no difference in the output then neither does
   106017     ** DISTINCT so it can be removed too. */
   106018     sqlite3ExprListDelete(db, p->pOrderBy);
   106019     p->pOrderBy = 0;
   106020     p->selFlags &= ~SF_Distinct;
   106021   }
   106022   sqlite3SelectPrep(pParse, p, 0);
   106023   memset(&sSort, 0, sizeof(sSort));
   106024   sSort.pOrderBy = p->pOrderBy;
   106025   pTabList = p->pSrc;
   106026   pEList = p->pEList;
   106027   if( pParse->nErr || db->mallocFailed ){
   106028     goto select_end;
   106029   }
   106030   isAgg = (p->selFlags & SF_Aggregate)!=0;
   106031   assert( pEList!=0 );
   106032 
   106033   /* Begin generating code.
   106034   */
   106035   v = sqlite3GetVdbe(pParse);
   106036   if( v==0 ) goto select_end;
   106037 
   106038   /* If writing to memory or generating a set
   106039   ** only a single column may be output.
   106040   */
   106041 #ifndef SQLITE_OMIT_SUBQUERY
   106042   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
   106043     goto select_end;
   106044   }
   106045 #endif
   106046 
   106047   /* Generate code for all sub-queries in the FROM clause
   106048   */
   106049 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   106050   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
   106051     struct SrcList_item *pItem = &pTabList->a[i];
   106052     SelectDest dest;
   106053     Select *pSub = pItem->pSelect;
   106054     int isAggSub;
   106055 
   106056     if( pSub==0 ) continue;
   106057 
   106058     /* Sometimes the code for a subquery will be generated more than
   106059     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
   106060     ** for example.  In that case, do not regenerate the code to manifest
   106061     ** a view or the co-routine to implement a view.  The first instance
   106062     ** is sufficient, though the subroutine to manifest the view does need
   106063     ** to be invoked again. */
   106064     if( pItem->addrFillSub ){
   106065       if( pItem->viaCoroutine==0 ){
   106066         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
   106067       }
   106068       continue;
   106069     }
   106070 
   106071     /* Increment Parse.nHeight by the height of the largest expression
   106072     ** tree referred to by this, the parent select. The child select
   106073     ** may contain expression trees of at most
   106074     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
   106075     ** more conservative than necessary, but much easier than enforcing
   106076     ** an exact limit.
   106077     */
   106078     pParse->nHeight += sqlite3SelectExprHeight(p);
   106079 
   106080     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
   106081     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
   106082       /* This subquery can be absorbed into its parent. */
   106083       if( isAggSub ){
   106084         isAgg = 1;
   106085         p->selFlags |= SF_Aggregate;
   106086       }
   106087       i = -1;
   106088     }else if( pTabList->nSrc==1
   106089            && OptimizationEnabled(db, SQLITE_SubqCoroutine)
   106090     ){
   106091       /* Implement a co-routine that will return a single row of the result
   106092       ** set on each invocation.
   106093       */
   106094       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
   106095       pItem->regReturn = ++pParse->nMem;
   106096       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
   106097       VdbeComment((v, "%s", pItem->pTab->zName));
   106098       pItem->addrFillSub = addrTop;
   106099       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
   106100       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   106101       sqlite3Select(pParse, pSub, &dest);
   106102       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
   106103       pItem->viaCoroutine = 1;
   106104       pItem->regResult = dest.iSdst;
   106105       sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
   106106       sqlite3VdbeJumpHere(v, addrTop-1);
   106107       sqlite3ClearTempRegCache(pParse);
   106108     }else{
   106109       /* Generate a subroutine that will fill an ephemeral table with
   106110       ** the content of this subquery.  pItem->addrFillSub will point
   106111       ** to the address of the generated subroutine.  pItem->regReturn
   106112       ** is a register allocated to hold the subroutine return address
   106113       */
   106114       int topAddr;
   106115       int onceAddr = 0;
   106116       int retAddr;
   106117       assert( pItem->addrFillSub==0 );
   106118       pItem->regReturn = ++pParse->nMem;
   106119       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
   106120       pItem->addrFillSub = topAddr+1;
   106121       if( pItem->isCorrelated==0 ){
   106122         /* If the subquery is not correlated and if we are not inside of
   106123         ** a trigger, then we only need to compute the value of the subquery
   106124         ** once. */
   106125         onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   106126         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
   106127       }else{
   106128         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
   106129       }
   106130       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
   106131       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   106132       sqlite3Select(pParse, pSub, &dest);
   106133       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
   106134       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
   106135       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
   106136       VdbeComment((v, "end %s", pItem->pTab->zName));
   106137       sqlite3VdbeChangeP1(v, topAddr, retAddr);
   106138       sqlite3ClearTempRegCache(pParse);
   106139     }
   106140     if( /*pParse->nErr ||*/ db->mallocFailed ){
   106141       goto select_end;
   106142     }
   106143     pParse->nHeight -= sqlite3SelectExprHeight(p);
   106144     pTabList = p->pSrc;
   106145     if( !IgnorableOrderby(pDest) ){
   106146       sSort.pOrderBy = p->pOrderBy;
   106147     }
   106148   }
   106149   pEList = p->pEList;
   106150 #endif
   106151   pWhere = p->pWhere;
   106152   pGroupBy = p->pGroupBy;
   106153   pHaving = p->pHaving;
   106154   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
   106155 
   106156 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   106157   /* If there is are a sequence of queries, do the earlier ones first.
   106158   */
   106159   if( p->pPrior ){
   106160     rc = multiSelect(pParse, p, pDest);
   106161     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   106162     return rc;
   106163   }
   106164 #endif
   106165 
   106166   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
   106167   ** if the select-list is the same as the ORDER BY list, then this query
   106168   ** can be rewritten as a GROUP BY. In other words, this:
   106169   **
   106170   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
   106171   **
   106172   ** is transformed to:
   106173   **
   106174   **     SELECT xyz FROM ... GROUP BY xyz
   106175   **
   106176   ** The second form is preferred as a single index (or temp-table) may be
   106177   ** used for both the ORDER BY and DISTINCT processing. As originally
   106178   ** written the query must use a temp-table for at least one of the ORDER
   106179   ** BY and DISTINCT, and an index or separate temp-table for the other.
   106180   */
   106181   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
   106182    && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
   106183   ){
   106184     p->selFlags &= ~SF_Distinct;
   106185     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
   106186     pGroupBy = p->pGroupBy;
   106187     sSort.pOrderBy = 0;
   106188     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
   106189     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
   106190     ** original setting of the SF_Distinct flag, not the current setting */
   106191     assert( sDistinct.isTnct );
   106192   }
   106193 
   106194   /* If there is an ORDER BY clause, then this sorting
   106195   ** index might end up being unused if the data can be
   106196   ** extracted in pre-sorted order.  If that is the case, then the
   106197   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
   106198   ** we figure out that the sorting index is not needed.  The addrSortIndex
   106199   ** variable is used to facilitate that change.
   106200   */
   106201   if( sSort.pOrderBy ){
   106202     KeyInfo *pKeyInfo;
   106203     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0);
   106204     sSort.iECursor = pParse->nTab++;
   106205     sSort.addrSortIndex =
   106206       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   106207                            sSort.iECursor, sSort.pOrderBy->nExpr+2, 0,
   106208                            (char*)pKeyInfo, P4_KEYINFO);
   106209   }else{
   106210     sSort.addrSortIndex = -1;
   106211   }
   106212 
   106213   /* If the output is destined for a temporary table, open that table.
   106214   */
   106215   if( pDest->eDest==SRT_EphemTab ){
   106216     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
   106217   }
   106218 
   106219   /* Set the limiter.
   106220   */
   106221   iEnd = sqlite3VdbeMakeLabel(v);
   106222   p->nSelectRow = LARGEST_INT64;
   106223   computeLimitRegisters(pParse, p, iEnd);
   106224   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
   106225     sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
   106226     sSort.sortFlags |= SORTFLAG_UseSorter;
   106227   }
   106228 
   106229   /* Open a virtual index to use for the distinct set.
   106230   */
   106231   if( p->selFlags & SF_Distinct ){
   106232     sDistinct.tabTnct = pParse->nTab++;
   106233     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   106234                                 sDistinct.tabTnct, 0, 0,
   106235                                 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
   106236                                 P4_KEYINFO);
   106237     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   106238     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
   106239   }else{
   106240     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
   106241   }
   106242 
   106243   if( !isAgg && pGroupBy==0 ){
   106244     /* No aggregate functions and no GROUP BY clause */
   106245     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
   106246 
   106247     /* Begin the database scan. */
   106248     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
   106249                                p->pEList, wctrlFlags, 0);
   106250     if( pWInfo==0 ) goto select_end;
   106251     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
   106252       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
   106253     }
   106254     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
   106255       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
   106256     }
   106257     if( sSort.pOrderBy ){
   106258       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
   106259       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
   106260         sSort.pOrderBy = 0;
   106261       }
   106262     }
   106263 
   106264     /* If sorting index that was created by a prior OP_OpenEphemeral
   106265     ** instruction ended up not being needed, then change the OP_OpenEphemeral
   106266     ** into an OP_Noop.
   106267     */
   106268     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
   106269       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
   106270     }
   106271 
   106272     /* Use the standard inner loop. */
   106273     selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
   106274                     sqlite3WhereContinueLabel(pWInfo),
   106275                     sqlite3WhereBreakLabel(pWInfo));
   106276 
   106277     /* End the database scan loop.
   106278     */
   106279     sqlite3WhereEnd(pWInfo);
   106280   }else{
   106281     /* This case when there exist aggregate functions or a GROUP BY clause
   106282     ** or both */
   106283     NameContext sNC;    /* Name context for processing aggregate information */
   106284     int iAMem;          /* First Mem address for storing current GROUP BY */
   106285     int iBMem;          /* First Mem address for previous GROUP BY */
   106286     int iUseFlag;       /* Mem address holding flag indicating that at least
   106287                         ** one row of the input to the aggregator has been
   106288                         ** processed */
   106289     int iAbortFlag;     /* Mem address which causes query abort if positive */
   106290     int groupBySort;    /* Rows come from source in GROUP BY order */
   106291     int addrEnd;        /* End of processing for this SELECT */
   106292     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
   106293     int sortOut = 0;    /* Output register from the sorter */
   106294     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
   106295 
   106296     /* Remove any and all aliases between the result set and the
   106297     ** GROUP BY clause.
   106298     */
   106299     if( pGroupBy ){
   106300       int k;                        /* Loop counter */
   106301       struct ExprList_item *pItem;  /* For looping over expression in a list */
   106302 
   106303       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
   106304         pItem->u.x.iAlias = 0;
   106305       }
   106306       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
   106307         pItem->u.x.iAlias = 0;
   106308       }
   106309       if( p->nSelectRow>100 ) p->nSelectRow = 100;
   106310     }else{
   106311       p->nSelectRow = 1;
   106312     }
   106313 
   106314 
   106315     /* If there is both a GROUP BY and an ORDER BY clause and they are
   106316     ** identical, then it may be possible to disable the ORDER BY clause
   106317     ** on the grounds that the GROUP BY will cause elements to come out
   106318     ** in the correct order. It also may not - the GROUP BY may use a
   106319     ** database index that causes rows to be grouped together as required
   106320     ** but not actually sorted. Either way, record the fact that the
   106321     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
   106322     ** variable.  */
   106323     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
   106324       orderByGrp = 1;
   106325     }
   106326 
   106327     /* Create a label to jump to when we want to abort the query */
   106328     addrEnd = sqlite3VdbeMakeLabel(v);
   106329 
   106330     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
   106331     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
   106332     ** SELECT statement.
   106333     */
   106334     memset(&sNC, 0, sizeof(sNC));
   106335     sNC.pParse = pParse;
   106336     sNC.pSrcList = pTabList;
   106337     sNC.pAggInfo = &sAggInfo;
   106338     sAggInfo.mnReg = pParse->nMem+1;
   106339     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
   106340     sAggInfo.pGroupBy = pGroupBy;
   106341     sqlite3ExprAnalyzeAggList(&sNC, pEList);
   106342     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
   106343     if( pHaving ){
   106344       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
   106345     }
   106346     sAggInfo.nAccumulator = sAggInfo.nColumn;
   106347     for(i=0; i<sAggInfo.nFunc; i++){
   106348       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
   106349       sNC.ncFlags |= NC_InAggFunc;
   106350       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
   106351       sNC.ncFlags &= ~NC_InAggFunc;
   106352     }
   106353     sAggInfo.mxReg = pParse->nMem;
   106354     if( db->mallocFailed ) goto select_end;
   106355 
   106356     /* Processing for aggregates with GROUP BY is very different and
   106357     ** much more complex than aggregates without a GROUP BY.
   106358     */
   106359     if( pGroupBy ){
   106360       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
   106361       int j1;             /* A-vs-B comparision jump */
   106362       int addrOutputRow;  /* Start of subroutine that outputs a result row */
   106363       int regOutputRow;   /* Return address register for output subroutine */
   106364       int addrSetAbort;   /* Set the abort flag and return */
   106365       int addrTopOfLoop;  /* Top of the input loop */
   106366       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
   106367       int addrReset;      /* Subroutine for resetting the accumulator */
   106368       int regReset;       /* Return address register for reset subroutine */
   106369 
   106370       /* If there is a GROUP BY clause we might need a sorting index to
   106371       ** implement it.  Allocate that sorting index now.  If it turns out
   106372       ** that we do not need it after all, the OP_SorterOpen instruction
   106373       ** will be converted into a Noop.
   106374       */
   106375       sAggInfo.sortingIdx = pParse->nTab++;
   106376       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0);
   106377       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
   106378           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
   106379           0, (char*)pKeyInfo, P4_KEYINFO);
   106380 
   106381       /* Initialize memory locations used by GROUP BY aggregate processing
   106382       */
   106383       iUseFlag = ++pParse->nMem;
   106384       iAbortFlag = ++pParse->nMem;
   106385       regOutputRow = ++pParse->nMem;
   106386       addrOutputRow = sqlite3VdbeMakeLabel(v);
   106387       regReset = ++pParse->nMem;
   106388       addrReset = sqlite3VdbeMakeLabel(v);
   106389       iAMem = pParse->nMem + 1;
   106390       pParse->nMem += pGroupBy->nExpr;
   106391       iBMem = pParse->nMem + 1;
   106392       pParse->nMem += pGroupBy->nExpr;
   106393       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
   106394       VdbeComment((v, "clear abort flag"));
   106395       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
   106396       VdbeComment((v, "indicate accumulator empty"));
   106397       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
   106398 
   106399       /* Begin a loop that will extract all source rows in GROUP BY order.
   106400       ** This might involve two separate loops with an OP_Sort in between, or
   106401       ** it might be a single loop that uses an index to extract information
   106402       ** in the right order to begin with.
   106403       */
   106404       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   106405       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
   106406           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
   106407       );
   106408       if( pWInfo==0 ) goto select_end;
   106409       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
   106410         /* The optimizer is able to deliver rows in group by order so
   106411         ** we do not have to sort.  The OP_OpenEphemeral table will be
   106412         ** cancelled later because we still need to use the pKeyInfo
   106413         */
   106414         groupBySort = 0;
   106415       }else{
   106416         /* Rows are coming out in undetermined order.  We have to push
   106417         ** each row into a sorting index, terminate the first loop,
   106418         ** then loop over the sorting index in order to get the output
   106419         ** in sorted order
   106420         */
   106421         int regBase;
   106422         int regRecord;
   106423         int nCol;
   106424         int nGroupBy;
   106425 
   106426         explainTempTable(pParse,
   106427             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
   106428                     "DISTINCT" : "GROUP BY");
   106429 
   106430         groupBySort = 1;
   106431         nGroupBy = pGroupBy->nExpr;
   106432         nCol = nGroupBy + 1;
   106433         j = nGroupBy+1;
   106434         for(i=0; i<sAggInfo.nColumn; i++){
   106435           if( sAggInfo.aCol[i].iSorterColumn>=j ){
   106436             nCol++;
   106437             j++;
   106438           }
   106439         }
   106440         regBase = sqlite3GetTempRange(pParse, nCol);
   106441         sqlite3ExprCacheClear(pParse);
   106442         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
   106443         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
   106444         j = nGroupBy+1;
   106445         for(i=0; i<sAggInfo.nColumn; i++){
   106446           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
   106447           if( pCol->iSorterColumn>=j ){
   106448             int r1 = j + regBase;
   106449             int r2;
   106450 
   106451             r2 = sqlite3ExprCodeGetColumn(pParse,
   106452                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
   106453             if( r1!=r2 ){
   106454               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
   106455             }
   106456             j++;
   106457           }
   106458         }
   106459         regRecord = sqlite3GetTempReg(pParse);
   106460         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
   106461         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
   106462         sqlite3ReleaseTempReg(pParse, regRecord);
   106463         sqlite3ReleaseTempRange(pParse, regBase, nCol);
   106464         sqlite3WhereEnd(pWInfo);
   106465         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
   106466         sortOut = sqlite3GetTempReg(pParse);
   106467         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
   106468         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
   106469         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
   106470         sAggInfo.useSortingIdx = 1;
   106471         sqlite3ExprCacheClear(pParse);
   106472 
   106473       }
   106474 
   106475       /* If the index or temporary table used by the GROUP BY sort
   106476       ** will naturally deliver rows in the order required by the ORDER BY
   106477       ** clause, cancel the ephemeral table open coded earlier.
   106478       **
   106479       ** This is an optimization - the correct answer should result regardless.
   106480       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
   106481       ** disable this optimization for testing purposes.  */
   106482       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
   106483        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
   106484       ){
   106485         sSort.pOrderBy = 0;
   106486         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
   106487       }
   106488 
   106489       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
   106490       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
   106491       ** Then compare the current GROUP BY terms against the GROUP BY terms
   106492       ** from the previous row currently stored in a0, a1, a2...
   106493       */
   106494       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
   106495       sqlite3ExprCacheClear(pParse);
   106496       if( groupBySort ){
   106497         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
   106498       }
   106499       for(j=0; j<pGroupBy->nExpr; j++){
   106500         if( groupBySort ){
   106501           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
   106502           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   106503         }else{
   106504           sAggInfo.directMode = 1;
   106505           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
   106506         }
   106507       }
   106508       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
   106509                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
   106510       j1 = sqlite3VdbeCurrentAddr(v);
   106511       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
   106512 
   106513       /* Generate code that runs whenever the GROUP BY changes.
   106514       ** Changes in the GROUP BY are detected by the previous code
   106515       ** block.  If there were no changes, this block is skipped.
   106516       **
   106517       ** This code copies current group by terms in b0,b1,b2,...
   106518       ** over to a0,a1,a2.  It then calls the output subroutine
   106519       ** and resets the aggregate accumulator registers in preparation
   106520       ** for the next GROUP BY batch.
   106521       */
   106522       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
   106523       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   106524       VdbeComment((v, "output one row"));
   106525       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
   106526       VdbeComment((v, "check abort flag"));
   106527       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   106528       VdbeComment((v, "reset accumulator"));
   106529 
   106530       /* Update the aggregate accumulators based on the content of
   106531       ** the current row
   106532       */
   106533       sqlite3VdbeJumpHere(v, j1);
   106534       updateAccumulator(pParse, &sAggInfo);
   106535       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
   106536       VdbeComment((v, "indicate data in accumulator"));
   106537 
   106538       /* End of the loop
   106539       */
   106540       if( groupBySort ){
   106541         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
   106542         VdbeCoverage(v);
   106543       }else{
   106544         sqlite3WhereEnd(pWInfo);
   106545         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
   106546       }
   106547 
   106548       /* Output the final row of result
   106549       */
   106550       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   106551       VdbeComment((v, "output final row"));
   106552 
   106553       /* Jump over the subroutines
   106554       */
   106555       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
   106556 
   106557       /* Generate a subroutine that outputs a single row of the result
   106558       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
   106559       ** is less than or equal to zero, the subroutine is a no-op.  If
   106560       ** the processing calls for the query to abort, this subroutine
   106561       ** increments the iAbortFlag memory location before returning in
   106562       ** order to signal the caller to abort.
   106563       */
   106564       addrSetAbort = sqlite3VdbeCurrentAddr(v);
   106565       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
   106566       VdbeComment((v, "set abort flag"));
   106567       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   106568       sqlite3VdbeResolveLabel(v, addrOutputRow);
   106569       addrOutputRow = sqlite3VdbeCurrentAddr(v);
   106570       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
   106571       VdbeComment((v, "Groupby result generator entry point"));
   106572       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   106573       finalizeAggFunctions(pParse, &sAggInfo);
   106574       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
   106575       selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
   106576                       &sDistinct, pDest,
   106577                       addrOutputRow+1, addrSetAbort);
   106578       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   106579       VdbeComment((v, "end groupby result generator"));
   106580 
   106581       /* Generate a subroutine that will reset the group-by accumulator
   106582       */
   106583       sqlite3VdbeResolveLabel(v, addrReset);
   106584       resetAccumulator(pParse, &sAggInfo);
   106585       sqlite3VdbeAddOp1(v, OP_Return, regReset);
   106586 
   106587     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
   106588     else {
   106589       ExprList *pDel = 0;
   106590 #ifndef SQLITE_OMIT_BTREECOUNT
   106591       Table *pTab;
   106592       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
   106593         /* If isSimpleCount() returns a pointer to a Table structure, then
   106594         ** the SQL statement is of the form:
   106595         **
   106596         **   SELECT count(*) FROM <tbl>
   106597         **
   106598         ** where the Table structure returned represents table <tbl>.
   106599         **
   106600         ** This statement is so common that it is optimized specially. The
   106601         ** OP_Count instruction is executed either on the intkey table that
   106602         ** contains the data for table <tbl> or on one of its indexes. It
   106603         ** is better to execute the op on an index, as indexes are almost
   106604         ** always spread across less pages than their corresponding tables.
   106605         */
   106606         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   106607         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
   106608         Index *pIdx;                         /* Iterator variable */
   106609         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
   106610         Index *pBest = 0;                    /* Best index found so far */
   106611         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
   106612 
   106613         sqlite3CodeVerifySchema(pParse, iDb);
   106614         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   106615 
   106616         /* Search for the index that has the lowest scan cost.
   106617         **
   106618         ** (2011-04-15) Do not do a full scan of an unordered index.
   106619         **
   106620         ** (2013-10-03) Do not count the entries in a partial index.
   106621         **
   106622         ** In practice the KeyInfo structure will not be used. It is only
   106623         ** passed to keep OP_OpenRead happy.
   106624         */
   106625         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
   106626         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   106627           if( pIdx->bUnordered==0
   106628            && pIdx->szIdxRow<pTab->szTabRow
   106629            && pIdx->pPartIdxWhere==0
   106630            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
   106631           ){
   106632             pBest = pIdx;
   106633           }
   106634         }
   106635         if( pBest ){
   106636           iRoot = pBest->tnum;
   106637           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
   106638         }
   106639 
   106640         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
   106641         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
   106642         if( pKeyInfo ){
   106643           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
   106644         }
   106645         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
   106646         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
   106647         explainSimpleCount(pParse, pTab, pBest);
   106648       }else
   106649 #endif /* SQLITE_OMIT_BTREECOUNT */
   106650       {
   106651         /* Check if the query is of one of the following forms:
   106652         **
   106653         **   SELECT min(x) FROM ...
   106654         **   SELECT max(x) FROM ...
   106655         **
   106656         ** If it is, then ask the code in where.c to attempt to sort results
   106657         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
   106658         ** If where.c is able to produce results sorted in this order, then
   106659         ** add vdbe code to break out of the processing loop after the
   106660         ** first iteration (since the first iteration of the loop is
   106661         ** guaranteed to operate on the row with the minimum or maximum
   106662         ** value of x, the only row required).
   106663         **
   106664         ** A special flag must be passed to sqlite3WhereBegin() to slightly
   106665         ** modify behavior as follows:
   106666         **
   106667         **   + If the query is a "SELECT min(x)", then the loop coded by
   106668         **     where.c should not iterate over any values with a NULL value
   106669         **     for x.
   106670         **
   106671         **   + The optimizer code in where.c (the thing that decides which
   106672         **     index or indices to use) should place a different priority on
   106673         **     satisfying the 'ORDER BY' clause than it does in other cases.
   106674         **     Refer to code and comments in where.c for details.
   106675         */
   106676         ExprList *pMinMax = 0;
   106677         u8 flag = WHERE_ORDERBY_NORMAL;
   106678 
   106679         assert( p->pGroupBy==0 );
   106680         assert( flag==0 );
   106681         if( p->pHaving==0 ){
   106682           flag = minMaxQuery(&sAggInfo, &pMinMax);
   106683         }
   106684         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
   106685 
   106686         if( flag ){
   106687           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
   106688           pDel = pMinMax;
   106689           if( pMinMax && !db->mallocFailed ){
   106690             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
   106691             pMinMax->a[0].pExpr->op = TK_COLUMN;
   106692           }
   106693         }
   106694 
   106695         /* This case runs if the aggregate has no GROUP BY clause.  The
   106696         ** processing is much simpler since there is only a single row
   106697         ** of output.
   106698         */
   106699         resetAccumulator(pParse, &sAggInfo);
   106700         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
   106701         if( pWInfo==0 ){
   106702           sqlite3ExprListDelete(db, pDel);
   106703           goto select_end;
   106704         }
   106705         updateAccumulator(pParse, &sAggInfo);
   106706         assert( pMinMax==0 || pMinMax->nExpr==1 );
   106707         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
   106708           sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
   106709           VdbeComment((v, "%s() by index",
   106710                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
   106711         }
   106712         sqlite3WhereEnd(pWInfo);
   106713         finalizeAggFunctions(pParse, &sAggInfo);
   106714       }
   106715 
   106716       sSort.pOrderBy = 0;
   106717       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
   106718       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
   106719                       pDest, addrEnd, addrEnd);
   106720       sqlite3ExprListDelete(db, pDel);
   106721     }
   106722     sqlite3VdbeResolveLabel(v, addrEnd);
   106723 
   106724   } /* endif aggregate query */
   106725 
   106726   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
   106727     explainTempTable(pParse, "DISTINCT");
   106728   }
   106729 
   106730   /* If there is an ORDER BY clause, then we need to sort the results
   106731   ** and send them to the callback one by one.
   106732   */
   106733   if( sSort.pOrderBy ){
   106734     explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
   106735     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
   106736   }
   106737 
   106738   /* Jump here to skip this query
   106739   */
   106740   sqlite3VdbeResolveLabel(v, iEnd);
   106741 
   106742   /* The SELECT was successfully coded.   Set the return code to 0
   106743   ** to indicate no errors.
   106744   */
   106745   rc = 0;
   106746 
   106747   /* Control jumps to here if an error is encountered above, or upon
   106748   ** successful coding of the SELECT.
   106749   */
   106750 select_end:
   106751   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   106752 
   106753   /* Identify column names if results of the SELECT are to be output.
   106754   */
   106755   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
   106756     generateColumnNames(pParse, pTabList, pEList);
   106757   }
   106758 
   106759   sqlite3DbFree(db, sAggInfo.aCol);
   106760   sqlite3DbFree(db, sAggInfo.aFunc);
   106761   return rc;
   106762 }
   106763 
   106764 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   106765 /*
   106766 ** Generate a human-readable description of a the Select object.
   106767 */
   106768 static void explainOneSelect(Vdbe *pVdbe, Select *p){
   106769   sqlite3ExplainPrintf(pVdbe, "SELECT ");
   106770   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   106771     if( p->selFlags & SF_Distinct ){
   106772       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
   106773     }
   106774     if( p->selFlags & SF_Aggregate ){
   106775       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
   106776     }
   106777     sqlite3ExplainNL(pVdbe);
   106778     sqlite3ExplainPrintf(pVdbe, "   ");
   106779   }
   106780   sqlite3ExplainExprList(pVdbe, p->pEList);
   106781   sqlite3ExplainNL(pVdbe);
   106782   if( p->pSrc && p->pSrc->nSrc ){
   106783     int i;
   106784     sqlite3ExplainPrintf(pVdbe, "FROM ");
   106785     sqlite3ExplainPush(pVdbe);
   106786     for(i=0; i<p->pSrc->nSrc; i++){
   106787       struct SrcList_item *pItem = &p->pSrc->a[i];
   106788       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
   106789       if( pItem->pSelect ){
   106790         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
   106791         if( pItem->pTab ){
   106792           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
   106793         }
   106794       }else if( pItem->zName ){
   106795         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
   106796       }
   106797       if( pItem->zAlias ){
   106798         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
   106799       }
   106800       if( pItem->jointype & JT_LEFT ){
   106801         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
   106802       }
   106803       sqlite3ExplainNL(pVdbe);
   106804     }
   106805     sqlite3ExplainPop(pVdbe);
   106806   }
   106807   if( p->pWhere ){
   106808     sqlite3ExplainPrintf(pVdbe, "WHERE ");
   106809     sqlite3ExplainExpr(pVdbe, p->pWhere);
   106810     sqlite3ExplainNL(pVdbe);
   106811   }
   106812   if( p->pGroupBy ){
   106813     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
   106814     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
   106815     sqlite3ExplainNL(pVdbe);
   106816   }
   106817   if( p->pHaving ){
   106818     sqlite3ExplainPrintf(pVdbe, "HAVING ");
   106819     sqlite3ExplainExpr(pVdbe, p->pHaving);
   106820     sqlite3ExplainNL(pVdbe);
   106821   }
   106822   if( p->pOrderBy ){
   106823     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
   106824     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
   106825     sqlite3ExplainNL(pVdbe);
   106826   }
   106827   if( p->pLimit ){
   106828     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
   106829     sqlite3ExplainExpr(pVdbe, p->pLimit);
   106830     sqlite3ExplainNL(pVdbe);
   106831   }
   106832   if( p->pOffset ){
   106833     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
   106834     sqlite3ExplainExpr(pVdbe, p->pOffset);
   106835     sqlite3ExplainNL(pVdbe);
   106836   }
   106837 }
   106838 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
   106839   if( p==0 ){
   106840     sqlite3ExplainPrintf(pVdbe, "(null-select)");
   106841     return;
   106842   }
   106843   sqlite3ExplainPush(pVdbe);
   106844   while( p ){
   106845     explainOneSelect(pVdbe, p);
   106846     p = p->pNext;
   106847     if( p==0 ) break;
   106848     sqlite3ExplainNL(pVdbe);
   106849     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
   106850   }
   106851   sqlite3ExplainPrintf(pVdbe, "END");
   106852   sqlite3ExplainPop(pVdbe);
   106853 }
   106854 
   106855 /* End of the structure debug printing code
   106856 *****************************************************************************/
   106857 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
   106858 
   106859 /************** End of select.c **********************************************/
   106860 /************** Begin file table.c *******************************************/
   106861 /*
   106862 ** 2001 September 15
   106863 **
   106864 ** The author disclaims copyright to this source code.  In place of
   106865 ** a legal notice, here is a blessing:
   106866 **
   106867 **    May you do good and not evil.
   106868 **    May you find forgiveness for yourself and forgive others.
   106869 **    May you share freely, never taking more than you give.
   106870 **
   106871 *************************************************************************
   106872 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
   106873 ** interface routines.  These are just wrappers around the main
   106874 ** interface routine of sqlite3_exec().
   106875 **
   106876 ** These routines are in a separate files so that they will not be linked
   106877 ** if they are not used.
   106878 */
   106879 /* #include <stdlib.h> */
   106880 /* #include <string.h> */
   106881 
   106882 #ifndef SQLITE_OMIT_GET_TABLE
   106883 
   106884 /*
   106885 ** This structure is used to pass data from sqlite3_get_table() through
   106886 ** to the callback function is uses to build the result.
   106887 */
   106888 typedef struct TabResult {
   106889   char **azResult;   /* Accumulated output */
   106890   char *zErrMsg;     /* Error message text, if an error occurs */
   106891   int nAlloc;        /* Slots allocated for azResult[] */
   106892   int nRow;          /* Number of rows in the result */
   106893   int nColumn;       /* Number of columns in the result */
   106894   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
   106895   int rc;            /* Return code from sqlite3_exec() */
   106896 } TabResult;
   106897 
   106898 /*
   106899 ** This routine is called once for each row in the result table.  Its job
   106900 ** is to fill in the TabResult structure appropriately, allocating new
   106901 ** memory as necessary.
   106902 */
   106903 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
   106904   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
   106905   int need;                         /* Slots needed in p->azResult[] */
   106906   int i;                            /* Loop counter */
   106907   char *z;                          /* A single column of result */
   106908 
   106909   /* Make sure there is enough space in p->azResult to hold everything
   106910   ** we need to remember from this invocation of the callback.
   106911   */
   106912   if( p->nRow==0 && argv!=0 ){
   106913     need = nCol*2;
   106914   }else{
   106915     need = nCol;
   106916   }
   106917   if( p->nData + need > p->nAlloc ){
   106918     char **azNew;
   106919     p->nAlloc = p->nAlloc*2 + need;
   106920     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
   106921     if( azNew==0 ) goto malloc_failed;
   106922     p->azResult = azNew;
   106923   }
   106924 
   106925   /* If this is the first row, then generate an extra row containing
   106926   ** the names of all columns.
   106927   */
   106928   if( p->nRow==0 ){
   106929     p->nColumn = nCol;
   106930     for(i=0; i<nCol; i++){
   106931       z = sqlite3_mprintf("%s", colv[i]);
   106932       if( z==0 ) goto malloc_failed;
   106933       p->azResult[p->nData++] = z;
   106934     }
   106935   }else if( p->nColumn!=nCol ){
   106936     sqlite3_free(p->zErrMsg);
   106937     p->zErrMsg = sqlite3_mprintf(
   106938        "sqlite3_get_table() called with two or more incompatible queries"
   106939     );
   106940     p->rc = SQLITE_ERROR;
   106941     return 1;
   106942   }
   106943 
   106944   /* Copy over the row data
   106945   */
   106946   if( argv!=0 ){
   106947     for(i=0; i<nCol; i++){
   106948       if( argv[i]==0 ){
   106949         z = 0;
   106950       }else{
   106951         int n = sqlite3Strlen30(argv[i])+1;
   106952         z = sqlite3_malloc( n );
   106953         if( z==0 ) goto malloc_failed;
   106954         memcpy(z, argv[i], n);
   106955       }
   106956       p->azResult[p->nData++] = z;
   106957     }
   106958     p->nRow++;
   106959   }
   106960   return 0;
   106961 
   106962 malloc_failed:
   106963   p->rc = SQLITE_NOMEM;
   106964   return 1;
   106965 }
   106966 
   106967 /*
   106968 ** Query the database.  But instead of invoking a callback for each row,
   106969 ** malloc() for space to hold the result and return the entire results
   106970 ** at the conclusion of the call.
   106971 **
   106972 ** The result that is written to ***pazResult is held in memory obtained
   106973 ** from malloc().  But the caller cannot free this memory directly.
   106974 ** Instead, the entire table should be passed to sqlite3_free_table() when
   106975 ** the calling procedure is finished using it.
   106976 */
   106977 SQLITE_API int sqlite3_get_table(
   106978   sqlite3 *db,                /* The database on which the SQL executes */
   106979   const char *zSql,           /* The SQL to be executed */
   106980   char ***pazResult,          /* Write the result table here */
   106981   int *pnRow,                 /* Write the number of rows in the result here */
   106982   int *pnColumn,              /* Write the number of columns of result here */
   106983   char **pzErrMsg             /* Write error messages here */
   106984 ){
   106985   int rc;
   106986   TabResult res;
   106987 
   106988   *pazResult = 0;
   106989   if( pnColumn ) *pnColumn = 0;
   106990   if( pnRow ) *pnRow = 0;
   106991   if( pzErrMsg ) *pzErrMsg = 0;
   106992   res.zErrMsg = 0;
   106993   res.nRow = 0;
   106994   res.nColumn = 0;
   106995   res.nData = 1;
   106996   res.nAlloc = 20;
   106997   res.rc = SQLITE_OK;
   106998   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
   106999   if( res.azResult==0 ){
   107000      db->errCode = SQLITE_NOMEM;
   107001      return SQLITE_NOMEM;
   107002   }
   107003   res.azResult[0] = 0;
   107004   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
   107005   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
   107006   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
   107007   if( (rc&0xff)==SQLITE_ABORT ){
   107008     sqlite3_free_table(&res.azResult[1]);
   107009     if( res.zErrMsg ){
   107010       if( pzErrMsg ){
   107011         sqlite3_free(*pzErrMsg);
   107012         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
   107013       }
   107014       sqlite3_free(res.zErrMsg);
   107015     }
   107016     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
   107017     return res.rc;
   107018   }
   107019   sqlite3_free(res.zErrMsg);
   107020   if( rc!=SQLITE_OK ){
   107021     sqlite3_free_table(&res.azResult[1]);
   107022     return rc;
   107023   }
   107024   if( res.nAlloc>res.nData ){
   107025     char **azNew;
   107026     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
   107027     if( azNew==0 ){
   107028       sqlite3_free_table(&res.azResult[1]);
   107029       db->errCode = SQLITE_NOMEM;
   107030       return SQLITE_NOMEM;
   107031     }
   107032     res.azResult = azNew;
   107033   }
   107034   *pazResult = &res.azResult[1];
   107035   if( pnColumn ) *pnColumn = res.nColumn;
   107036   if( pnRow ) *pnRow = res.nRow;
   107037   return rc;
   107038 }
   107039 
   107040 /*
   107041 ** This routine frees the space the sqlite3_get_table() malloced.
   107042 */
   107043 SQLITE_API void sqlite3_free_table(
   107044   char **azResult            /* Result returned from from sqlite3_get_table() */
   107045 ){
   107046   if( azResult ){
   107047     int i, n;
   107048     azResult--;
   107049     assert( azResult!=0 );
   107050     n = SQLITE_PTR_TO_INT(azResult[0]);
   107051     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
   107052     sqlite3_free(azResult);
   107053   }
   107054 }
   107055 
   107056 #endif /* SQLITE_OMIT_GET_TABLE */
   107057 
   107058 /************** End of table.c ***********************************************/
   107059 /************** Begin file trigger.c *****************************************/
   107060 /*
   107061 **
   107062 ** The author disclaims copyright to this source code.  In place of
   107063 ** a legal notice, here is a blessing:
   107064 **
   107065 **    May you do good and not evil.
   107066 **    May you find forgiveness for yourself and forgive others.
   107067 **    May you share freely, never taking more than you give.
   107068 **
   107069 *************************************************************************
   107070 ** This file contains the implementation for TRIGGERs
   107071 */
   107072 
   107073 #ifndef SQLITE_OMIT_TRIGGER
   107074 /*
   107075 ** Delete a linked list of TriggerStep structures.
   107076 */
   107077 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
   107078   while( pTriggerStep ){
   107079     TriggerStep * pTmp = pTriggerStep;
   107080     pTriggerStep = pTriggerStep->pNext;
   107081 
   107082     sqlite3ExprDelete(db, pTmp->pWhere);
   107083     sqlite3ExprListDelete(db, pTmp->pExprList);
   107084     sqlite3SelectDelete(db, pTmp->pSelect);
   107085     sqlite3IdListDelete(db, pTmp->pIdList);
   107086 
   107087     sqlite3DbFree(db, pTmp);
   107088   }
   107089 }
   107090 
   107091 /*
   107092 ** Given table pTab, return a list of all the triggers attached to
   107093 ** the table. The list is connected by Trigger.pNext pointers.
   107094 **
   107095 ** All of the triggers on pTab that are in the same database as pTab
   107096 ** are already attached to pTab->pTrigger.  But there might be additional
   107097 ** triggers on pTab in the TEMP schema.  This routine prepends all
   107098 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
   107099 ** and returns the combined list.
   107100 **
   107101 ** To state it another way:  This routine returns a list of all triggers
   107102 ** that fire off of pTab.  The list will include any TEMP triggers on
   107103 ** pTab as well as the triggers lised in pTab->pTrigger.
   107104 */
   107105 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
   107106   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
   107107   Trigger *pList = 0;                  /* List of triggers to return */
   107108 
   107109   if( pParse->disableTriggers ){
   107110     return 0;
   107111   }
   107112 
   107113   if( pTmpSchema!=pTab->pSchema ){
   107114     HashElem *p;
   107115     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
   107116     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
   107117       Trigger *pTrig = (Trigger *)sqliteHashData(p);
   107118       if( pTrig->pTabSchema==pTab->pSchema
   107119        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
   107120       ){
   107121         pTrig->pNext = (pList ? pList : pTab->pTrigger);
   107122         pList = pTrig;
   107123       }
   107124     }
   107125   }
   107126 
   107127   return (pList ? pList : pTab->pTrigger);
   107128 }
   107129 
   107130 /*
   107131 ** This is called by the parser when it sees a CREATE TRIGGER statement
   107132 ** up to the point of the BEGIN before the trigger actions.  A Trigger
   107133 ** structure is generated based on the information available and stored
   107134 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
   107135 ** sqlite3FinishTrigger() function is called to complete the trigger
   107136 ** construction process.
   107137 */
   107138 SQLITE_PRIVATE void sqlite3BeginTrigger(
   107139   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
   107140   Token *pName1,      /* The name of the trigger */
   107141   Token *pName2,      /* The name of the trigger */
   107142   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
   107143   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
   107144   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
   107145   SrcList *pTableName,/* The name of the table/view the trigger applies to */
   107146   Expr *pWhen,        /* WHEN clause */
   107147   int isTemp,         /* True if the TEMPORARY keyword is present */
   107148   int noErr           /* Suppress errors if the trigger already exists */
   107149 ){
   107150   Trigger *pTrigger = 0;  /* The new trigger */
   107151   Table *pTab;            /* Table that the trigger fires off of */
   107152   char *zName = 0;        /* Name of the trigger */
   107153   sqlite3 *db = pParse->db;  /* The database connection */
   107154   int iDb;                /* The database to store the trigger in */
   107155   Token *pName;           /* The unqualified db name */
   107156   DbFixer sFix;           /* State vector for the DB fixer */
   107157   int iTabDb;             /* Index of the database holding pTab */
   107158 
   107159   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
   107160   assert( pName2!=0 );
   107161   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
   107162   assert( op>0 && op<0xff );
   107163   if( isTemp ){
   107164     /* If TEMP was specified, then the trigger name may not be qualified. */
   107165     if( pName2->n>0 ){
   107166       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
   107167       goto trigger_cleanup;
   107168     }
   107169     iDb = 1;
   107170     pName = pName1;
   107171   }else{
   107172     /* Figure out the db that the trigger will be created in */
   107173     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   107174     if( iDb<0 ){
   107175       goto trigger_cleanup;
   107176     }
   107177   }
   107178   if( !pTableName || db->mallocFailed ){
   107179     goto trigger_cleanup;
   107180   }
   107181 
   107182   /* A long-standing parser bug is that this syntax was allowed:
   107183   **
   107184   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
   107185   **                                                 ^^^^^^^^
   107186   **
   107187   ** To maintain backwards compatibility, ignore the database
   107188   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
   107189   */
   107190   if( db->init.busy && iDb!=1 ){
   107191     sqlite3DbFree(db, pTableName->a[0].zDatabase);
   107192     pTableName->a[0].zDatabase = 0;
   107193   }
   107194 
   107195   /* If the trigger name was unqualified, and the table is a temp table,
   107196   ** then set iDb to 1 to create the trigger in the temporary database.
   107197   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
   107198   ** exist, the error is caught by the block below.
   107199   */
   107200   pTab = sqlite3SrcListLookup(pParse, pTableName);
   107201   if( db->init.busy==0 && pName2->n==0 && pTab
   107202         && pTab->pSchema==db->aDb[1].pSchema ){
   107203     iDb = 1;
   107204   }
   107205 
   107206   /* Ensure the table name matches database name and that the table exists */
   107207   if( db->mallocFailed ) goto trigger_cleanup;
   107208   assert( pTableName->nSrc==1 );
   107209   sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
   107210   if( sqlite3FixSrcList(&sFix, pTableName) ){
   107211     goto trigger_cleanup;
   107212   }
   107213   pTab = sqlite3SrcListLookup(pParse, pTableName);
   107214   if( !pTab ){
   107215     /* The table does not exist. */
   107216     if( db->init.iDb==1 ){
   107217       /* Ticket #3810.
   107218       ** Normally, whenever a table is dropped, all associated triggers are
   107219       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
   107220       ** and the table is dropped by a different database connection, the
   107221       ** trigger is not visible to the database connection that does the
   107222       ** drop so the trigger cannot be dropped.  This results in an
   107223       ** "orphaned trigger" - a trigger whose associated table is missing.
   107224       */
   107225       db->init.orphanTrigger = 1;
   107226     }
   107227     goto trigger_cleanup;
   107228   }
   107229   if( IsVirtual(pTab) ){
   107230     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
   107231     goto trigger_cleanup;
   107232   }
   107233 
   107234   /* Check that the trigger name is not reserved and that no trigger of the
   107235   ** specified name exists */
   107236   zName = sqlite3NameFromToken(db, pName);
   107237   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   107238     goto trigger_cleanup;
   107239   }
   107240   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   107241   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
   107242                       zName, sqlite3Strlen30(zName)) ){
   107243     if( !noErr ){
   107244       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
   107245     }else{
   107246       assert( !db->init.busy );
   107247       sqlite3CodeVerifySchema(pParse, iDb);
   107248     }
   107249     goto trigger_cleanup;
   107250   }
   107251 
   107252   /* Do not create a trigger on a system table */
   107253   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   107254     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
   107255     pParse->nErr++;
   107256     goto trigger_cleanup;
   107257   }
   107258 
   107259   /* INSTEAD of triggers are only for views and views only support INSTEAD
   107260   ** of triggers.
   107261   */
   107262   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
   107263     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
   107264         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
   107265     goto trigger_cleanup;
   107266   }
   107267   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
   107268     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
   107269         " trigger on table: %S", pTableName, 0);
   107270     goto trigger_cleanup;
   107271   }
   107272   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   107273 
   107274 #ifndef SQLITE_OMIT_AUTHORIZATION
   107275   {
   107276     int code = SQLITE_CREATE_TRIGGER;
   107277     const char *zDb = db->aDb[iTabDb].zName;
   107278     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
   107279     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
   107280     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
   107281       goto trigger_cleanup;
   107282     }
   107283     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
   107284       goto trigger_cleanup;
   107285     }
   107286   }
   107287 #endif
   107288 
   107289   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
   107290   ** cannot appear on views.  So we might as well translate every
   107291   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
   107292   ** elsewhere.
   107293   */
   107294   if (tr_tm == TK_INSTEAD){
   107295     tr_tm = TK_BEFORE;
   107296   }
   107297 
   107298   /* Build the Trigger object */
   107299   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
   107300   if( pTrigger==0 ) goto trigger_cleanup;
   107301   pTrigger->zName = zName;
   107302   zName = 0;
   107303   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
   107304   pTrigger->pSchema = db->aDb[iDb].pSchema;
   107305   pTrigger->pTabSchema = pTab->pSchema;
   107306   pTrigger->op = (u8)op;
   107307   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
   107308   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   107309   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
   107310   assert( pParse->pNewTrigger==0 );
   107311   pParse->pNewTrigger = pTrigger;
   107312 
   107313 trigger_cleanup:
   107314   sqlite3DbFree(db, zName);
   107315   sqlite3SrcListDelete(db, pTableName);
   107316   sqlite3IdListDelete(db, pColumns);
   107317   sqlite3ExprDelete(db, pWhen);
   107318   if( !pParse->pNewTrigger ){
   107319     sqlite3DeleteTrigger(db, pTrigger);
   107320   }else{
   107321     assert( pParse->pNewTrigger==pTrigger );
   107322   }
   107323 }
   107324 
   107325 /*
   107326 ** This routine is called after all of the trigger actions have been parsed
   107327 ** in order to complete the process of building the trigger.
   107328 */
   107329 SQLITE_PRIVATE void sqlite3FinishTrigger(
   107330   Parse *pParse,          /* Parser context */
   107331   TriggerStep *pStepList, /* The triggered program */
   107332   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
   107333 ){
   107334   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
   107335   char *zName;                            /* Name of trigger */
   107336   sqlite3 *db = pParse->db;               /* The database */
   107337   DbFixer sFix;                           /* Fixer object */
   107338   int iDb;                                /* Database containing the trigger */
   107339   Token nameToken;                        /* Trigger name for error reporting */
   107340 
   107341   pParse->pNewTrigger = 0;
   107342   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
   107343   zName = pTrig->zName;
   107344   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   107345   pTrig->step_list = pStepList;
   107346   while( pStepList ){
   107347     pStepList->pTrig = pTrig;
   107348     pStepList = pStepList->pNext;
   107349   }
   107350   nameToken.z = pTrig->zName;
   107351   nameToken.n = sqlite3Strlen30(nameToken.z);
   107352   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
   107353   if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
   107354    || sqlite3FixExpr(&sFix, pTrig->pWhen)
   107355   ){
   107356     goto triggerfinish_cleanup;
   107357   }
   107358 
   107359   /* if we are not initializing,
   107360   ** build the sqlite_master entry
   107361   */
   107362   if( !db->init.busy ){
   107363     Vdbe *v;
   107364     char *z;
   107365 
   107366     /* Make an entry in the sqlite_master table */
   107367     v = sqlite3GetVdbe(pParse);
   107368     if( v==0 ) goto triggerfinish_cleanup;
   107369     sqlite3BeginWriteOperation(pParse, 0, iDb);
   107370     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
   107371     sqlite3NestedParse(pParse,
   107372        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
   107373        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
   107374        pTrig->table, z);
   107375     sqlite3DbFree(db, z);
   107376     sqlite3ChangeCookie(pParse, iDb);
   107377     sqlite3VdbeAddParseSchemaOp(v, iDb,
   107378         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
   107379   }
   107380 
   107381   if( db->init.busy ){
   107382     Trigger *pLink = pTrig;
   107383     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
   107384     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   107385     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
   107386     if( pTrig ){
   107387       db->mallocFailed = 1;
   107388     }else if( pLink->pSchema==pLink->pTabSchema ){
   107389       Table *pTab;
   107390       int n = sqlite3Strlen30(pLink->table);
   107391       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
   107392       assert( pTab!=0 );
   107393       pLink->pNext = pTab->pTrigger;
   107394       pTab->pTrigger = pLink;
   107395     }
   107396   }
   107397 
   107398 triggerfinish_cleanup:
   107399   sqlite3DeleteTrigger(db, pTrig);
   107400   assert( !pParse->pNewTrigger );
   107401   sqlite3DeleteTriggerStep(db, pStepList);
   107402 }
   107403 
   107404 /*
   107405 ** Turn a SELECT statement (that the pSelect parameter points to) into
   107406 ** a trigger step.  Return a pointer to a TriggerStep structure.
   107407 **
   107408 ** The parser calls this routine when it finds a SELECT statement in
   107409 ** body of a TRIGGER.
   107410 */
   107411 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
   107412   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
   107413   if( pTriggerStep==0 ) {
   107414     sqlite3SelectDelete(db, pSelect);
   107415     return 0;
   107416   }
   107417   pTriggerStep->op = TK_SELECT;
   107418   pTriggerStep->pSelect = pSelect;
   107419   pTriggerStep->orconf = OE_Default;
   107420   return pTriggerStep;
   107421 }
   107422 
   107423 /*
   107424 ** Allocate space to hold a new trigger step.  The allocated space
   107425 ** holds both the TriggerStep object and the TriggerStep.target.z string.
   107426 **
   107427 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
   107428 */
   107429 static TriggerStep *triggerStepAllocate(
   107430   sqlite3 *db,                /* Database connection */
   107431   u8 op,                      /* Trigger opcode */
   107432   Token *pName                /* The target name */
   107433 ){
   107434   TriggerStep *pTriggerStep;
   107435 
   107436   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
   107437   if( pTriggerStep ){
   107438     char *z = (char*)&pTriggerStep[1];
   107439     memcpy(z, pName->z, pName->n);
   107440     pTriggerStep->target.z = z;
   107441     pTriggerStep->target.n = pName->n;
   107442     pTriggerStep->op = op;
   107443   }
   107444   return pTriggerStep;
   107445 }
   107446 
   107447 /*
   107448 ** Build a trigger step out of an INSERT statement.  Return a pointer
   107449 ** to the new trigger step.
   107450 **
   107451 ** The parser calls this routine when it sees an INSERT inside the
   107452 ** body of a trigger.
   107453 */
   107454 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
   107455   sqlite3 *db,        /* The database connection */
   107456   Token *pTableName,  /* Name of the table into which we insert */
   107457   IdList *pColumn,    /* List of columns in pTableName to insert into */
   107458   Select *pSelect,    /* A SELECT statement that supplies values */
   107459   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
   107460 ){
   107461   TriggerStep *pTriggerStep;
   107462 
   107463   assert(pSelect != 0 || db->mallocFailed);
   107464 
   107465   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
   107466   if( pTriggerStep ){
   107467     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   107468     pTriggerStep->pIdList = pColumn;
   107469     pTriggerStep->orconf = orconf;
   107470   }else{
   107471     sqlite3IdListDelete(db, pColumn);
   107472   }
   107473   sqlite3SelectDelete(db, pSelect);
   107474 
   107475   return pTriggerStep;
   107476 }
   107477 
   107478 /*
   107479 ** Construct a trigger step that implements an UPDATE statement and return
   107480 ** a pointer to that trigger step.  The parser calls this routine when it
   107481 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
   107482 */
   107483 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
   107484   sqlite3 *db,         /* The database connection */
   107485   Token *pTableName,   /* Name of the table to be updated */
   107486   ExprList *pEList,    /* The SET clause: list of column and new values */
   107487   Expr *pWhere,        /* The WHERE clause */
   107488   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
   107489 ){
   107490   TriggerStep *pTriggerStep;
   107491 
   107492   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
   107493   if( pTriggerStep ){
   107494     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   107495     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   107496     pTriggerStep->orconf = orconf;
   107497   }
   107498   sqlite3ExprListDelete(db, pEList);
   107499   sqlite3ExprDelete(db, pWhere);
   107500   return pTriggerStep;
   107501 }
   107502 
   107503 /*
   107504 ** Construct a trigger step that implements a DELETE statement and return
   107505 ** a pointer to that trigger step.  The parser calls this routine when it
   107506 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
   107507 */
   107508 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
   107509   sqlite3 *db,            /* Database connection */
   107510   Token *pTableName,      /* The table from which rows are deleted */
   107511   Expr *pWhere            /* The WHERE clause */
   107512 ){
   107513   TriggerStep *pTriggerStep;
   107514 
   107515   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
   107516   if( pTriggerStep ){
   107517     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   107518     pTriggerStep->orconf = OE_Default;
   107519   }
   107520   sqlite3ExprDelete(db, pWhere);
   107521   return pTriggerStep;
   107522 }
   107523 
   107524 /*
   107525 ** Recursively delete a Trigger structure
   107526 */
   107527 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
   107528   if( pTrigger==0 ) return;
   107529   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   107530   sqlite3DbFree(db, pTrigger->zName);
   107531   sqlite3DbFree(db, pTrigger->table);
   107532   sqlite3ExprDelete(db, pTrigger->pWhen);
   107533   sqlite3IdListDelete(db, pTrigger->pColumns);
   107534   sqlite3DbFree(db, pTrigger);
   107535 }
   107536 
   107537 /*
   107538 ** This function is called to drop a trigger from the database schema.
   107539 **
   107540 ** This may be called directly from the parser and therefore identifies
   107541 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
   107542 ** same job as this routine except it takes a pointer to the trigger
   107543 ** instead of the trigger name.
   107544 **/
   107545 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
   107546   Trigger *pTrigger = 0;
   107547   int i;
   107548   const char *zDb;
   107549   const char *zName;
   107550   int nName;
   107551   sqlite3 *db = pParse->db;
   107552 
   107553   if( db->mallocFailed ) goto drop_trigger_cleanup;
   107554   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   107555     goto drop_trigger_cleanup;
   107556   }
   107557 
   107558   assert( pName->nSrc==1 );
   107559   zDb = pName->a[0].zDatabase;
   107560   zName = pName->a[0].zName;
   107561   nName = sqlite3Strlen30(zName);
   107562   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   107563   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   107564     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   107565     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
   107566     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   107567     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
   107568     if( pTrigger ) break;
   107569   }
   107570   if( !pTrigger ){
   107571     if( !noErr ){
   107572       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
   107573     }else{
   107574       sqlite3CodeVerifyNamedSchema(pParse, zDb);
   107575     }
   107576     pParse->checkSchema = 1;
   107577     goto drop_trigger_cleanup;
   107578   }
   107579   sqlite3DropTriggerPtr(pParse, pTrigger);
   107580 
   107581 drop_trigger_cleanup:
   107582   sqlite3SrcListDelete(db, pName);
   107583 }
   107584 
   107585 /*
   107586 ** Return a pointer to the Table structure for the table that a trigger
   107587 ** is set on.
   107588 */
   107589 static Table *tableOfTrigger(Trigger *pTrigger){
   107590   int n = sqlite3Strlen30(pTrigger->table);
   107591   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
   107592 }
   107593 
   107594 
   107595 /*
   107596 ** Drop a trigger given a pointer to that trigger.
   107597 */
   107598 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   107599   Table   *pTable;
   107600   Vdbe *v;
   107601   sqlite3 *db = pParse->db;
   107602   int iDb;
   107603 
   107604   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
   107605   assert( iDb>=0 && iDb<db->nDb );
   107606   pTable = tableOfTrigger(pTrigger);
   107607   assert( pTable );
   107608   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   107609 #ifndef SQLITE_OMIT_AUTHORIZATION
   107610   {
   107611     int code = SQLITE_DROP_TRIGGER;
   107612     const char *zDb = db->aDb[iDb].zName;
   107613     const char *zTab = SCHEMA_TABLE(iDb);
   107614     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   107615     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   107616       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   107617       return;
   107618     }
   107619   }
   107620 #endif
   107621 
   107622   /* Generate code to destroy the database record of the trigger.
   107623   */
   107624   assert( pTable!=0 );
   107625   if( (v = sqlite3GetVdbe(pParse))!=0 ){
   107626     int base;
   107627     static const int iLn = VDBE_OFFSET_LINENO(2);
   107628     static const VdbeOpList dropTrigger[] = {
   107629       { OP_Rewind,     0, ADDR(9),  0},
   107630       { OP_String8,    0, 1,        0}, /* 1 */
   107631       { OP_Column,     0, 1,        2},
   107632       { OP_Ne,         2, ADDR(8),  1},
   107633       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
   107634       { OP_Column,     0, 0,        2},
   107635       { OP_Ne,         2, ADDR(8),  1},
   107636       { OP_Delete,     0, 0,        0},
   107637       { OP_Next,       0, ADDR(1),  0}, /* 8 */
   107638     };
   107639 
   107640     sqlite3BeginWriteOperation(pParse, 0, iDb);
   107641     sqlite3OpenMasterTable(pParse, iDb);
   107642     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
   107643     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
   107644     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
   107645     sqlite3ChangeCookie(pParse, iDb);
   107646     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
   107647     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   107648     if( pParse->nMem<3 ){
   107649       pParse->nMem = 3;
   107650     }
   107651   }
   107652 }
   107653 
   107654 /*
   107655 ** Remove a trigger from the hash tables of the sqlite* pointer.
   107656 */
   107657 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
   107658   Trigger *pTrigger;
   107659   Hash *pHash;
   107660 
   107661   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   107662   pHash = &(db->aDb[iDb].pSchema->trigHash);
   107663   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
   107664   if( ALWAYS(pTrigger) ){
   107665     if( pTrigger->pSchema==pTrigger->pTabSchema ){
   107666       Table *pTab = tableOfTrigger(pTrigger);
   107667       Trigger **pp;
   107668       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
   107669       *pp = (*pp)->pNext;
   107670     }
   107671     sqlite3DeleteTrigger(db, pTrigger);
   107672     db->flags |= SQLITE_InternChanges;
   107673   }
   107674 }
   107675 
   107676 /*
   107677 ** pEList is the SET clause of an UPDATE statement.  Each entry
   107678 ** in pEList is of the format <id>=<expr>.  If any of the entries
   107679 ** in pEList have an <id> which matches an identifier in pIdList,
   107680 ** then return TRUE.  If pIdList==NULL, then it is considered a
   107681 ** wildcard that matches anything.  Likewise if pEList==NULL then
   107682 ** it matches anything so always return true.  Return false only
   107683 ** if there is no match.
   107684 */
   107685 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
   107686   int e;
   107687   if( pIdList==0 || NEVER(pEList==0) ) return 1;
   107688   for(e=0; e<pEList->nExpr; e++){
   107689     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
   107690   }
   107691   return 0;
   107692 }
   107693 
   107694 /*
   107695 ** Return a list of all triggers on table pTab if there exists at least
   107696 ** one trigger that must be fired when an operation of type 'op' is
   107697 ** performed on the table, and, if that operation is an UPDATE, if at
   107698 ** least one of the columns in pChanges is being modified.
   107699 */
   107700 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
   107701   Parse *pParse,          /* Parse context */
   107702   Table *pTab,            /* The table the contains the triggers */
   107703   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
   107704   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
   107705   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   107706 ){
   107707   int mask = 0;
   107708   Trigger *pList = 0;
   107709   Trigger *p;
   107710 
   107711   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
   107712     pList = sqlite3TriggerList(pParse, pTab);
   107713   }
   107714   assert( pList==0 || IsVirtual(pTab)==0 );
   107715   for(p=pList; p; p=p->pNext){
   107716     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
   107717       mask |= p->tr_tm;
   107718     }
   107719   }
   107720   if( pMask ){
   107721     *pMask = mask;
   107722   }
   107723   return (mask ? pList : 0);
   107724 }
   107725 
   107726 /*
   107727 ** Convert the pStep->target token into a SrcList and return a pointer
   107728 ** to that SrcList.
   107729 **
   107730 ** This routine adds a specific database name, if needed, to the target when
   107731 ** forming the SrcList.  This prevents a trigger in one database from
   107732 ** referring to a target in another database.  An exception is when the
   107733 ** trigger is in TEMP in which case it can refer to any other database it
   107734 ** wants.
   107735 */
   107736 static SrcList *targetSrcList(
   107737   Parse *pParse,       /* The parsing context */
   107738   TriggerStep *pStep   /* The trigger containing the target token */
   107739 ){
   107740   int iDb;             /* Index of the database to use */
   107741   SrcList *pSrc;       /* SrcList to be returned */
   107742 
   107743   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
   107744   if( pSrc ){
   107745     assert( pSrc->nSrc>0 );
   107746     assert( pSrc->a!=0 );
   107747     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
   107748     if( iDb==0 || iDb>=2 ){
   107749       sqlite3 *db = pParse->db;
   107750       assert( iDb<pParse->db->nDb );
   107751       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   107752     }
   107753   }
   107754   return pSrc;
   107755 }
   107756 
   107757 /*
   107758 ** Generate VDBE code for the statements inside the body of a single
   107759 ** trigger.
   107760 */
   107761 static int codeTriggerProgram(
   107762   Parse *pParse,            /* The parser context */
   107763   TriggerStep *pStepList,   /* List of statements inside the trigger body */
   107764   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
   107765 ){
   107766   TriggerStep *pStep;
   107767   Vdbe *v = pParse->pVdbe;
   107768   sqlite3 *db = pParse->db;
   107769 
   107770   assert( pParse->pTriggerTab && pParse->pToplevel );
   107771   assert( pStepList );
   107772   assert( v!=0 );
   107773   for(pStep=pStepList; pStep; pStep=pStep->pNext){
   107774     /* Figure out the ON CONFLICT policy that will be used for this step
   107775     ** of the trigger program. If the statement that caused this trigger
   107776     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
   107777     ** the ON CONFLICT policy that was specified as part of the trigger
   107778     ** step statement. Example:
   107779     **
   107780     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
   107781     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
   107782     **   END;
   107783     **
   107784     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
   107785     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
   107786     */
   107787     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
   107788     assert( pParse->okConstFactor==0 );
   107789 
   107790     switch( pStep->op ){
   107791       case TK_UPDATE: {
   107792         sqlite3Update(pParse,
   107793           targetSrcList(pParse, pStep),
   107794           sqlite3ExprListDup(db, pStep->pExprList, 0),
   107795           sqlite3ExprDup(db, pStep->pWhere, 0),
   107796           pParse->eOrconf
   107797         );
   107798         break;
   107799       }
   107800       case TK_INSERT: {
   107801         sqlite3Insert(pParse,
   107802           targetSrcList(pParse, pStep),
   107803           sqlite3SelectDup(db, pStep->pSelect, 0),
   107804           sqlite3IdListDup(db, pStep->pIdList),
   107805           pParse->eOrconf
   107806         );
   107807         break;
   107808       }
   107809       case TK_DELETE: {
   107810         sqlite3DeleteFrom(pParse,
   107811           targetSrcList(pParse, pStep),
   107812           sqlite3ExprDup(db, pStep->pWhere, 0)
   107813         );
   107814         break;
   107815       }
   107816       default: assert( pStep->op==TK_SELECT ); {
   107817         SelectDest sDest;
   107818         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
   107819         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
   107820         sqlite3Select(pParse, pSelect, &sDest);
   107821         sqlite3SelectDelete(db, pSelect);
   107822         break;
   107823       }
   107824     }
   107825     if( pStep->op!=TK_SELECT ){
   107826       sqlite3VdbeAddOp0(v, OP_ResetCount);
   107827     }
   107828   }
   107829 
   107830   return 0;
   107831 }
   107832 
   107833 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   107834 /*
   107835 ** This function is used to add VdbeComment() annotations to a VDBE
   107836 ** program. It is not used in production code, only for debugging.
   107837 */
   107838 static const char *onErrorText(int onError){
   107839   switch( onError ){
   107840     case OE_Abort:    return "abort";
   107841     case OE_Rollback: return "rollback";
   107842     case OE_Fail:     return "fail";
   107843     case OE_Replace:  return "replace";
   107844     case OE_Ignore:   return "ignore";
   107845     case OE_Default:  return "default";
   107846   }
   107847   return "n/a";
   107848 }
   107849 #endif
   107850 
   107851 /*
   107852 ** Parse context structure pFrom has just been used to create a sub-vdbe
   107853 ** (trigger program). If an error has occurred, transfer error information
   107854 ** from pFrom to pTo.
   107855 */
   107856 static void transferParseError(Parse *pTo, Parse *pFrom){
   107857   assert( pFrom->zErrMsg==0 || pFrom->nErr );
   107858   assert( pTo->zErrMsg==0 || pTo->nErr );
   107859   if( pTo->nErr==0 ){
   107860     pTo->zErrMsg = pFrom->zErrMsg;
   107861     pTo->nErr = pFrom->nErr;
   107862   }else{
   107863     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
   107864   }
   107865 }
   107866 
   107867 /*
   107868 ** Create and populate a new TriggerPrg object with a sub-program
   107869 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
   107870 */
   107871 static TriggerPrg *codeRowTrigger(
   107872   Parse *pParse,       /* Current parse context */
   107873   Trigger *pTrigger,   /* Trigger to code */
   107874   Table *pTab,         /* The table pTrigger is attached to */
   107875   int orconf           /* ON CONFLICT policy to code trigger program with */
   107876 ){
   107877   Parse *pTop = sqlite3ParseToplevel(pParse);
   107878   sqlite3 *db = pParse->db;   /* Database handle */
   107879   TriggerPrg *pPrg;           /* Value to return */
   107880   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
   107881   Vdbe *v;                    /* Temporary VM */
   107882   NameContext sNC;            /* Name context for sub-vdbe */
   107883   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
   107884   Parse *pSubParse;           /* Parse context for sub-vdbe */
   107885   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
   107886 
   107887   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   107888   assert( pTop->pVdbe );
   107889 
   107890   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
   107891   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
   107892   ** list of the top-level Parse object sooner rather than later.  */
   107893   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   107894   if( !pPrg ) return 0;
   107895   pPrg->pNext = pTop->pTriggerPrg;
   107896   pTop->pTriggerPrg = pPrg;
   107897   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
   107898   if( !pProgram ) return 0;
   107899   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
   107900   pPrg->pTrigger = pTrigger;
   107901   pPrg->orconf = orconf;
   107902   pPrg->aColmask[0] = 0xffffffff;
   107903   pPrg->aColmask[1] = 0xffffffff;
   107904 
   107905   /* Allocate and populate a new Parse context to use for coding the
   107906   ** trigger sub-program.  */
   107907   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   107908   if( !pSubParse ) return 0;
   107909   memset(&sNC, 0, sizeof(sNC));
   107910   sNC.pParse = pSubParse;
   107911   pSubParse->db = db;
   107912   pSubParse->pTriggerTab = pTab;
   107913   pSubParse->pToplevel = pTop;
   107914   pSubParse->zAuthContext = pTrigger->zName;
   107915   pSubParse->eTriggerOp = pTrigger->op;
   107916   pSubParse->nQueryLoop = pParse->nQueryLoop;
   107917 
   107918   v = sqlite3GetVdbe(pSubParse);
   107919   if( v ){
   107920     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
   107921       pTrigger->zName, onErrorText(orconf),
   107922       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
   107923         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
   107924         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
   107925         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
   107926       pTab->zName
   107927     ));
   107928 #ifndef SQLITE_OMIT_TRACE
   107929     sqlite3VdbeChangeP4(v, -1,
   107930       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
   107931     );
   107932 #endif
   107933 
   107934     /* If one was specified, code the WHEN clause. If it evaluates to false
   107935     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
   107936     ** OP_Halt inserted at the end of the program.  */
   107937     if( pTrigger->pWhen ){
   107938       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
   107939       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
   107940        && db->mallocFailed==0
   107941       ){
   107942         iEndTrigger = sqlite3VdbeMakeLabel(v);
   107943         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
   107944       }
   107945       sqlite3ExprDelete(db, pWhen);
   107946     }
   107947 
   107948     /* Code the trigger program into the sub-vdbe. */
   107949     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
   107950 
   107951     /* Insert an OP_Halt at the end of the sub-program. */
   107952     if( iEndTrigger ){
   107953       sqlite3VdbeResolveLabel(v, iEndTrigger);
   107954     }
   107955     sqlite3VdbeAddOp0(v, OP_Halt);
   107956     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
   107957 
   107958     transferParseError(pParse, pSubParse);
   107959     if( db->mallocFailed==0 ){
   107960       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
   107961     }
   107962     pProgram->nMem = pSubParse->nMem;
   107963     pProgram->nCsr = pSubParse->nTab;
   107964     pProgram->nOnce = pSubParse->nOnce;
   107965     pProgram->token = (void *)pTrigger;
   107966     pPrg->aColmask[0] = pSubParse->oldmask;
   107967     pPrg->aColmask[1] = pSubParse->newmask;
   107968     sqlite3VdbeDelete(v);
   107969   }
   107970 
   107971   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   107972   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   107973   sqlite3ParserReset(pSubParse);
   107974   sqlite3StackFree(db, pSubParse);
   107975 
   107976   return pPrg;
   107977 }
   107978 
   107979 /*
   107980 ** Return a pointer to a TriggerPrg object containing the sub-program for
   107981 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
   107982 ** TriggerPrg object exists, a new object is allocated and populated before
   107983 ** being returned.
   107984 */
   107985 static TriggerPrg *getRowTrigger(
   107986   Parse *pParse,       /* Current parse context */
   107987   Trigger *pTrigger,   /* Trigger to code */
   107988   Table *pTab,         /* The table trigger pTrigger is attached to */
   107989   int orconf           /* ON CONFLICT algorithm. */
   107990 ){
   107991   Parse *pRoot = sqlite3ParseToplevel(pParse);
   107992   TriggerPrg *pPrg;
   107993 
   107994   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   107995 
   107996   /* It may be that this trigger has already been coded (or is in the
   107997   ** process of being coded). If this is the case, then an entry with
   107998   ** a matching TriggerPrg.pTrigger field will be present somewhere
   107999   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
   108000   for(pPrg=pRoot->pTriggerPrg;
   108001       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
   108002       pPrg=pPrg->pNext
   108003   );
   108004 
   108005   /* If an existing TriggerPrg could not be located, create a new one. */
   108006   if( !pPrg ){
   108007     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
   108008   }
   108009 
   108010   return pPrg;
   108011 }
   108012 
   108013 /*
   108014 ** Generate code for the trigger program associated with trigger p on
   108015 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
   108016 ** function are the same as those described in the header function for
   108017 ** sqlite3CodeRowTrigger()
   108018 */
   108019 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   108020   Parse *pParse,       /* Parse context */
   108021   Trigger *p,          /* Trigger to code */
   108022   Table *pTab,         /* The table to code triggers from */
   108023   int reg,             /* Reg array containing OLD.* and NEW.* values */
   108024   int orconf,          /* ON CONFLICT policy */
   108025   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   108026 ){
   108027   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   108028   TriggerPrg *pPrg;
   108029   pPrg = getRowTrigger(pParse, p, pTab, orconf);
   108030   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
   108031 
   108032   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   108033   ** is a pointer to the sub-vdbe containing the trigger program.  */
   108034   if( pPrg ){
   108035     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
   108036 
   108037     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
   108038     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
   108039     VdbeComment(
   108040         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
   108041 
   108042     /* Set the P5 operand of the OP_Program instruction to non-zero if
   108043     ** recursive invocation of this trigger program is disallowed. Recursive
   108044     ** invocation is disallowed if (a) the sub-program is really a trigger,
   108045     ** not a foreign key action, and (b) the flag to enable recursive triggers
   108046     ** is clear.  */
   108047     sqlite3VdbeChangeP5(v, (u8)bRecursive);
   108048   }
   108049 }
   108050 
   108051 /*
   108052 ** This is called to code the required FOR EACH ROW triggers for an operation
   108053 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
   108054 ** is given by the op parameter. The tr_tm parameter determines whether the
   108055 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
   108056 ** parameter pChanges is passed the list of columns being modified.
   108057 **
   108058 ** If there are no triggers that fire at the specified time for the specified
   108059 ** operation on pTab, this function is a no-op.
   108060 **
   108061 ** The reg argument is the address of the first in an array of registers
   108062 ** that contain the values substituted for the new.* and old.* references
   108063 ** in the trigger program. If N is the number of columns in table pTab
   108064 ** (a copy of pTab->nCol), then registers are populated as follows:
   108065 **
   108066 **   Register       Contains
   108067 **   ------------------------------------------------------
   108068 **   reg+0          OLD.rowid
   108069 **   reg+1          OLD.* value of left-most column of pTab
   108070 **   ...            ...
   108071 **   reg+N          OLD.* value of right-most column of pTab
   108072 **   reg+N+1        NEW.rowid
   108073 **   reg+N+2        OLD.* value of left-most column of pTab
   108074 **   ...            ...
   108075 **   reg+N+N+1      NEW.* value of right-most column of pTab
   108076 **
   108077 ** For ON DELETE triggers, the registers containing the NEW.* values will
   108078 ** never be accessed by the trigger program, so they are not allocated or
   108079 ** populated by the caller (there is no data to populate them with anyway).
   108080 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
   108081 ** are never accessed, and so are not allocated by the caller. So, for an
   108082 ** ON INSERT trigger, the value passed to this function as parameter reg
   108083 ** is not a readable register, although registers (reg+N) through
   108084 ** (reg+N+N+1) are.
   108085 **
   108086 ** Parameter orconf is the default conflict resolution algorithm for the
   108087 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
   108088 ** is the instruction that control should jump to if a trigger program
   108089 ** raises an IGNORE exception.
   108090 */
   108091 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
   108092   Parse *pParse,       /* Parse context */
   108093   Trigger *pTrigger,   /* List of triggers on table pTab */
   108094   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   108095   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   108096   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   108097   Table *pTab,         /* The table to code triggers from */
   108098   int reg,             /* The first in an array of registers (see above) */
   108099   int orconf,          /* ON CONFLICT policy */
   108100   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   108101 ){
   108102   Trigger *p;          /* Used to iterate through pTrigger list */
   108103 
   108104   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
   108105   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
   108106   assert( (op==TK_UPDATE)==(pChanges!=0) );
   108107 
   108108   for(p=pTrigger; p; p=p->pNext){
   108109 
   108110     /* Sanity checking:  The schema for the trigger and for the table are
   108111     ** always defined.  The trigger must be in the same schema as the table
   108112     ** or else it must be a TEMP trigger. */
   108113     assert( p->pSchema!=0 );
   108114     assert( p->pTabSchema!=0 );
   108115     assert( p->pSchema==p->pTabSchema
   108116          || p->pSchema==pParse->db->aDb[1].pSchema );
   108117 
   108118     /* Determine whether we should code this trigger */
   108119     if( p->op==op
   108120      && p->tr_tm==tr_tm
   108121      && checkColumnOverlap(p->pColumns, pChanges)
   108122     ){
   108123       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
   108124     }
   108125   }
   108126 }
   108127 
   108128 /*
   108129 ** Triggers may access values stored in the old.* or new.* pseudo-table.
   108130 ** This function returns a 32-bit bitmask indicating which columns of the
   108131 ** old.* or new.* tables actually are used by triggers. This information
   108132 ** may be used by the caller, for example, to avoid having to load the entire
   108133 ** old.* record into memory when executing an UPDATE or DELETE command.
   108134 **
   108135 ** Bit 0 of the returned mask is set if the left-most column of the
   108136 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
   108137 ** the second leftmost column value is required, and so on. If there
   108138 ** are more than 32 columns in the table, and at least one of the columns
   108139 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
   108140 **
   108141 ** It is not possible to determine if the old.rowid or new.rowid column is
   108142 ** accessed by triggers. The caller must always assume that it is.
   108143 **
   108144 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
   108145 ** applies to the old.* table. If 1, the new.* table.
   108146 **
   108147 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
   108148 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
   108149 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
   108150 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
   108151 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
   108152 */
   108153 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
   108154   Parse *pParse,       /* Parse context */
   108155   Trigger *pTrigger,   /* List of triggers on table pTab */
   108156   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   108157   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
   108158   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   108159   Table *pTab,         /* The table to code triggers from */
   108160   int orconf           /* Default ON CONFLICT policy for trigger steps */
   108161 ){
   108162   const int op = pChanges ? TK_UPDATE : TK_DELETE;
   108163   u32 mask = 0;
   108164   Trigger *p;
   108165 
   108166   assert( isNew==1 || isNew==0 );
   108167   for(p=pTrigger; p; p=p->pNext){
   108168     if( p->op==op && (tr_tm&p->tr_tm)
   108169      && checkColumnOverlap(p->pColumns,pChanges)
   108170     ){
   108171       TriggerPrg *pPrg;
   108172       pPrg = getRowTrigger(pParse, p, pTab, orconf);
   108173       if( pPrg ){
   108174         mask |= pPrg->aColmask[isNew];
   108175       }
   108176     }
   108177   }
   108178 
   108179   return mask;
   108180 }
   108181 
   108182 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   108183 
   108184 /************** End of trigger.c *********************************************/
   108185 /************** Begin file update.c ******************************************/
   108186 /*
   108187 ** 2001 September 15
   108188 **
   108189 ** The author disclaims copyright to this source code.  In place of
   108190 ** a legal notice, here is a blessing:
   108191 **
   108192 **    May you do good and not evil.
   108193 **    May you find forgiveness for yourself and forgive others.
   108194 **    May you share freely, never taking more than you give.
   108195 **
   108196 *************************************************************************
   108197 ** This file contains C code routines that are called by the parser
   108198 ** to handle UPDATE statements.
   108199 */
   108200 
   108201 #ifndef SQLITE_OMIT_VIRTUALTABLE
   108202 /* Forward declaration */
   108203 static void updateVirtualTable(
   108204   Parse *pParse,       /* The parsing context */
   108205   SrcList *pSrc,       /* The virtual table to be modified */
   108206   Table *pTab,         /* The virtual table */
   108207   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   108208   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
   108209   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   108210   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   108211   int onError          /* ON CONFLICT strategy */
   108212 );
   108213 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   108214 
   108215 /*
   108216 ** The most recently coded instruction was an OP_Column to retrieve the
   108217 ** i-th column of table pTab. This routine sets the P4 parameter of the
   108218 ** OP_Column to the default value, if any.
   108219 **
   108220 ** The default value of a column is specified by a DEFAULT clause in the
   108221 ** column definition. This was either supplied by the user when the table
   108222 ** was created, or added later to the table definition by an ALTER TABLE
   108223 ** command. If the latter, then the row-records in the table btree on disk
   108224 ** may not contain a value for the column and the default value, taken
   108225 ** from the P4 parameter of the OP_Column instruction, is returned instead.
   108226 ** If the former, then all row-records are guaranteed to include a value
   108227 ** for the column and the P4 value is not required.
   108228 **
   108229 ** Column definitions created by an ALTER TABLE command may only have
   108230 ** literal default values specified: a number, null or a string. (If a more
   108231 ** complicated default expression value was provided, it is evaluated
   108232 ** when the ALTER TABLE is executed and one of the literal values written
   108233 ** into the sqlite_master table.)
   108234 **
   108235 ** Therefore, the P4 parameter is only required if the default value for
   108236 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
   108237 ** function is capable of transforming these types of expressions into
   108238 ** sqlite3_value objects.
   108239 **
   108240 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
   108241 ** on register iReg. This is used when an equivalent integer value is
   108242 ** stored in place of an 8-byte floating point value in order to save
   108243 ** space.
   108244 */
   108245 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   108246   assert( pTab!=0 );
   108247   if( !pTab->pSelect ){
   108248     sqlite3_value *pValue = 0;
   108249     u8 enc = ENC(sqlite3VdbeDb(v));
   108250     Column *pCol = &pTab->aCol[i];
   108251     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
   108252     assert( i<pTab->nCol );
   108253     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
   108254                          pCol->affinity, &pValue);
   108255     if( pValue ){
   108256       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
   108257     }
   108258 #ifndef SQLITE_OMIT_FLOATING_POINT
   108259     if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
   108260       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
   108261     }
   108262 #endif
   108263   }
   108264 }
   108265 
   108266 /*
   108267 ** Process an UPDATE statement.
   108268 **
   108269 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
   108270 **          \_______/ \________/     \______/       \________________/
   108271 *            onError   pTabList      pChanges             pWhere
   108272 */
   108273 SQLITE_PRIVATE void sqlite3Update(
   108274   Parse *pParse,         /* The parser context */
   108275   SrcList *pTabList,     /* The table in which we should change things */
   108276   ExprList *pChanges,    /* Things to be changed */
   108277   Expr *pWhere,          /* The WHERE clause.  May be null */
   108278   int onError            /* How to handle constraint errors */
   108279 ){
   108280   int i, j;              /* Loop counters */
   108281   Table *pTab;           /* The table to be updated */
   108282   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
   108283   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   108284   Vdbe *v;               /* The virtual database engine */
   108285   Index *pIdx;           /* For looping over indices */
   108286   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
   108287   int nIdx;              /* Number of indices that need updating */
   108288   int iBaseCur;          /* Base cursor number */
   108289   int iDataCur;          /* Cursor for the canonical data btree */
   108290   int iIdxCur;           /* Cursor for the first index */
   108291   sqlite3 *db;           /* The database structure */
   108292   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
   108293   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
   108294                          ** an expression for the i-th column of the table.
   108295                          ** aXRef[i]==-1 if the i-th column is not changed. */
   108296   u8 *aToOpen;           /* 1 for tables and indices to be opened */
   108297   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
   108298   u8 chngRowid;          /* Rowid changed in a normal table */
   108299   u8 chngKey;            /* Either chngPk or chngRowid */
   108300   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
   108301   AuthContext sContext;  /* The authorization context */
   108302   NameContext sNC;       /* The name-context to resolve expressions in */
   108303   int iDb;               /* Database containing the table being updated */
   108304   int okOnePass;         /* True for one-pass algorithm without the FIFO */
   108305   int hasFK;             /* True if foreign key processing is required */
   108306   int labelBreak;        /* Jump here to break out of UPDATE loop */
   108307   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
   108308 
   108309 #ifndef SQLITE_OMIT_TRIGGER
   108310   int isView;            /* True when updating a view (INSTEAD OF trigger) */
   108311   Trigger *pTrigger;     /* List of triggers on pTab, if required */
   108312   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   108313 #endif
   108314   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
   108315   int iEph = 0;          /* Ephemeral table holding all primary key values */
   108316   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
   108317   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
   108318 
   108319   /* Register Allocations */
   108320   int regRowCount = 0;   /* A count of rows changed */
   108321   int regOldRowid;       /* The old rowid */
   108322   int regNewRowid;       /* The new rowid */
   108323   int regNew;            /* Content of the NEW.* table in triggers */
   108324   int regOld = 0;        /* Content of OLD.* table in triggers */
   108325   int regRowSet = 0;     /* Rowset of rows to be updated */
   108326   int regKey = 0;        /* composite PRIMARY KEY value */
   108327 
   108328   memset(&sContext, 0, sizeof(sContext));
   108329   db = pParse->db;
   108330   if( pParse->nErr || db->mallocFailed ){
   108331     goto update_cleanup;
   108332   }
   108333   assert( pTabList->nSrc==1 );
   108334 
   108335   /* Locate the table which we want to update.
   108336   */
   108337   pTab = sqlite3SrcListLookup(pParse, pTabList);
   108338   if( pTab==0 ) goto update_cleanup;
   108339   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   108340 
   108341   /* Figure out if we have any triggers and if the table being
   108342   ** updated is a view.
   108343   */
   108344 #ifndef SQLITE_OMIT_TRIGGER
   108345   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
   108346   isView = pTab->pSelect!=0;
   108347   assert( pTrigger || tmask==0 );
   108348 #else
   108349 # define pTrigger 0
   108350 # define isView 0
   108351 # define tmask 0
   108352 #endif
   108353 #ifdef SQLITE_OMIT_VIEW
   108354 # undef isView
   108355 # define isView 0
   108356 #endif
   108357 
   108358   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   108359     goto update_cleanup;
   108360   }
   108361   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   108362     goto update_cleanup;
   108363   }
   108364 
   108365   /* Allocate a cursors for the main database table and for all indices.
   108366   ** The index cursors might not be used, but if they are used they
   108367   ** need to occur right after the database cursor.  So go ahead and
   108368   ** allocate enough space, just in case.
   108369   */
   108370   pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
   108371   iIdxCur = iDataCur+1;
   108372   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   108373   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
   108374     if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
   108375       iDataCur = pParse->nTab;
   108376       pTabList->a[0].iCursor = iDataCur;
   108377     }
   108378     pParse->nTab++;
   108379   }
   108380 
   108381   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
   108382   ** Initialize aXRef[] and aToOpen[] to their default values.
   108383   */
   108384   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
   108385   if( aXRef==0 ) goto update_cleanup;
   108386   aRegIdx = aXRef+pTab->nCol;
   108387   aToOpen = (u8*)(aRegIdx+nIdx);
   108388   memset(aToOpen, 1, nIdx+1);
   108389   aToOpen[nIdx+1] = 0;
   108390   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   108391 
   108392   /* Initialize the name-context */
   108393   memset(&sNC, 0, sizeof(sNC));
   108394   sNC.pParse = pParse;
   108395   sNC.pSrcList = pTabList;
   108396 
   108397   /* Resolve the column names in all the expressions of the
   108398   ** of the UPDATE statement.  Also find the column index
   108399   ** for each column to be updated in the pChanges array.  For each
   108400   ** column to be updated, make sure we have authorization to change
   108401   ** that column.
   108402   */
   108403   chngRowid = chngPk = 0;
   108404   for(i=0; i<pChanges->nExpr; i++){
   108405     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
   108406       goto update_cleanup;
   108407     }
   108408     for(j=0; j<pTab->nCol; j++){
   108409       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   108410         if( j==pTab->iPKey ){
   108411           chngRowid = 1;
   108412           pRowidExpr = pChanges->a[i].pExpr;
   108413         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
   108414           chngPk = 1;
   108415         }
   108416         aXRef[j] = i;
   108417         break;
   108418       }
   108419     }
   108420     if( j>=pTab->nCol ){
   108421       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
   108422         j = -1;
   108423         chngRowid = 1;
   108424         pRowidExpr = pChanges->a[i].pExpr;
   108425       }else{
   108426         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
   108427         pParse->checkSchema = 1;
   108428         goto update_cleanup;
   108429       }
   108430     }
   108431 #ifndef SQLITE_OMIT_AUTHORIZATION
   108432     {
   108433       int rc;
   108434       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
   108435                             j<0 ? "ROWID" : pTab->aCol[j].zName,
   108436                             db->aDb[iDb].zName);
   108437       if( rc==SQLITE_DENY ){
   108438         goto update_cleanup;
   108439       }else if( rc==SQLITE_IGNORE ){
   108440         aXRef[j] = -1;
   108441       }
   108442     }
   108443 #endif
   108444   }
   108445   assert( (chngRowid & chngPk)==0 );
   108446   assert( chngRowid==0 || chngRowid==1 );
   108447   assert( chngPk==0 || chngPk==1 );
   108448   chngKey = chngRowid + chngPk;
   108449 
   108450   /* The SET expressions are not actually used inside the WHERE loop.
   108451   ** So reset the colUsed mask
   108452   */
   108453   pTabList->a[0].colUsed = 0;
   108454 
   108455   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
   108456 
   108457   /* There is one entry in the aRegIdx[] array for each index on the table
   108458   ** being updated.  Fill in aRegIdx[] with a register number that will hold
   108459   ** the key for accessing each index.
   108460   */
   108461   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   108462     int reg;
   108463     if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
   108464       reg = ++pParse->nMem;
   108465     }else{
   108466       reg = 0;
   108467       for(i=0; i<pIdx->nKeyCol; i++){
   108468         if( aXRef[pIdx->aiColumn[i]]>=0 ){
   108469           reg = ++pParse->nMem;
   108470           break;
   108471         }
   108472       }
   108473     }
   108474     if( reg==0 ) aToOpen[j+1] = 0;
   108475     aRegIdx[j] = reg;
   108476   }
   108477 
   108478   /* Begin generating code. */
   108479   v = sqlite3GetVdbe(pParse);
   108480   if( v==0 ) goto update_cleanup;
   108481   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   108482   sqlite3BeginWriteOperation(pParse, 1, iDb);
   108483 
   108484 #ifndef SQLITE_OMIT_VIRTUALTABLE
   108485   /* Virtual tables must be handled separately */
   108486   if( IsVirtual(pTab) ){
   108487     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
   108488                        pWhere, onError);
   108489     pWhere = 0;
   108490     pTabList = 0;
   108491     goto update_cleanup;
   108492   }
   108493 #endif
   108494 
   108495   /* Allocate required registers. */
   108496   regRowSet = ++pParse->nMem;
   108497   regOldRowid = regNewRowid = ++pParse->nMem;
   108498   if( chngPk || pTrigger || hasFK ){
   108499     regOld = pParse->nMem + 1;
   108500     pParse->nMem += pTab->nCol;
   108501   }
   108502   if( chngKey || pTrigger || hasFK ){
   108503     regNewRowid = ++pParse->nMem;
   108504   }
   108505   regNew = pParse->nMem + 1;
   108506   pParse->nMem += pTab->nCol;
   108507 
   108508   /* Start the view context. */
   108509   if( isView ){
   108510     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   108511   }
   108512 
   108513   /* If we are trying to update a view, realize that view into
   108514   ** a ephemeral table.
   108515   */
   108516 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   108517   if( isView ){
   108518     sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
   108519   }
   108520 #endif
   108521 
   108522   /* Resolve the column names in all the expressions in the
   108523   ** WHERE clause.
   108524   */
   108525   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   108526     goto update_cleanup;
   108527   }
   108528 
   108529   /* Begin the database scan
   108530   */
   108531   if( HasRowid(pTab) ){
   108532     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
   108533     pWInfo = sqlite3WhereBegin(
   108534         pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
   108535     );
   108536     if( pWInfo==0 ) goto update_cleanup;
   108537     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
   108538 
   108539     /* Remember the rowid of every item to be updated.
   108540     */
   108541     sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
   108542     if( !okOnePass ){
   108543       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
   108544     }
   108545 
   108546     /* End the database scan loop.
   108547     */
   108548     sqlite3WhereEnd(pWInfo);
   108549   }else{
   108550     int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
   108551     i16 nPk;         /* Number of components of the PRIMARY KEY */
   108552     int addrOpen;    /* Address of the OpenEphemeral instruction */
   108553 
   108554     assert( pPk!=0 );
   108555     nPk = pPk->nKeyCol;
   108556     iPk = pParse->nMem+1;
   108557     pParse->nMem += nPk;
   108558     regKey = ++pParse->nMem;
   108559     iEph = pParse->nTab++;
   108560     sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
   108561     addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
   108562     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   108563     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
   108564                                WHERE_ONEPASS_DESIRED, iIdxCur);
   108565     if( pWInfo==0 ) goto update_cleanup;
   108566     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
   108567     for(i=0; i<nPk; i++){
   108568       sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
   108569                                       iPk+i);
   108570     }
   108571     if( okOnePass ){
   108572       sqlite3VdbeChangeToNoop(v, addrOpen);
   108573       nKey = nPk;
   108574       regKey = iPk;
   108575     }else{
   108576       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
   108577                         sqlite3IndexAffinityStr(v, pPk), nPk);
   108578       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
   108579     }
   108580     sqlite3WhereEnd(pWInfo);
   108581   }
   108582 
   108583   /* Initialize the count of updated rows
   108584   */
   108585   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
   108586     regRowCount = ++pParse->nMem;
   108587     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   108588   }
   108589 
   108590   labelBreak = sqlite3VdbeMakeLabel(v);
   108591   if( !isView ){
   108592     /*
   108593     ** Open every index that needs updating.  Note that if any
   108594     ** index could potentially invoke a REPLACE conflict resolution
   108595     ** action, then we need to open all indices because we might need
   108596     ** to be deleting some records.
   108597     */
   108598     if( onError==OE_Replace ){
   108599       memset(aToOpen, 1, nIdx+1);
   108600     }else{
   108601       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   108602         if( pIdx->onError==OE_Replace ){
   108603           memset(aToOpen, 1, nIdx+1);
   108604           break;
   108605         }
   108606       }
   108607     }
   108608     if( okOnePass ){
   108609       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
   108610       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
   108611     }
   108612     sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
   108613                                0, 0);
   108614   }
   108615 
   108616   /* Top of the update loop */
   108617   if( okOnePass ){
   108618     if( aToOpen[iDataCur-iBaseCur] ){
   108619       assert( pPk!=0 );
   108620       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
   108621       VdbeCoverageNeverTaken(v);
   108622     }
   108623     labelContinue = labelBreak;
   108624     sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
   108625     VdbeCoverageIf(v, pPk==0);
   108626     VdbeCoverageIf(v, pPk!=0);
   108627   }else if( pPk ){
   108628     labelContinue = sqlite3VdbeMakeLabel(v);
   108629     sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
   108630     addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
   108631     sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
   108632     VdbeCoverage(v);
   108633   }else{
   108634     labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
   108635                              regOldRowid);
   108636     VdbeCoverage(v);
   108637     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
   108638     VdbeCoverage(v);
   108639   }
   108640 
   108641   /* If the record number will change, set register regNewRowid to
   108642   ** contain the new value. If the record number is not being modified,
   108643   ** then regNewRowid is the same register as regOldRowid, which is
   108644   ** already populated.  */
   108645   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
   108646   if( chngRowid ){
   108647     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   108648     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
   108649   }
   108650 
   108651   /* Compute the old pre-UPDATE content of the row being changed, if that
   108652   ** information is needed */
   108653   if( chngPk || hasFK || pTrigger ){
   108654     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   108655     oldmask |= sqlite3TriggerColmask(pParse,
   108656         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
   108657     );
   108658     for(i=0; i<pTab->nCol; i++){
   108659       if( oldmask==0xffffffff
   108660        || (i<32 && (oldmask & MASKBIT32(i))!=0)
   108661        || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
   108662       ){
   108663         testcase(  oldmask!=0xffffffff && i==31 );
   108664         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
   108665       }else{
   108666         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
   108667       }
   108668     }
   108669     if( chngRowid==0 && pPk==0 ){
   108670       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
   108671     }
   108672   }
   108673 
   108674   /* Populate the array of registers beginning at regNew with the new
   108675   ** row data. This array is used to check constaints, create the new
   108676   ** table and index records, and as the values for any new.* references
   108677   ** made by triggers.
   108678   **
   108679   ** If there are one or more BEFORE triggers, then do not populate the
   108680   ** registers associated with columns that are (a) not modified by
   108681   ** this UPDATE statement and (b) not accessed by new.* references. The
   108682   ** values for registers not modified by the UPDATE must be reloaded from
   108683   ** the database after the BEFORE triggers are fired anyway (as the trigger
   108684   ** may have modified them). So not loading those that are not going to
   108685   ** be used eliminates some redundant opcodes.
   108686   */
   108687   newmask = sqlite3TriggerColmask(
   108688       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
   108689   );
   108690   /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
   108691   for(i=0; i<pTab->nCol; i++){
   108692     if( i==pTab->iPKey ){
   108693       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   108694     }else{
   108695       j = aXRef[i];
   108696       if( j>=0 ){
   108697         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
   108698       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
   108699         /* This branch loads the value of a column that will not be changed
   108700         ** into a register. This is done if there are no BEFORE triggers, or
   108701         ** if there are one or more BEFORE triggers that use this value via
   108702         ** a new.* reference in a trigger program.
   108703         */
   108704         testcase( i==31 );
   108705         testcase( i==32 );
   108706         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
   108707       }else{
   108708         sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   108709       }
   108710     }
   108711   }
   108712 
   108713   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   108714   ** verified. One could argue that this is wrong.
   108715   */
   108716   if( tmask&TRIGGER_BEFORE ){
   108717     sqlite3TableAffinity(v, pTab, regNew);
   108718     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   108719         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
   108720 
   108721     /* The row-trigger may have deleted the row being updated. In this
   108722     ** case, jump to the next row. No updates or AFTER triggers are
   108723     ** required. This behavior - what happens when the row being updated
   108724     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   108725     ** documentation.
   108726     */
   108727     if( pPk ){
   108728       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
   108729       VdbeCoverage(v);
   108730     }else{
   108731       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
   108732       VdbeCoverage(v);
   108733     }
   108734 
   108735     /* If it did not delete it, the row-trigger may still have modified
   108736     ** some of the columns of the row being updated. Load the values for
   108737     ** all columns not modified by the update statement into their
   108738     ** registers in case this has happened.
   108739     */
   108740     for(i=0; i<pTab->nCol; i++){
   108741       if( aXRef[i]<0 && i!=pTab->iPKey ){
   108742         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
   108743       }
   108744     }
   108745   }
   108746 
   108747   if( !isView ){
   108748     int j1 = 0;           /* Address of jump instruction */
   108749     int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
   108750 
   108751     /* Do constraint checks. */
   108752     assert( regOldRowid>0 );
   108753     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
   108754         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
   108755 
   108756     /* Do FK constraint checks. */
   108757     if( hasFK ){
   108758       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
   108759     }
   108760 
   108761     /* Delete the index entries associated with the current record.  */
   108762     if( bReplace || chngKey ){
   108763       if( pPk ){
   108764         j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
   108765       }else{
   108766         j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
   108767       }
   108768       VdbeCoverageNeverTaken(v);
   108769     }
   108770     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
   108771 
   108772     /* If changing the record number, delete the old record.  */
   108773     if( hasFK || chngKey || pPk!=0 ){
   108774       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
   108775     }
   108776     if( bReplace || chngKey ){
   108777       sqlite3VdbeJumpHere(v, j1);
   108778     }
   108779 
   108780     if( hasFK ){
   108781       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
   108782     }
   108783 
   108784     /* Insert the new index entries and the new record. */
   108785     sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
   108786                              regNewRowid, aRegIdx, 1, 0, 0);
   108787 
   108788     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   108789     ** handle rows (possibly in other tables) that refer via a foreign key
   108790     ** to the row just updated. */
   108791     if( hasFK ){
   108792       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
   108793     }
   108794   }
   108795 
   108796   /* Increment the row counter
   108797   */
   108798   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   108799     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   108800   }
   108801 
   108802   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   108803       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
   108804 
   108805   /* Repeat the above with the next record to be updated, until
   108806   ** all record selected by the WHERE clause have been updated.
   108807   */
   108808   if( okOnePass ){
   108809     /* Nothing to do at end-of-loop for a single-pass */
   108810   }else if( pPk ){
   108811     sqlite3VdbeResolveLabel(v, labelContinue);
   108812     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
   108813   }else{
   108814     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
   108815   }
   108816   sqlite3VdbeResolveLabel(v, labelBreak);
   108817 
   108818   /* Close all tables */
   108819   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   108820     assert( aRegIdx );
   108821     if( aToOpen[i+1] ){
   108822       sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
   108823     }
   108824   }
   108825   if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
   108826 
   108827   /* Update the sqlite_sequence table by storing the content of the
   108828   ** maximum rowid counter values recorded while inserting into
   108829   ** autoincrement tables.
   108830   */
   108831   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   108832     sqlite3AutoincrementEnd(pParse);
   108833   }
   108834 
   108835   /*
   108836   ** Return the number of rows that were changed. If this routine is
   108837   ** generating code because of a call to sqlite3NestedParse(), do not
   108838   ** invoke the callback function.
   108839   */
   108840   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
   108841     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   108842     sqlite3VdbeSetNumCols(v, 1);
   108843     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   108844   }
   108845 
   108846 update_cleanup:
   108847   sqlite3AuthContextPop(&sContext);
   108848   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
   108849   sqlite3SrcListDelete(db, pTabList);
   108850   sqlite3ExprListDelete(db, pChanges);
   108851   sqlite3ExprDelete(db, pWhere);
   108852   return;
   108853 }
   108854 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   108855 ** thely may interfere with compilation of other functions in this file
   108856 ** (or in another file, if this file becomes part of the amalgamation).  */
   108857 #ifdef isView
   108858  #undef isView
   108859 #endif
   108860 #ifdef pTrigger
   108861  #undef pTrigger
   108862 #endif
   108863 
   108864 #ifndef SQLITE_OMIT_VIRTUALTABLE
   108865 /*
   108866 ** Generate code for an UPDATE of a virtual table.
   108867 **
   108868 ** The strategy is that we create an ephemerial table that contains
   108869 ** for each row to be changed:
   108870 **
   108871 **   (A)  The original rowid of that row.
   108872 **   (B)  The revised rowid for the row. (note1)
   108873 **   (C)  The content of every column in the row.
   108874 **
   108875 ** Then we loop over this ephemeral table and for each row in
   108876 ** the ephermeral table call VUpdate.
   108877 **
   108878 ** When finished, drop the ephemeral table.
   108879 **
   108880 ** (note1) Actually, if we know in advance that (A) is always the same
   108881 ** as (B) we only store (A), then duplicate (A) when pulling
   108882 ** it out of the ephemeral table before calling VUpdate.
   108883 */
   108884 static void updateVirtualTable(
   108885   Parse *pParse,       /* The parsing context */
   108886   SrcList *pSrc,       /* The virtual table to be modified */
   108887   Table *pTab,         /* The virtual table */
   108888   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   108889   Expr *pRowid,        /* Expression used to recompute the rowid */
   108890   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   108891   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   108892   int onError          /* ON CONFLICT strategy */
   108893 ){
   108894   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
   108895   ExprList *pEList = 0;     /* The result set of the SELECT statement */
   108896   Select *pSelect = 0;      /* The SELECT statement */
   108897   Expr *pExpr;              /* Temporary expression */
   108898   int ephemTab;             /* Table holding the result of the SELECT */
   108899   int i;                    /* Loop counter */
   108900   int addr;                 /* Address of top of loop */
   108901   int iReg;                 /* First register in set passed to OP_VUpdate */
   108902   sqlite3 *db = pParse->db; /* Database connection */
   108903   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
   108904   SelectDest dest;
   108905 
   108906   /* Construct the SELECT statement that will find the new values for
   108907   ** all updated rows.
   108908   */
   108909   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
   108910   if( pRowid ){
   108911     pEList = sqlite3ExprListAppend(pParse, pEList,
   108912                                    sqlite3ExprDup(db, pRowid, 0));
   108913   }
   108914   assert( pTab->iPKey<0 );
   108915   for(i=0; i<pTab->nCol; i++){
   108916     if( aXRef[i]>=0 ){
   108917       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
   108918     }else{
   108919       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
   108920     }
   108921     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
   108922   }
   108923   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
   108924 
   108925   /* Create the ephemeral table into which the update results will
   108926   ** be stored.
   108927   */
   108928   assert( v );
   108929   ephemTab = pParse->nTab++;
   108930   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
   108931   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   108932 
   108933   /* fill the ephemeral table
   108934   */
   108935   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
   108936   sqlite3Select(pParse, pSelect, &dest);
   108937 
   108938   /* Generate code to scan the ephemeral table and call VUpdate. */
   108939   iReg = ++pParse->nMem;
   108940   pParse->nMem += pTab->nCol+1;
   108941   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
   108942   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
   108943   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
   108944   for(i=0; i<pTab->nCol; i++){
   108945     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
   108946   }
   108947   sqlite3VtabMakeWritable(pParse, pTab);
   108948   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
   108949   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   108950   sqlite3MayAbort(pParse);
   108951   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
   108952   sqlite3VdbeJumpHere(v, addr);
   108953   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
   108954 
   108955   /* Cleanup */
   108956   sqlite3SelectDelete(db, pSelect);
   108957 }
   108958 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   108959 
   108960 /************** End of update.c **********************************************/
   108961 /************** Begin file vacuum.c ******************************************/
   108962 /*
   108963 ** 2003 April 6
   108964 **
   108965 ** The author disclaims copyright to this source code.  In place of
   108966 ** a legal notice, here is a blessing:
   108967 **
   108968 **    May you do good and not evil.
   108969 **    May you find forgiveness for yourself and forgive others.
   108970 **    May you share freely, never taking more than you give.
   108971 **
   108972 *************************************************************************
   108973 ** This file contains code used to implement the VACUUM command.
   108974 **
   108975 ** Most of the code in this file may be omitted by defining the
   108976 ** SQLITE_OMIT_VACUUM macro.
   108977 */
   108978 
   108979 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   108980 /*
   108981 ** Finalize a prepared statement.  If there was an error, store the
   108982 ** text of the error message in *pzErrMsg.  Return the result code.
   108983 */
   108984 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
   108985   int rc;
   108986   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
   108987   if( rc ){
   108988     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   108989   }
   108990   return rc;
   108991 }
   108992 
   108993 /*
   108994 ** Execute zSql on database db. Return an error code.
   108995 */
   108996 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   108997   sqlite3_stmt *pStmt;
   108998   VVA_ONLY( int rc; )
   108999   if( !zSql ){
   109000     return SQLITE_NOMEM;
   109001   }
   109002   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
   109003     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   109004     return sqlite3_errcode(db);
   109005   }
   109006   VVA_ONLY( rc = ) sqlite3_step(pStmt);
   109007   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
   109008   return vacuumFinalize(db, pStmt, pzErrMsg);
   109009 }
   109010 
   109011 /*
   109012 ** Execute zSql on database db. The statement returns exactly
   109013 ** one column. Execute this as SQL on the same database.
   109014 */
   109015 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   109016   sqlite3_stmt *pStmt;
   109017   int rc;
   109018 
   109019   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   109020   if( rc!=SQLITE_OK ) return rc;
   109021 
   109022   while( SQLITE_ROW==sqlite3_step(pStmt) ){
   109023     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
   109024     if( rc!=SQLITE_OK ){
   109025       vacuumFinalize(db, pStmt, pzErrMsg);
   109026       return rc;
   109027     }
   109028   }
   109029 
   109030   return vacuumFinalize(db, pStmt, pzErrMsg);
   109031 }
   109032 
   109033 /*
   109034 ** The VACUUM command is used to clean up the database,
   109035 ** collapse free space, etc.  It is modelled after the VACUUM command
   109036 ** in PostgreSQL.  The VACUUM command works as follows:
   109037 **
   109038 **   (1)  Create a new transient database file
   109039 **   (2)  Copy all content from the database being vacuumed into
   109040 **        the new transient database file
   109041 **   (3)  Copy content from the transient database back into the
   109042 **        original database.
   109043 **
   109044 ** The transient database requires temporary disk space approximately
   109045 ** equal to the size of the original database.  The copy operation of
   109046 ** step (3) requires additional temporary disk space approximately equal
   109047 ** to the size of the original database for the rollback journal.
   109048 ** Hence, temporary disk space that is approximately 2x the size of the
   109049 ** orginal database is required.  Every page of the database is written
   109050 ** approximately 3 times:  Once for step (2) and twice for step (3).
   109051 ** Two writes per page are required in step (3) because the original
   109052 ** database content must be written into the rollback journal prior to
   109053 ** overwriting the database with the vacuumed content.
   109054 **
   109055 ** Only 1x temporary space and only 1x writes would be required if
   109056 ** the copy of step (3) were replace by deleting the original database
   109057 ** and renaming the transient database as the original.  But that will
   109058 ** not work if other processes are attached to the original database.
   109059 ** And a power loss in between deleting the original and renaming the
   109060 ** transient would cause the database file to appear to be deleted
   109061 ** following reboot.
   109062 */
   109063 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
   109064   Vdbe *v = sqlite3GetVdbe(pParse);
   109065   if( v ){
   109066     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
   109067     sqlite3VdbeUsesBtree(v, 0);
   109068   }
   109069   return;
   109070 }
   109071 
   109072 /*
   109073 ** This routine implements the OP_Vacuum opcode of the VDBE.
   109074 */
   109075 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
   109076   int rc = SQLITE_OK;     /* Return code from service routines */
   109077   Btree *pMain;           /* The database being vacuumed */
   109078   Btree *pTemp;           /* The temporary database we vacuum into */
   109079   char *zSql = 0;         /* SQL statements */
   109080   int saved_flags;        /* Saved value of the db->flags */
   109081   int saved_nChange;      /* Saved value of db->nChange */
   109082   int saved_nTotalChange; /* Saved value of db->nTotalChange */
   109083   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
   109084   Db *pDb = 0;            /* Database to detach at end of vacuum */
   109085   int isMemDb;            /* True if vacuuming a :memory: database */
   109086   int nRes;               /* Bytes of reserved space at the end of each page */
   109087   int nDb;                /* Number of attached databases */
   109088 
   109089   if( !db->autoCommit ){
   109090     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
   109091     return SQLITE_ERROR;
   109092   }
   109093   if( db->nVdbeActive>1 ){
   109094     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
   109095     return SQLITE_ERROR;
   109096   }
   109097 
   109098   /* Save the current value of the database flags so that it can be
   109099   ** restored before returning. Then set the writable-schema flag, and
   109100   ** disable CHECK and foreign key constraints.  */
   109101   saved_flags = db->flags;
   109102   saved_nChange = db->nChange;
   109103   saved_nTotalChange = db->nTotalChange;
   109104   saved_xTrace = db->xTrace;
   109105   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
   109106   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
   109107   db->xTrace = 0;
   109108 
   109109   pMain = db->aDb[0].pBt;
   109110   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
   109111 
   109112   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
   109113   ** can be set to 'off' for this file, as it is not recovered if a crash
   109114   ** occurs anyway. The integrity of the database is maintained by a
   109115   ** (possibly synchronous) transaction opened on the main database before
   109116   ** sqlite3BtreeCopyFile() is called.
   109117   **
   109118   ** An optimisation would be to use a non-journaled pager.
   109119   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
   109120   ** that actually made the VACUUM run slower.  Very little journalling
   109121   ** actually occurs when doing a vacuum since the vacuum_db is initially
   109122   ** empty.  Only the journal header is written.  Apparently it takes more
   109123   ** time to parse and run the PRAGMA to turn journalling off than it does
   109124   ** to write the journal header file.
   109125   */
   109126   nDb = db->nDb;
   109127   if( sqlite3TempInMemory(db) ){
   109128     zSql = "ATTACH ':memory:' AS vacuum_db;";
   109129   }else{
   109130     zSql = "ATTACH '' AS vacuum_db;";
   109131   }
   109132   rc = execSql(db, pzErrMsg, zSql);
   109133   if( db->nDb>nDb ){
   109134     pDb = &db->aDb[db->nDb-1];
   109135     assert( strcmp(pDb->zName,"vacuum_db")==0 );
   109136   }
   109137   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109138   pTemp = db->aDb[db->nDb-1].pBt;
   109139 
   109140   /* The call to execSql() to attach the temp database has left the file
   109141   ** locked (as there was more than one active statement when the transaction
   109142   ** to read the schema was concluded. Unlock it here so that this doesn't
   109143   ** cause problems for the call to BtreeSetPageSize() below.  */
   109144   sqlite3BtreeCommit(pTemp);
   109145 
   109146   nRes = sqlite3BtreeGetReserve(pMain);
   109147 
   109148   /* A VACUUM cannot change the pagesize of an encrypted database. */
   109149 #ifdef SQLITE_HAS_CODEC
   109150   if( db->nextPagesize ){
   109151     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   109152     int nKey;
   109153     char *zKey;
   109154     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   109155     if( nKey ) db->nextPagesize = 0;
   109156   }
   109157 #endif
   109158 
   109159   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
   109160   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109161 
   109162   /* Begin a transaction and take an exclusive lock on the main database
   109163   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
   109164   ** to ensure that we do not try to change the page-size on a WAL database.
   109165   */
   109166   rc = execSql(db, pzErrMsg, "BEGIN;");
   109167   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109168   rc = sqlite3BtreeBeginTrans(pMain, 2);
   109169   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109170 
   109171   /* Do not attempt to change the page size for a WAL database */
   109172   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
   109173                                                ==PAGER_JOURNALMODE_WAL ){
   109174     db->nextPagesize = 0;
   109175   }
   109176 
   109177   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
   109178    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
   109179    || NEVER(db->mallocFailed)
   109180   ){
   109181     rc = SQLITE_NOMEM;
   109182     goto end_of_vacuum;
   109183   }
   109184 
   109185 #ifndef SQLITE_OMIT_AUTOVACUUM
   109186   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
   109187                                            sqlite3BtreeGetAutoVacuum(pMain));
   109188 #endif
   109189 
   109190   /* Query the schema of the main database. Create a mirror schema
   109191   ** in the temporary database.
   109192   */
   109193   rc = execExecSql(db, pzErrMsg,
   109194       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
   109195       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
   109196       "   AND coalesce(rootpage,1)>0"
   109197   );
   109198   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109199   rc = execExecSql(db, pzErrMsg,
   109200       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
   109201       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
   109202   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109203   rc = execExecSql(db, pzErrMsg,
   109204       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
   109205       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
   109206   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109207 
   109208   /* Loop through the tables in the main database. For each, do
   109209   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
   109210   ** the contents to the temporary database.
   109211   */
   109212   rc = execExecSql(db, pzErrMsg,
   109213       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   109214       "|| ' SELECT * FROM main.' || quote(name) || ';'"
   109215       "FROM main.sqlite_master "
   109216       "WHERE type = 'table' AND name!='sqlite_sequence' "
   109217       "  AND coalesce(rootpage,1)>0"
   109218   );
   109219   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109220 
   109221   /* Copy over the sequence table
   109222   */
   109223   rc = execExecSql(db, pzErrMsg,
   109224       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
   109225       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
   109226   );
   109227   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109228   rc = execExecSql(db, pzErrMsg,
   109229       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   109230       "|| ' SELECT * FROM main.' || quote(name) || ';' "
   109231       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
   109232   );
   109233   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109234 
   109235 
   109236   /* Copy the triggers, views, and virtual tables from the main database
   109237   ** over to the temporary database.  None of these objects has any
   109238   ** associated storage, so all we have to do is copy their entries
   109239   ** from the SQLITE_MASTER table.
   109240   */
   109241   rc = execSql(db, pzErrMsg,
   109242       "INSERT INTO vacuum_db.sqlite_master "
   109243       "  SELECT type, name, tbl_name, rootpage, sql"
   109244       "    FROM main.sqlite_master"
   109245       "   WHERE type='view' OR type='trigger'"
   109246       "      OR (type='table' AND rootpage=0)"
   109247   );
   109248   if( rc ) goto end_of_vacuum;
   109249 
   109250   /* At this point, there is a write transaction open on both the
   109251   ** vacuum database and the main database. Assuming no error occurs,
   109252   ** both transactions are closed by this block - the main database
   109253   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
   109254   ** call to sqlite3BtreeCommit().
   109255   */
   109256   {
   109257     u32 meta;
   109258     int i;
   109259 
   109260     /* This array determines which meta meta values are preserved in the
   109261     ** vacuum.  Even entries are the meta value number and odd entries
   109262     ** are an increment to apply to the meta value after the vacuum.
   109263     ** The increment is used to increase the schema cookie so that other
   109264     ** connections to the same database will know to reread the schema.
   109265     */
   109266     static const unsigned char aCopy[] = {
   109267        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
   109268        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
   109269        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
   109270        BTREE_USER_VERSION,       0,  /* Preserve the user version */
   109271        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
   109272     };
   109273 
   109274     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
   109275     assert( 1==sqlite3BtreeIsInTrans(pMain) );
   109276 
   109277     /* Copy Btree meta values */
   109278     for(i=0; i<ArraySize(aCopy); i+=2){
   109279       /* GetMeta() and UpdateMeta() cannot fail in this context because
   109280       ** we already have page 1 loaded into cache and marked dirty. */
   109281       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
   109282       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
   109283       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
   109284     }
   109285 
   109286     rc = sqlite3BtreeCopyFile(pMain, pTemp);
   109287     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109288     rc = sqlite3BtreeCommit(pTemp);
   109289     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   109290 #ifndef SQLITE_OMIT_AUTOVACUUM
   109291     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
   109292 #endif
   109293   }
   109294 
   109295   assert( rc==SQLITE_OK );
   109296   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
   109297 
   109298 end_of_vacuum:
   109299   /* Restore the original value of db->flags */
   109300   db->flags = saved_flags;
   109301   db->nChange = saved_nChange;
   109302   db->nTotalChange = saved_nTotalChange;
   109303   db->xTrace = saved_xTrace;
   109304   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
   109305 
   109306   /* Currently there is an SQL level transaction open on the vacuum
   109307   ** database. No locks are held on any other files (since the main file
   109308   ** was committed at the btree level). So it safe to end the transaction
   109309   ** by manually setting the autoCommit flag to true and detaching the
   109310   ** vacuum database. The vacuum_db journal file is deleted when the pager
   109311   ** is closed by the DETACH.
   109312   */
   109313   db->autoCommit = 1;
   109314 
   109315   if( pDb ){
   109316     sqlite3BtreeClose(pDb->pBt);
   109317     pDb->pBt = 0;
   109318     pDb->pSchema = 0;
   109319   }
   109320 
   109321   /* This both clears the schemas and reduces the size of the db->aDb[]
   109322   ** array. */
   109323   sqlite3ResetAllSchemasOfConnection(db);
   109324 
   109325   return rc;
   109326 }
   109327 
   109328 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
   109329 
   109330 /************** End of vacuum.c **********************************************/
   109331 /************** Begin file vtab.c ********************************************/
   109332 /*
   109333 ** 2006 June 10
   109334 **
   109335 ** The author disclaims copyright to this source code.  In place of
   109336 ** a legal notice, here is a blessing:
   109337 **
   109338 **    May you do good and not evil.
   109339 **    May you find forgiveness for yourself and forgive others.
   109340 **    May you share freely, never taking more than you give.
   109341 **
   109342 *************************************************************************
   109343 ** This file contains code used to help implement virtual tables.
   109344 */
   109345 #ifndef SQLITE_OMIT_VIRTUALTABLE
   109346 
   109347 /*
   109348 ** Before a virtual table xCreate() or xConnect() method is invoked, the
   109349 ** sqlite3.pVtabCtx member variable is set to point to an instance of
   109350 ** this struct allocated on the stack. It is used by the implementation of
   109351 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
   109352 ** are invoked only from within xCreate and xConnect methods.
   109353 */
   109354 struct VtabCtx {
   109355   VTable *pVTable;    /* The virtual table being constructed */
   109356   Table *pTab;        /* The Table object to which the virtual table belongs */
   109357 };
   109358 
   109359 /*
   109360 ** The actual function that does the work of creating a new module.
   109361 ** This function implements the sqlite3_create_module() and
   109362 ** sqlite3_create_module_v2() interfaces.
   109363 */
   109364 static int createModule(
   109365   sqlite3 *db,                    /* Database in which module is registered */
   109366   const char *zName,              /* Name assigned to this module */
   109367   const sqlite3_module *pModule,  /* The definition of the module */
   109368   void *pAux,                     /* Context pointer for xCreate/xConnect */
   109369   void (*xDestroy)(void *)        /* Module destructor function */
   109370 ){
   109371   int rc = SQLITE_OK;
   109372   int nName;
   109373 
   109374   sqlite3_mutex_enter(db->mutex);
   109375   nName = sqlite3Strlen30(zName);
   109376   if( sqlite3HashFind(&db->aModule, zName, nName) ){
   109377     rc = SQLITE_MISUSE_BKPT;
   109378   }else{
   109379     Module *pMod;
   109380     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
   109381     if( pMod ){
   109382       Module *pDel;
   109383       char *zCopy = (char *)(&pMod[1]);
   109384       memcpy(zCopy, zName, nName+1);
   109385       pMod->zName = zCopy;
   109386       pMod->pModule = pModule;
   109387       pMod->pAux = pAux;
   109388       pMod->xDestroy = xDestroy;
   109389       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
   109390       assert( pDel==0 || pDel==pMod );
   109391       if( pDel ){
   109392         db->mallocFailed = 1;
   109393         sqlite3DbFree(db, pDel);
   109394       }
   109395     }
   109396   }
   109397   rc = sqlite3ApiExit(db, rc);
   109398   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
   109399 
   109400   sqlite3_mutex_leave(db->mutex);
   109401   return rc;
   109402 }
   109403 
   109404 
   109405 /*
   109406 ** External API function used to create a new virtual-table module.
   109407 */
   109408 SQLITE_API int sqlite3_create_module(
   109409   sqlite3 *db,                    /* Database in which module is registered */
   109410   const char *zName,              /* Name assigned to this module */
   109411   const sqlite3_module *pModule,  /* The definition of the module */
   109412   void *pAux                      /* Context pointer for xCreate/xConnect */
   109413 ){
   109414   return createModule(db, zName, pModule, pAux, 0);
   109415 }
   109416 
   109417 /*
   109418 ** External API function used to create a new virtual-table module.
   109419 */
   109420 SQLITE_API int sqlite3_create_module_v2(
   109421   sqlite3 *db,                    /* Database in which module is registered */
   109422   const char *zName,              /* Name assigned to this module */
   109423   const sqlite3_module *pModule,  /* The definition of the module */
   109424   void *pAux,                     /* Context pointer for xCreate/xConnect */
   109425   void (*xDestroy)(void *)        /* Module destructor function */
   109426 ){
   109427   return createModule(db, zName, pModule, pAux, xDestroy);
   109428 }
   109429 
   109430 /*
   109431 ** Lock the virtual table so that it cannot be disconnected.
   109432 ** Locks nest.  Every lock should have a corresponding unlock.
   109433 ** If an unlock is omitted, resources leaks will occur.
   109434 **
   109435 ** If a disconnect is attempted while a virtual table is locked,
   109436 ** the disconnect is deferred until all locks have been removed.
   109437 */
   109438 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
   109439   pVTab->nRef++;
   109440 }
   109441 
   109442 
   109443 /*
   109444 ** pTab is a pointer to a Table structure representing a virtual-table.
   109445 ** Return a pointer to the VTable object used by connection db to access
   109446 ** this virtual-table, if one has been created, or NULL otherwise.
   109447 */
   109448 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
   109449   VTable *pVtab;
   109450   assert( IsVirtual(pTab) );
   109451   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
   109452   return pVtab;
   109453 }
   109454 
   109455 /*
   109456 ** Decrement the ref-count on a virtual table object. When the ref-count
   109457 ** reaches zero, call the xDisconnect() method to delete the object.
   109458 */
   109459 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
   109460   sqlite3 *db = pVTab->db;
   109461 
   109462   assert( db );
   109463   assert( pVTab->nRef>0 );
   109464   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
   109465 
   109466   pVTab->nRef--;
   109467   if( pVTab->nRef==0 ){
   109468     sqlite3_vtab *p = pVTab->pVtab;
   109469     if( p ){
   109470       p->pModule->xDisconnect(p);
   109471     }
   109472     sqlite3DbFree(db, pVTab);
   109473   }
   109474 }
   109475 
   109476 /*
   109477 ** Table p is a virtual table. This function moves all elements in the
   109478 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
   109479 ** database connections to be disconnected at the next opportunity.
   109480 ** Except, if argument db is not NULL, then the entry associated with
   109481 ** connection db is left in the p->pVTable list.
   109482 */
   109483 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   109484   VTable *pRet = 0;
   109485   VTable *pVTable = p->pVTable;
   109486   p->pVTable = 0;
   109487 
   109488   /* Assert that the mutex (if any) associated with the BtShared database
   109489   ** that contains table p is held by the caller. See header comments
   109490   ** above function sqlite3VtabUnlockList() for an explanation of why
   109491   ** this makes it safe to access the sqlite3.pDisconnect list of any
   109492   ** database connection that may have an entry in the p->pVTable list.
   109493   */
   109494   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   109495 
   109496   while( pVTable ){
   109497     sqlite3 *db2 = pVTable->db;
   109498     VTable *pNext = pVTable->pNext;
   109499     assert( db2 );
   109500     if( db2==db ){
   109501       pRet = pVTable;
   109502       p->pVTable = pRet;
   109503       pRet->pNext = 0;
   109504     }else{
   109505       pVTable->pNext = db2->pDisconnect;
   109506       db2->pDisconnect = pVTable;
   109507     }
   109508     pVTable = pNext;
   109509   }
   109510 
   109511   assert( !db || pRet );
   109512   return pRet;
   109513 }
   109514 
   109515 /*
   109516 ** Table *p is a virtual table. This function removes the VTable object
   109517 ** for table *p associated with database connection db from the linked
   109518 ** list in p->pVTab. It also decrements the VTable ref count. This is
   109519 ** used when closing database connection db to free all of its VTable
   109520 ** objects without disturbing the rest of the Schema object (which may
   109521 ** be being used by other shared-cache connections).
   109522 */
   109523 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
   109524   VTable **ppVTab;
   109525 
   109526   assert( IsVirtual(p) );
   109527   assert( sqlite3BtreeHoldsAllMutexes(db) );
   109528   assert( sqlite3_mutex_held(db->mutex) );
   109529 
   109530   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
   109531     if( (*ppVTab)->db==db  ){
   109532       VTable *pVTab = *ppVTab;
   109533       *ppVTab = pVTab->pNext;
   109534       sqlite3VtabUnlock(pVTab);
   109535       break;
   109536     }
   109537   }
   109538 }
   109539 
   109540 
   109541 /*
   109542 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
   109543 **
   109544 ** This function may only be called when the mutexes associated with all
   109545 ** shared b-tree databases opened using connection db are held by the
   109546 ** caller. This is done to protect the sqlite3.pDisconnect list. The
   109547 ** sqlite3.pDisconnect list is accessed only as follows:
   109548 **
   109549 **   1) By this function. In this case, all BtShared mutexes and the mutex
   109550 **      associated with the database handle itself must be held.
   109551 **
   109552 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
   109553 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
   109554 **      associated with the database the virtual table is stored in is held
   109555 **      or, if the virtual table is stored in a non-sharable database, then
   109556 **      the database handle mutex is held.
   109557 **
   109558 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
   109559 ** by multiple threads. It is thread-safe.
   109560 */
   109561 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
   109562   VTable *p = db->pDisconnect;
   109563   db->pDisconnect = 0;
   109564 
   109565   assert( sqlite3BtreeHoldsAllMutexes(db) );
   109566   assert( sqlite3_mutex_held(db->mutex) );
   109567 
   109568   if( p ){
   109569     sqlite3ExpirePreparedStatements(db);
   109570     do {
   109571       VTable *pNext = p->pNext;
   109572       sqlite3VtabUnlock(p);
   109573       p = pNext;
   109574     }while( p );
   109575   }
   109576 }
   109577 
   109578 /*
   109579 ** Clear any and all virtual-table information from the Table record.
   109580 ** This routine is called, for example, just before deleting the Table
   109581 ** record.
   109582 **
   109583 ** Since it is a virtual-table, the Table structure contains a pointer
   109584 ** to the head of a linked list of VTable structures. Each VTable
   109585 ** structure is associated with a single sqlite3* user of the schema.
   109586 ** The reference count of the VTable structure associated with database
   109587 ** connection db is decremented immediately (which may lead to the
   109588 ** structure being xDisconnected and free). Any other VTable structures
   109589 ** in the list are moved to the sqlite3.pDisconnect list of the associated
   109590 ** database connection.
   109591 */
   109592 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
   109593   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
   109594   if( p->azModuleArg ){
   109595     int i;
   109596     for(i=0; i<p->nModuleArg; i++){
   109597       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
   109598     }
   109599     sqlite3DbFree(db, p->azModuleArg);
   109600   }
   109601 }
   109602 
   109603 /*
   109604 ** Add a new module argument to pTable->azModuleArg[].
   109605 ** The string is not copied - the pointer is stored.  The
   109606 ** string will be freed automatically when the table is
   109607 ** deleted.
   109608 */
   109609 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
   109610   int i = pTable->nModuleArg++;
   109611   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
   109612   char **azModuleArg;
   109613   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
   109614   if( azModuleArg==0 ){
   109615     int j;
   109616     for(j=0; j<i; j++){
   109617       sqlite3DbFree(db, pTable->azModuleArg[j]);
   109618     }
   109619     sqlite3DbFree(db, zArg);
   109620     sqlite3DbFree(db, pTable->azModuleArg);
   109621     pTable->nModuleArg = 0;
   109622   }else{
   109623     azModuleArg[i] = zArg;
   109624     azModuleArg[i+1] = 0;
   109625   }
   109626   pTable->azModuleArg = azModuleArg;
   109627 }
   109628 
   109629 /*
   109630 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
   109631 ** statement.  The module name has been parsed, but the optional list
   109632 ** of parameters that follow the module name are still pending.
   109633 */
   109634 SQLITE_PRIVATE void sqlite3VtabBeginParse(
   109635   Parse *pParse,        /* Parsing context */
   109636   Token *pName1,        /* Name of new table, or database name */
   109637   Token *pName2,        /* Name of new table or NULL */
   109638   Token *pModuleName,   /* Name of the module for the virtual table */
   109639   int ifNotExists       /* No error if the table already exists */
   109640 ){
   109641   int iDb;              /* The database the table is being created in */
   109642   Table *pTable;        /* The new virtual table */
   109643   sqlite3 *db;          /* Database connection */
   109644 
   109645   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
   109646   pTable = pParse->pNewTable;
   109647   if( pTable==0 ) return;
   109648   assert( 0==pTable->pIndex );
   109649 
   109650   db = pParse->db;
   109651   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
   109652   assert( iDb>=0 );
   109653 
   109654   pTable->tabFlags |= TF_Virtual;
   109655   pTable->nModuleArg = 0;
   109656   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
   109657   addModuleArgument(db, pTable, 0);
   109658   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
   109659   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
   109660 
   109661 #ifndef SQLITE_OMIT_AUTHORIZATION
   109662   /* Creating a virtual table invokes the authorization callback twice.
   109663   ** The first invocation, to obtain permission to INSERT a row into the
   109664   ** sqlite_master table, has already been made by sqlite3StartTable().
   109665   ** The second call, to obtain permission to create the table, is made now.
   109666   */
   109667   if( pTable->azModuleArg ){
   109668     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
   109669             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
   109670   }
   109671 #endif
   109672 }
   109673 
   109674 /*
   109675 ** This routine takes the module argument that has been accumulating
   109676 ** in pParse->zArg[] and appends it to the list of arguments on the
   109677 ** virtual table currently under construction in pParse->pTable.
   109678 */
   109679 static void addArgumentToVtab(Parse *pParse){
   109680   if( pParse->sArg.z && pParse->pNewTable ){
   109681     const char *z = (const char*)pParse->sArg.z;
   109682     int n = pParse->sArg.n;
   109683     sqlite3 *db = pParse->db;
   109684     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
   109685   }
   109686 }
   109687 
   109688 /*
   109689 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
   109690 ** has been completely parsed.
   109691 */
   109692 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   109693   Table *pTab = pParse->pNewTable;  /* The table being constructed */
   109694   sqlite3 *db = pParse->db;         /* The database connection */
   109695 
   109696   if( pTab==0 ) return;
   109697   addArgumentToVtab(pParse);
   109698   pParse->sArg.z = 0;
   109699   if( pTab->nModuleArg<1 ) return;
   109700 
   109701   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   109702   ** first time (in other words if the virtual table is actually being
   109703   ** created now instead of just being read out of sqlite_master) then
   109704   ** do additional initialization work and store the statement text
   109705   ** in the sqlite_master table.
   109706   */
   109707   if( !db->init.busy ){
   109708     char *zStmt;
   109709     char *zWhere;
   109710     int iDb;
   109711     Vdbe *v;
   109712 
   109713     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
   109714     if( pEnd ){
   109715       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
   109716     }
   109717     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
   109718 
   109719     /* A slot for the record has already been allocated in the
   109720     ** SQLITE_MASTER table.  We just need to update that slot with all
   109721     ** the information we've collected.
   109722     **
   109723     ** The VM register number pParse->regRowid holds the rowid of an
   109724     ** entry in the sqlite_master table tht was created for this vtab
   109725     ** by sqlite3StartTable().
   109726     */
   109727     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   109728     sqlite3NestedParse(pParse,
   109729       "UPDATE %Q.%s "
   109730          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
   109731        "WHERE rowid=#%d",
   109732       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   109733       pTab->zName,
   109734       pTab->zName,
   109735       zStmt,
   109736       pParse->regRowid
   109737     );
   109738     sqlite3DbFree(db, zStmt);
   109739     v = sqlite3GetVdbe(pParse);
   109740     sqlite3ChangeCookie(pParse, iDb);
   109741 
   109742     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   109743     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
   109744     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   109745     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
   109746                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
   109747   }
   109748 
   109749   /* If we are rereading the sqlite_master table create the in-memory
   109750   ** record of the table. The xConnect() method is not called until
   109751   ** the first time the virtual table is used in an SQL statement. This
   109752   ** allows a schema that contains virtual tables to be loaded before
   109753   ** the required virtual table implementations are registered.  */
   109754   else {
   109755     Table *pOld;
   109756     Schema *pSchema = pTab->pSchema;
   109757     const char *zName = pTab->zName;
   109758     int nName = sqlite3Strlen30(zName);
   109759     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
   109760     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
   109761     if( pOld ){
   109762       db->mallocFailed = 1;
   109763       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   109764       return;
   109765     }
   109766     pParse->pNewTable = 0;
   109767   }
   109768 }
   109769 
   109770 /*
   109771 ** The parser calls this routine when it sees the first token
   109772 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
   109773 */
   109774 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
   109775   addArgumentToVtab(pParse);
   109776   pParse->sArg.z = 0;
   109777   pParse->sArg.n = 0;
   109778 }
   109779 
   109780 /*
   109781 ** The parser calls this routine for each token after the first token
   109782 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
   109783 */
   109784 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
   109785   Token *pArg = &pParse->sArg;
   109786   if( pArg->z==0 ){
   109787     pArg->z = p->z;
   109788     pArg->n = p->n;
   109789   }else{
   109790     assert(pArg->z < p->z);
   109791     pArg->n = (int)(&p->z[p->n] - pArg->z);
   109792   }
   109793 }
   109794 
   109795 /*
   109796 ** Invoke a virtual table constructor (either xCreate or xConnect). The
   109797 ** pointer to the function to invoke is passed as the fourth parameter
   109798 ** to this procedure.
   109799 */
   109800 static int vtabCallConstructor(
   109801   sqlite3 *db,
   109802   Table *pTab,
   109803   Module *pMod,
   109804   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
   109805   char **pzErr
   109806 ){
   109807   VtabCtx sCtx, *pPriorCtx;
   109808   VTable *pVTable;
   109809   int rc;
   109810   const char *const*azArg = (const char *const*)pTab->azModuleArg;
   109811   int nArg = pTab->nModuleArg;
   109812   char *zErr = 0;
   109813   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
   109814   int iDb;
   109815 
   109816   if( !zModuleName ){
   109817     return SQLITE_NOMEM;
   109818   }
   109819 
   109820   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
   109821   if( !pVTable ){
   109822     sqlite3DbFree(db, zModuleName);
   109823     return SQLITE_NOMEM;
   109824   }
   109825   pVTable->db = db;
   109826   pVTable->pMod = pMod;
   109827 
   109828   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   109829   pTab->azModuleArg[1] = db->aDb[iDb].zName;
   109830 
   109831   /* Invoke the virtual table constructor */
   109832   assert( &db->pVtabCtx );
   109833   assert( xConstruct );
   109834   sCtx.pTab = pTab;
   109835   sCtx.pVTable = pVTable;
   109836   pPriorCtx = db->pVtabCtx;
   109837   db->pVtabCtx = &sCtx;
   109838   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   109839   db->pVtabCtx = pPriorCtx;
   109840   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   109841 
   109842   if( SQLITE_OK!=rc ){
   109843     if( zErr==0 ){
   109844       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   109845     }else {
   109846       *pzErr = sqlite3MPrintf(db, "%s", zErr);
   109847       sqlite3_free(zErr);
   109848     }
   109849     sqlite3DbFree(db, pVTable);
   109850   }else if( ALWAYS(pVTable->pVtab) ){
   109851     /* Justification of ALWAYS():  A correct vtab constructor must allocate
   109852     ** the sqlite3_vtab object if successful.  */
   109853     pVTable->pVtab->pModule = pMod->pModule;
   109854     pVTable->nRef = 1;
   109855     if( sCtx.pTab ){
   109856       const char *zFormat = "vtable constructor did not declare schema: %s";
   109857       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
   109858       sqlite3VtabUnlock(pVTable);
   109859       rc = SQLITE_ERROR;
   109860     }else{
   109861       int iCol;
   109862       /* If everything went according to plan, link the new VTable structure
   109863       ** into the linked list headed by pTab->pVTable. Then loop through the
   109864       ** columns of the table to see if any of them contain the token "hidden".
   109865       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
   109866       ** the type string.  */
   109867       pVTable->pNext = pTab->pVTable;
   109868       pTab->pVTable = pVTable;
   109869 
   109870       for(iCol=0; iCol<pTab->nCol; iCol++){
   109871         char *zType = pTab->aCol[iCol].zType;
   109872         int nType;
   109873         int i = 0;
   109874         if( !zType ) continue;
   109875         nType = sqlite3Strlen30(zType);
   109876         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
   109877           for(i=0; i<nType; i++){
   109878             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
   109879              && (zType[i+7]=='\0' || zType[i+7]==' ')
   109880             ){
   109881               i++;
   109882               break;
   109883             }
   109884           }
   109885         }
   109886         if( i<nType ){
   109887           int j;
   109888           int nDel = 6 + (zType[i+6] ? 1 : 0);
   109889           for(j=i; (j+nDel)<=nType; j++){
   109890             zType[j] = zType[j+nDel];
   109891           }
   109892           if( zType[i]=='\0' && i>0 ){
   109893             assert(zType[i-1]==' ');
   109894             zType[i-1] = '\0';
   109895           }
   109896           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
   109897         }
   109898       }
   109899     }
   109900   }
   109901 
   109902   sqlite3DbFree(db, zModuleName);
   109903   return rc;
   109904 }
   109905 
   109906 /*
   109907 ** This function is invoked by the parser to call the xConnect() method
   109908 ** of the virtual table pTab. If an error occurs, an error code is returned
   109909 ** and an error left in pParse.
   109910 **
   109911 ** This call is a no-op if table pTab is not a virtual table.
   109912 */
   109913 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
   109914   sqlite3 *db = pParse->db;
   109915   const char *zMod;
   109916   Module *pMod;
   109917   int rc;
   109918 
   109919   assert( pTab );
   109920   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
   109921     return SQLITE_OK;
   109922   }
   109923 
   109924   /* Locate the required virtual table module */
   109925   zMod = pTab->azModuleArg[0];
   109926   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   109927 
   109928   if( !pMod ){
   109929     const char *zModule = pTab->azModuleArg[0];
   109930     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
   109931     rc = SQLITE_ERROR;
   109932   }else{
   109933     char *zErr = 0;
   109934     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
   109935     if( rc!=SQLITE_OK ){
   109936       sqlite3ErrorMsg(pParse, "%s", zErr);
   109937     }
   109938     sqlite3DbFree(db, zErr);
   109939   }
   109940 
   109941   return rc;
   109942 }
   109943 /*
   109944 ** Grow the db->aVTrans[] array so that there is room for at least one
   109945 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
   109946 */
   109947 static int growVTrans(sqlite3 *db){
   109948   const int ARRAY_INCR = 5;
   109949 
   109950   /* Grow the sqlite3.aVTrans array if required */
   109951   if( (db->nVTrans%ARRAY_INCR)==0 ){
   109952     VTable **aVTrans;
   109953     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
   109954     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
   109955     if( !aVTrans ){
   109956       return SQLITE_NOMEM;
   109957     }
   109958     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
   109959     db->aVTrans = aVTrans;
   109960   }
   109961 
   109962   return SQLITE_OK;
   109963 }
   109964 
   109965 /*
   109966 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
   109967 ** have already been reserved using growVTrans().
   109968 */
   109969 static void addToVTrans(sqlite3 *db, VTable *pVTab){
   109970   /* Add pVtab to the end of sqlite3.aVTrans */
   109971   db->aVTrans[db->nVTrans++] = pVTab;
   109972   sqlite3VtabLock(pVTab);
   109973 }
   109974 
   109975 /*
   109976 ** This function is invoked by the vdbe to call the xCreate method
   109977 ** of the virtual table named zTab in database iDb.
   109978 **
   109979 ** If an error occurs, *pzErr is set to point an an English language
   109980 ** description of the error and an SQLITE_XXX error code is returned.
   109981 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
   109982 */
   109983 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
   109984   int rc = SQLITE_OK;
   109985   Table *pTab;
   109986   Module *pMod;
   109987   const char *zMod;
   109988 
   109989   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   109990   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
   109991 
   109992   /* Locate the required virtual table module */
   109993   zMod = pTab->azModuleArg[0];
   109994   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   109995 
   109996   /* If the module has been registered and includes a Create method,
   109997   ** invoke it now. If the module has not been registered, return an
   109998   ** error. Otherwise, do nothing.
   109999   */
   110000   if( !pMod ){
   110001     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
   110002     rc = SQLITE_ERROR;
   110003   }else{
   110004     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
   110005   }
   110006 
   110007   /* Justification of ALWAYS():  The xConstructor method is required to
   110008   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
   110009   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
   110010     rc = growVTrans(db);
   110011     if( rc==SQLITE_OK ){
   110012       addToVTrans(db, sqlite3GetVTable(db, pTab));
   110013     }
   110014   }
   110015 
   110016   return rc;
   110017 }
   110018 
   110019 /*
   110020 ** This function is used to set the schema of a virtual table.  It is only
   110021 ** valid to call this function from within the xCreate() or xConnect() of a
   110022 ** virtual table module.
   110023 */
   110024 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   110025   Parse *pParse;
   110026 
   110027   int rc = SQLITE_OK;
   110028   Table *pTab;
   110029   char *zErr = 0;
   110030 
   110031   sqlite3_mutex_enter(db->mutex);
   110032   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
   110033     sqlite3Error(db, SQLITE_MISUSE, 0);
   110034     sqlite3_mutex_leave(db->mutex);
   110035     return SQLITE_MISUSE_BKPT;
   110036   }
   110037   assert( (pTab->tabFlags & TF_Virtual)!=0 );
   110038 
   110039   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   110040   if( pParse==0 ){
   110041     rc = SQLITE_NOMEM;
   110042   }else{
   110043     pParse->declareVtab = 1;
   110044     pParse->db = db;
   110045     pParse->nQueryLoop = 1;
   110046 
   110047     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
   110048      && pParse->pNewTable
   110049      && !db->mallocFailed
   110050      && !pParse->pNewTable->pSelect
   110051      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
   110052     ){
   110053       if( !pTab->aCol ){
   110054         pTab->aCol = pParse->pNewTable->aCol;
   110055         pTab->nCol = pParse->pNewTable->nCol;
   110056         pParse->pNewTable->nCol = 0;
   110057         pParse->pNewTable->aCol = 0;
   110058       }
   110059       db->pVtabCtx->pTab = 0;
   110060     }else{
   110061       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
   110062       sqlite3DbFree(db, zErr);
   110063       rc = SQLITE_ERROR;
   110064     }
   110065     pParse->declareVtab = 0;
   110066 
   110067     if( pParse->pVdbe ){
   110068       sqlite3VdbeFinalize(pParse->pVdbe);
   110069     }
   110070     sqlite3DeleteTable(db, pParse->pNewTable);
   110071     sqlite3ParserReset(pParse);
   110072     sqlite3StackFree(db, pParse);
   110073   }
   110074 
   110075   assert( (rc&0xff)==rc );
   110076   rc = sqlite3ApiExit(db, rc);
   110077   sqlite3_mutex_leave(db->mutex);
   110078   return rc;
   110079 }
   110080 
   110081 /*
   110082 ** This function is invoked by the vdbe to call the xDestroy method
   110083 ** of the virtual table named zTab in database iDb. This occurs
   110084 ** when a DROP TABLE is mentioned.
   110085 **
   110086 ** This call is a no-op if zTab is not a virtual table.
   110087 */
   110088 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
   110089   int rc = SQLITE_OK;
   110090   Table *pTab;
   110091 
   110092   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   110093   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
   110094     VTable *p = vtabDisconnectAll(db, pTab);
   110095 
   110096     assert( rc==SQLITE_OK );
   110097     rc = p->pMod->pModule->xDestroy(p->pVtab);
   110098 
   110099     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
   110100     if( rc==SQLITE_OK ){
   110101       assert( pTab->pVTable==p && p->pNext==0 );
   110102       p->pVtab = 0;
   110103       pTab->pVTable = 0;
   110104       sqlite3VtabUnlock(p);
   110105     }
   110106   }
   110107 
   110108   return rc;
   110109 }
   110110 
   110111 /*
   110112 ** This function invokes either the xRollback or xCommit method
   110113 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
   110114 ** called is identified by the second argument, "offset", which is
   110115 ** the offset of the method to call in the sqlite3_module structure.
   110116 **
   110117 ** The array is cleared after invoking the callbacks.
   110118 */
   110119 static void callFinaliser(sqlite3 *db, int offset){
   110120   int i;
   110121   if( db->aVTrans ){
   110122     for(i=0; i<db->nVTrans; i++){
   110123       VTable *pVTab = db->aVTrans[i];
   110124       sqlite3_vtab *p = pVTab->pVtab;
   110125       if( p ){
   110126         int (*x)(sqlite3_vtab *);
   110127         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
   110128         if( x ) x(p);
   110129       }
   110130       pVTab->iSavepoint = 0;
   110131       sqlite3VtabUnlock(pVTab);
   110132     }
   110133     sqlite3DbFree(db, db->aVTrans);
   110134     db->nVTrans = 0;
   110135     db->aVTrans = 0;
   110136   }
   110137 }
   110138 
   110139 /*
   110140 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
   110141 ** array. Return the error code for the first error that occurs, or
   110142 ** SQLITE_OK if all xSync operations are successful.
   110143 **
   110144 ** If an error message is available, leave it in p->zErrMsg.
   110145 */
   110146 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
   110147   int i;
   110148   int rc = SQLITE_OK;
   110149   VTable **aVTrans = db->aVTrans;
   110150 
   110151   db->aVTrans = 0;
   110152   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   110153     int (*x)(sqlite3_vtab *);
   110154     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
   110155     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
   110156       rc = x(pVtab);
   110157       sqlite3VtabImportErrmsg(p, pVtab);
   110158     }
   110159   }
   110160   db->aVTrans = aVTrans;
   110161   return rc;
   110162 }
   110163 
   110164 /*
   110165 ** Invoke the xRollback method of all virtual tables in the
   110166 ** sqlite3.aVTrans array. Then clear the array itself.
   110167 */
   110168 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
   110169   callFinaliser(db, offsetof(sqlite3_module,xRollback));
   110170   return SQLITE_OK;
   110171 }
   110172 
   110173 /*
   110174 ** Invoke the xCommit method of all virtual tables in the
   110175 ** sqlite3.aVTrans array. Then clear the array itself.
   110176 */
   110177 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
   110178   callFinaliser(db, offsetof(sqlite3_module,xCommit));
   110179   return SQLITE_OK;
   110180 }
   110181 
   110182 /*
   110183 ** If the virtual table pVtab supports the transaction interface
   110184 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
   110185 ** not currently open, invoke the xBegin method now.
   110186 **
   110187 ** If the xBegin call is successful, place the sqlite3_vtab pointer
   110188 ** in the sqlite3.aVTrans array.
   110189 */
   110190 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
   110191   int rc = SQLITE_OK;
   110192   const sqlite3_module *pModule;
   110193 
   110194   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
   110195   ** than zero, then this function is being called from within a
   110196   ** virtual module xSync() callback. It is illegal to write to
   110197   ** virtual module tables in this case, so return SQLITE_LOCKED.
   110198   */
   110199   if( sqlite3VtabInSync(db) ){
   110200     return SQLITE_LOCKED;
   110201   }
   110202   if( !pVTab ){
   110203     return SQLITE_OK;
   110204   }
   110205   pModule = pVTab->pVtab->pModule;
   110206 
   110207   if( pModule->xBegin ){
   110208     int i;
   110209 
   110210     /* If pVtab is already in the aVTrans array, return early */
   110211     for(i=0; i<db->nVTrans; i++){
   110212       if( db->aVTrans[i]==pVTab ){
   110213         return SQLITE_OK;
   110214       }
   110215     }
   110216 
   110217     /* Invoke the xBegin method. If successful, add the vtab to the
   110218     ** sqlite3.aVTrans[] array. */
   110219     rc = growVTrans(db);
   110220     if( rc==SQLITE_OK ){
   110221       rc = pModule->xBegin(pVTab->pVtab);
   110222       if( rc==SQLITE_OK ){
   110223         addToVTrans(db, pVTab);
   110224       }
   110225     }
   110226   }
   110227   return rc;
   110228 }
   110229 
   110230 /*
   110231 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
   110232 ** virtual tables that currently have an open transaction. Pass iSavepoint
   110233 ** as the second argument to the virtual table method invoked.
   110234 **
   110235 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
   110236 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
   110237 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
   110238 ** an open transaction is invoked.
   110239 **
   110240 ** If any virtual table method returns an error code other than SQLITE_OK,
   110241 ** processing is abandoned and the error returned to the caller of this
   110242 ** function immediately. If all calls to virtual table methods are successful,
   110243 ** SQLITE_OK is returned.
   110244 */
   110245 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
   110246   int rc = SQLITE_OK;
   110247 
   110248   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
   110249   assert( iSavepoint>=0 );
   110250   if( db->aVTrans ){
   110251     int i;
   110252     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   110253       VTable *pVTab = db->aVTrans[i];
   110254       const sqlite3_module *pMod = pVTab->pMod->pModule;
   110255       if( pVTab->pVtab && pMod->iVersion>=2 ){
   110256         int (*xMethod)(sqlite3_vtab *, int);
   110257         switch( op ){
   110258           case SAVEPOINT_BEGIN:
   110259             xMethod = pMod->xSavepoint;
   110260             pVTab->iSavepoint = iSavepoint+1;
   110261             break;
   110262           case SAVEPOINT_ROLLBACK:
   110263             xMethod = pMod->xRollbackTo;
   110264             break;
   110265           default:
   110266             xMethod = pMod->xRelease;
   110267             break;
   110268         }
   110269         if( xMethod && pVTab->iSavepoint>iSavepoint ){
   110270           rc = xMethod(pVTab->pVtab, iSavepoint);
   110271         }
   110272       }
   110273     }
   110274   }
   110275   return rc;
   110276 }
   110277 
   110278 /*
   110279 ** The first parameter (pDef) is a function implementation.  The
   110280 ** second parameter (pExpr) is the first argument to this function.
   110281 ** If pExpr is a column in a virtual table, then let the virtual
   110282 ** table implementation have an opportunity to overload the function.
   110283 **
   110284 ** This routine is used to allow virtual table implementations to
   110285 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
   110286 **
   110287 ** Return either the pDef argument (indicating no change) or a
   110288 ** new FuncDef structure that is marked as ephemeral using the
   110289 ** SQLITE_FUNC_EPHEM flag.
   110290 */
   110291 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   110292   sqlite3 *db,    /* Database connection for reporting malloc problems */
   110293   FuncDef *pDef,  /* Function to possibly overload */
   110294   int nArg,       /* Number of arguments to the function */
   110295   Expr *pExpr     /* First argument to the function */
   110296 ){
   110297   Table *pTab;
   110298   sqlite3_vtab *pVtab;
   110299   sqlite3_module *pMod;
   110300   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
   110301   void *pArg = 0;
   110302   FuncDef *pNew;
   110303   int rc = 0;
   110304   char *zLowerName;
   110305   unsigned char *z;
   110306 
   110307 
   110308   /* Check to see the left operand is a column in a virtual table */
   110309   if( NEVER(pExpr==0) ) return pDef;
   110310   if( pExpr->op!=TK_COLUMN ) return pDef;
   110311   pTab = pExpr->pTab;
   110312   if( NEVER(pTab==0) ) return pDef;
   110313   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
   110314   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
   110315   assert( pVtab!=0 );
   110316   assert( pVtab->pModule!=0 );
   110317   pMod = (sqlite3_module *)pVtab->pModule;
   110318   if( pMod->xFindFunction==0 ) return pDef;
   110319 
   110320   /* Call the xFindFunction method on the virtual table implementation
   110321   ** to see if the implementation wants to overload this function
   110322   */
   110323   zLowerName = sqlite3DbStrDup(db, pDef->zName);
   110324   if( zLowerName ){
   110325     for(z=(unsigned char*)zLowerName; *z; z++){
   110326       *z = sqlite3UpperToLower[*z];
   110327     }
   110328     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
   110329     sqlite3DbFree(db, zLowerName);
   110330   }
   110331   if( rc==0 ){
   110332     return pDef;
   110333   }
   110334 
   110335   /* Create a new ephemeral function definition for the overloaded
   110336   ** function */
   110337   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
   110338                              + sqlite3Strlen30(pDef->zName) + 1);
   110339   if( pNew==0 ){
   110340     return pDef;
   110341   }
   110342   *pNew = *pDef;
   110343   pNew->zName = (char *)&pNew[1];
   110344   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
   110345   pNew->xFunc = xFunc;
   110346   pNew->pUserData = pArg;
   110347   pNew->funcFlags |= SQLITE_FUNC_EPHEM;
   110348   return pNew;
   110349 }
   110350 
   110351 /*
   110352 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
   110353 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
   110354 ** array if it is missing.  If pTab is already in the array, this routine
   110355 ** is a no-op.
   110356 */
   110357 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
   110358   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   110359   int i, n;
   110360   Table **apVtabLock;
   110361 
   110362   assert( IsVirtual(pTab) );
   110363   for(i=0; i<pToplevel->nVtabLock; i++){
   110364     if( pTab==pToplevel->apVtabLock[i] ) return;
   110365   }
   110366   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
   110367   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
   110368   if( apVtabLock ){
   110369     pToplevel->apVtabLock = apVtabLock;
   110370     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   110371   }else{
   110372     pToplevel->db->mallocFailed = 1;
   110373   }
   110374 }
   110375 
   110376 /*
   110377 ** Return the ON CONFLICT resolution mode in effect for the virtual
   110378 ** table update operation currently in progress.
   110379 **
   110380 ** The results of this routine are undefined unless it is called from
   110381 ** within an xUpdate method.
   110382 */
   110383 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
   110384   static const unsigned char aMap[] = {
   110385     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
   110386   };
   110387   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
   110388   assert( OE_Ignore==4 && OE_Replace==5 );
   110389   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
   110390   return (int)aMap[db->vtabOnConflict-1];
   110391 }
   110392 
   110393 /*
   110394 ** Call from within the xCreate() or xConnect() methods to provide
   110395 ** the SQLite core with additional information about the behavior
   110396 ** of the virtual table being implemented.
   110397 */
   110398 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
   110399   va_list ap;
   110400   int rc = SQLITE_OK;
   110401 
   110402   sqlite3_mutex_enter(db->mutex);
   110403 
   110404   va_start(ap, op);
   110405   switch( op ){
   110406     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
   110407       VtabCtx *p = db->pVtabCtx;
   110408       if( !p ){
   110409         rc = SQLITE_MISUSE_BKPT;
   110410       }else{
   110411         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
   110412         p->pVTable->bConstraint = (u8)va_arg(ap, int);
   110413       }
   110414       break;
   110415     }
   110416     default:
   110417       rc = SQLITE_MISUSE_BKPT;
   110418       break;
   110419   }
   110420   va_end(ap);
   110421 
   110422   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
   110423   sqlite3_mutex_leave(db->mutex);
   110424   return rc;
   110425 }
   110426 
   110427 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   110428 
   110429 /************** End of vtab.c ************************************************/
   110430 /************** Begin file where.c *******************************************/
   110431 /*
   110432 ** 2001 September 15
   110433 **
   110434 ** The author disclaims copyright to this source code.  In place of
   110435 ** a legal notice, here is a blessing:
   110436 **
   110437 **    May you do good and not evil.
   110438 **    May you find forgiveness for yourself and forgive others.
   110439 **    May you share freely, never taking more than you give.
   110440 **
   110441 *************************************************************************
   110442 ** This module contains C code that generates VDBE code used to process
   110443 ** the WHERE clause of SQL statements.  This module is responsible for
   110444 ** generating the code that loops through a table looking for applicable
   110445 ** rows.  Indices are selected and used to speed the search when doing
   110446 ** so is applicable.  Because this module is responsible for selecting
   110447 ** indices, you might also think of this module as the "query optimizer".
   110448 */
   110449 /************** Include whereInt.h in the middle of where.c ******************/
   110450 /************** Begin file whereInt.h ****************************************/
   110451 /*
   110452 ** 2013-11-12
   110453 **
   110454 ** The author disclaims copyright to this source code.  In place of
   110455 ** a legal notice, here is a blessing:
   110456 **
   110457 **    May you do good and not evil.
   110458 **    May you find forgiveness for yourself and forgive others.
   110459 **    May you share freely, never taking more than you give.
   110460 **
   110461 *************************************************************************
   110462 **
   110463 ** This file contains structure and macro definitions for the query
   110464 ** planner logic in "where.c".  These definitions are broken out into
   110465 ** a separate source file for easier editing.
   110466 */
   110467 
   110468 /*
   110469 ** Trace output macros
   110470 */
   110471 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   110472 /***/ int sqlite3WhereTrace = 0;
   110473 #endif
   110474 #if defined(SQLITE_DEBUG) \
   110475     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
   110476 # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
   110477 # define WHERETRACE_ENABLED 1
   110478 #else
   110479 # define WHERETRACE(K,X)
   110480 #endif
   110481 
   110482 /* Forward references
   110483 */
   110484 typedef struct WhereClause WhereClause;
   110485 typedef struct WhereMaskSet WhereMaskSet;
   110486 typedef struct WhereOrInfo WhereOrInfo;
   110487 typedef struct WhereAndInfo WhereAndInfo;
   110488 typedef struct WhereLevel WhereLevel;
   110489 typedef struct WhereLoop WhereLoop;
   110490 typedef struct WherePath WherePath;
   110491 typedef struct WhereTerm WhereTerm;
   110492 typedef struct WhereLoopBuilder WhereLoopBuilder;
   110493 typedef struct WhereScan WhereScan;
   110494 typedef struct WhereOrCost WhereOrCost;
   110495 typedef struct WhereOrSet WhereOrSet;
   110496 
   110497 /*
   110498 ** This object contains information needed to implement a single nested
   110499 ** loop in WHERE clause.
   110500 **
   110501 ** Contrast this object with WhereLoop.  This object describes the
   110502 ** implementation of the loop.  WhereLoop describes the algorithm.
   110503 ** This object contains a pointer to the WhereLoop algorithm as one of
   110504 ** its elements.
   110505 **
   110506 ** The WhereInfo object contains a single instance of this object for
   110507 ** each term in the FROM clause (which is to say, for each of the
   110508 ** nested loops as implemented).  The order of WhereLevel objects determines
   110509 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
   110510 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
   110511 */
   110512 struct WhereLevel {
   110513   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
   110514   int iTabCur;          /* The VDBE cursor used to access the table */
   110515   int iIdxCur;          /* The VDBE cursor used to access pIdx */
   110516   int addrBrk;          /* Jump here to break out of the loop */
   110517   int addrNxt;          /* Jump here to start the next IN combination */
   110518   int addrSkip;         /* Jump here for next iteration of skip-scan */
   110519   int addrCont;         /* Jump here to continue with the next loop cycle */
   110520   int addrFirst;        /* First instruction of interior of the loop */
   110521   int addrBody;         /* Beginning of the body of this loop */
   110522   u8 iFrom;             /* Which entry in the FROM clause */
   110523   u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
   110524   int p1, p2;           /* Operands of the opcode used to ends the loop */
   110525   union {               /* Information that depends on pWLoop->wsFlags */
   110526     struct {
   110527       int nIn;              /* Number of entries in aInLoop[] */
   110528       struct InLoop {
   110529         int iCur;              /* The VDBE cursor used by this IN operator */
   110530         int addrInTop;         /* Top of the IN loop */
   110531         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
   110532       } *aInLoop;           /* Information about each nested IN operator */
   110533     } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
   110534     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
   110535   } u;
   110536   struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
   110537   Bitmask notReady;          /* FROM entries not usable at this level */
   110538 };
   110539 
   110540 /*
   110541 ** Each instance of this object represents an algorithm for evaluating one
   110542 ** term of a join.  Every term of the FROM clause will have at least
   110543 ** one corresponding WhereLoop object (unless INDEXED BY constraints
   110544 ** prevent a query solution - which is an error) and many terms of the
   110545 ** FROM clause will have multiple WhereLoop objects, each describing a
   110546 ** potential way of implementing that FROM-clause term, together with
   110547 ** dependencies and cost estimates for using the chosen algorithm.
   110548 **
   110549 ** Query planning consists of building up a collection of these WhereLoop
   110550 ** objects, then computing a particular sequence of WhereLoop objects, with
   110551 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
   110552 ** and that minimize the overall cost.
   110553 */
   110554 struct WhereLoop {
   110555   Bitmask prereq;       /* Bitmask of other loops that must run first */
   110556   Bitmask maskSelf;     /* Bitmask identifying table iTab */
   110557 #ifdef SQLITE_DEBUG
   110558   char cId;             /* Symbolic ID of this loop for debugging use */
   110559 #endif
   110560   u8 iTab;              /* Position in FROM clause of table for this loop */
   110561   u8 iSortIdx;          /* Sorting index number.  0==None */
   110562   LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
   110563   LogEst rRun;          /* Cost of running each loop */
   110564   LogEst nOut;          /* Estimated number of output rows */
   110565   union {
   110566     struct {               /* Information for internal btree tables */
   110567       u16 nEq;               /* Number of equality constraints */
   110568       u16 nSkip;             /* Number of initial index columns to skip */
   110569       Index *pIndex;         /* Index used, or NULL */
   110570     } btree;
   110571     struct {               /* Information for virtual tables */
   110572       int idxNum;            /* Index number */
   110573       u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
   110574       i8 isOrdered;          /* True if satisfies ORDER BY */
   110575       u16 omitMask;          /* Terms that may be omitted */
   110576       char *idxStr;          /* Index identifier string */
   110577     } vtab;
   110578   } u;
   110579   u32 wsFlags;          /* WHERE_* flags describing the plan */
   110580   u16 nLTerm;           /* Number of entries in aLTerm[] */
   110581   /**** whereLoopXfer() copies fields above ***********************/
   110582 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
   110583   u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
   110584   WhereTerm **aLTerm;   /* WhereTerms used */
   110585   WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
   110586   WhereTerm *aLTermSpace[4];  /* Initial aLTerm[] space */
   110587 };
   110588 
   110589 /* This object holds the prerequisites and the cost of running a
   110590 ** subquery on one operand of an OR operator in the WHERE clause.
   110591 ** See WhereOrSet for additional information
   110592 */
   110593 struct WhereOrCost {
   110594   Bitmask prereq;     /* Prerequisites */
   110595   LogEst rRun;        /* Cost of running this subquery */
   110596   LogEst nOut;        /* Number of outputs for this subquery */
   110597 };
   110598 
   110599 /* The WhereOrSet object holds a set of possible WhereOrCosts that
   110600 ** correspond to the subquery(s) of OR-clause processing.  Only the
   110601 ** best N_OR_COST elements are retained.
   110602 */
   110603 #define N_OR_COST 3
   110604 struct WhereOrSet {
   110605   u16 n;                      /* Number of valid a[] entries */
   110606   WhereOrCost a[N_OR_COST];   /* Set of best costs */
   110607 };
   110608 
   110609 
   110610 /* Forward declaration of methods */
   110611 static int whereLoopResize(sqlite3*, WhereLoop*, int);
   110612 
   110613 /*
   110614 ** Each instance of this object holds a sequence of WhereLoop objects
   110615 ** that implement some or all of a query plan.
   110616 **
   110617 ** Think of each WhereLoop object as a node in a graph with arcs
   110618 ** showing dependencies and costs for travelling between nodes.  (That is
   110619 ** not a completely accurate description because WhereLoop costs are a
   110620 ** vector, not a scalar, and because dependencies are many-to-one, not
   110621 ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
   110622 ** Then a WherePath object is a path through the graph that visits some
   110623 ** or all of the WhereLoop objects once.
   110624 **
   110625 ** The "solver" works by creating the N best WherePath objects of length
   110626 ** 1.  Then using those as a basis to compute the N best WherePath objects
   110627 ** of length 2.  And so forth until the length of WherePaths equals the
   110628 ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
   110629 ** at the end is the choosen query plan.
   110630 */
   110631 struct WherePath {
   110632   Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
   110633   Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
   110634   LogEst nRow;          /* Estimated number of rows generated by this path */
   110635   LogEst rCost;         /* Total cost of this path */
   110636   LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
   110637   i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
   110638   WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
   110639 };
   110640 
   110641 /*
   110642 ** The query generator uses an array of instances of this structure to
   110643 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
   110644 ** clause subexpression is separated from the others by AND operators,
   110645 ** usually, or sometimes subexpressions separated by OR.
   110646 **
   110647 ** All WhereTerms are collected into a single WhereClause structure.
   110648 ** The following identity holds:
   110649 **
   110650 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
   110651 **
   110652 ** When a term is of the form:
   110653 **
   110654 **              X <op> <expr>
   110655 **
   110656 ** where X is a column name and <op> is one of certain operators,
   110657 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
   110658 ** cursor number and column number for X.  WhereTerm.eOperator records
   110659 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
   110660 ** use of a bitmask encoding for the operator allows us to search
   110661 ** quickly for terms that match any of several different operators.
   110662 **
   110663 ** A WhereTerm might also be two or more subterms connected by OR:
   110664 **
   110665 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
   110666 **
   110667 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
   110668 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
   110669 ** is collected about the OR clause.
   110670 **
   110671 ** If a term in the WHERE clause does not match either of the two previous
   110672 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
   110673 ** to the original subexpression content and wtFlags is set up appropriately
   110674 ** but no other fields in the WhereTerm object are meaningful.
   110675 **
   110676 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
   110677 ** but they do so indirectly.  A single WhereMaskSet structure translates
   110678 ** cursor number into bits and the translated bit is stored in the prereq
   110679 ** fields.  The translation is used in order to maximize the number of
   110680 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
   110681 ** spread out over the non-negative integers.  For example, the cursor
   110682 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
   110683 ** translates these sparse cursor numbers into consecutive integers
   110684 ** beginning with 0 in order to make the best possible use of the available
   110685 ** bits in the Bitmask.  So, in the example above, the cursor numbers
   110686 ** would be mapped into integers 0 through 7.
   110687 **
   110688 ** The number of terms in a join is limited by the number of bits
   110689 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
   110690 ** is only able to process joins with 64 or fewer tables.
   110691 */
   110692 struct WhereTerm {
   110693   Expr *pExpr;            /* Pointer to the subexpression that is this term */
   110694   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
   110695   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
   110696   union {
   110697     int leftColumn;         /* Column number of X in "X <op> <expr>" */
   110698     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
   110699     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
   110700   } u;
   110701   LogEst truthProb;       /* Probability of truth for this expression */
   110702   u16 eOperator;          /* A WO_xx value describing <op> */
   110703   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
   110704   u8 nChild;              /* Number of children that must disable us */
   110705   WhereClause *pWC;       /* The clause this term is part of */
   110706   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
   110707   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
   110708 };
   110709 
   110710 /*
   110711 ** Allowed values of WhereTerm.wtFlags
   110712 */
   110713 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
   110714 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
   110715 #define TERM_CODED      0x04   /* This term is already coded */
   110716 #define TERM_COPIED     0x08   /* Has a child */
   110717 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
   110718 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
   110719 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
   110720 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   110721 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
   110722 #else
   110723 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
   110724 #endif
   110725 
   110726 /*
   110727 ** An instance of the WhereScan object is used as an iterator for locating
   110728 ** terms in the WHERE clause that are useful to the query planner.
   110729 */
   110730 struct WhereScan {
   110731   WhereClause *pOrigWC;      /* Original, innermost WhereClause */
   110732   WhereClause *pWC;          /* WhereClause currently being scanned */
   110733   char *zCollName;           /* Required collating sequence, if not NULL */
   110734   char idxaff;               /* Must match this affinity, if zCollName!=NULL */
   110735   unsigned char nEquiv;      /* Number of entries in aEquiv[] */
   110736   unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
   110737   u32 opMask;                /* Acceptable operators */
   110738   int k;                     /* Resume scanning at this->pWC->a[this->k] */
   110739   int aEquiv[22];            /* Cursor,Column pairs for equivalence classes */
   110740 };
   110741 
   110742 /*
   110743 ** An instance of the following structure holds all information about a
   110744 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
   110745 **
   110746 ** Explanation of pOuter:  For a WHERE clause of the form
   110747 **
   110748 **           a AND ((b AND c) OR (d AND e)) AND f
   110749 **
   110750 ** There are separate WhereClause objects for the whole clause and for
   110751 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
   110752 ** subclauses points to the WhereClause object for the whole clause.
   110753 */
   110754 struct WhereClause {
   110755   WhereInfo *pWInfo;       /* WHERE clause processing context */
   110756   WhereClause *pOuter;     /* Outer conjunction */
   110757   u8 op;                   /* Split operator.  TK_AND or TK_OR */
   110758   int nTerm;               /* Number of terms */
   110759   int nSlot;               /* Number of entries in a[] */
   110760   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
   110761 #if defined(SQLITE_SMALL_STACK)
   110762   WhereTerm aStatic[1];    /* Initial static space for a[] */
   110763 #else
   110764   WhereTerm aStatic[8];    /* Initial static space for a[] */
   110765 #endif
   110766 };
   110767 
   110768 /*
   110769 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
   110770 ** a dynamically allocated instance of the following structure.
   110771 */
   110772 struct WhereOrInfo {
   110773   WhereClause wc;          /* Decomposition into subterms */
   110774   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
   110775 };
   110776 
   110777 /*
   110778 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
   110779 ** a dynamically allocated instance of the following structure.
   110780 */
   110781 struct WhereAndInfo {
   110782   WhereClause wc;          /* The subexpression broken out */
   110783 };
   110784 
   110785 /*
   110786 ** An instance of the following structure keeps track of a mapping
   110787 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
   110788 **
   110789 ** The VDBE cursor numbers are small integers contained in
   110790 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
   110791 ** clause, the cursor numbers might not begin with 0 and they might
   110792 ** contain gaps in the numbering sequence.  But we want to make maximum
   110793 ** use of the bits in our bitmasks.  This structure provides a mapping
   110794 ** from the sparse cursor numbers into consecutive integers beginning
   110795 ** with 0.
   110796 **
   110797 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
   110798 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
   110799 **
   110800 ** For example, if the WHERE clause expression used these VDBE
   110801 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
   110802 ** would map those cursor numbers into bits 0 through 5.
   110803 **
   110804 ** Note that the mapping is not necessarily ordered.  In the example
   110805 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
   110806 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
   110807 ** does not really matter.  What is important is that sparse cursor
   110808 ** numbers all get mapped into bit numbers that begin with 0 and contain
   110809 ** no gaps.
   110810 */
   110811 struct WhereMaskSet {
   110812   int n;                        /* Number of assigned cursor values */
   110813   int ix[BMS];                  /* Cursor assigned to each bit */
   110814 };
   110815 
   110816 /*
   110817 ** This object is a convenience wrapper holding all information needed
   110818 ** to construct WhereLoop objects for a particular query.
   110819 */
   110820 struct WhereLoopBuilder {
   110821   WhereInfo *pWInfo;        /* Information about this WHERE */
   110822   WhereClause *pWC;         /* WHERE clause terms */
   110823   ExprList *pOrderBy;       /* ORDER BY clause */
   110824   WhereLoop *pNew;          /* Template WhereLoop */
   110825   WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
   110826 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   110827   UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
   110828   int nRecValid;            /* Number of valid fields currently in pRec */
   110829 #endif
   110830 };
   110831 
   110832 /*
   110833 ** The WHERE clause processing routine has two halves.  The
   110834 ** first part does the start of the WHERE loop and the second
   110835 ** half does the tail of the WHERE loop.  An instance of
   110836 ** this structure is returned by the first half and passed
   110837 ** into the second half to give some continuity.
   110838 **
   110839 ** An instance of this object holds the complete state of the query
   110840 ** planner.
   110841 */
   110842 struct WhereInfo {
   110843   Parse *pParse;            /* Parsing and code generating context */
   110844   SrcList *pTabList;        /* List of tables in the join */
   110845   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
   110846   ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
   110847   WhereLoop *pLoops;        /* List of all WhereLoop objects */
   110848   Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
   110849   LogEst nRowOut;           /* Estimated number of output rows */
   110850   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
   110851   i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
   110852   u8 sorted;                /* True if really sorted (not just grouped) */
   110853   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
   110854   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
   110855   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
   110856   u8 nLevel;                /* Number of nested loop */
   110857   int iTop;                 /* The very beginning of the WHERE loop */
   110858   int iContinue;            /* Jump here to continue with next record */
   110859   int iBreak;               /* Jump here to break out of the loop */
   110860   int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
   110861   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
   110862   WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
   110863   WhereClause sWC;          /* Decomposition of the WHERE clause */
   110864   WhereLevel a[1];          /* Information about each nest loop in WHERE */
   110865 };
   110866 
   110867 /*
   110868 ** Bitmasks for the operators on WhereTerm objects.  These are all
   110869 ** operators that are of interest to the query planner.  An
   110870 ** OR-ed combination of these values can be used when searching for
   110871 ** particular WhereTerms within a WhereClause.
   110872 */
   110873 #define WO_IN     0x001
   110874 #define WO_EQ     0x002
   110875 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
   110876 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
   110877 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
   110878 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
   110879 #define WO_MATCH  0x040
   110880 #define WO_ISNULL 0x080
   110881 #define WO_OR     0x100       /* Two or more OR-connected terms */
   110882 #define WO_AND    0x200       /* Two or more AND-connected terms */
   110883 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
   110884 #define WO_NOOP   0x800       /* This term does not restrict search space */
   110885 
   110886 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
   110887 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
   110888 
   110889 /*
   110890 ** These are definitions of bits in the WhereLoop.wsFlags field.
   110891 ** The particular combination of bits in each WhereLoop help to
   110892 ** determine the algorithm that WhereLoop represents.
   110893 */
   110894 #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
   110895 #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
   110896 #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
   110897 #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
   110898 #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
   110899 #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
   110900 #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
   110901 #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
   110902 #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
   110903 #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
   110904 #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
   110905 #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
   110906 #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
   110907 #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
   110908 #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
   110909 #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
   110910 #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
   110911 #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
   110912 
   110913 /************** End of whereInt.h ********************************************/
   110914 /************** Continuing where we left off in where.c **********************/
   110915 
   110916 /*
   110917 ** Return the estimated number of output rows from a WHERE clause
   110918 */
   110919 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
   110920   return sqlite3LogEstToInt(pWInfo->nRowOut);
   110921 }
   110922 
   110923 /*
   110924 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
   110925 ** WHERE clause returns outputs for DISTINCT processing.
   110926 */
   110927 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
   110928   return pWInfo->eDistinct;
   110929 }
   110930 
   110931 /*
   110932 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
   110933 ** Return FALSE if the output needs to be sorted.
   110934 */
   110935 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
   110936   return pWInfo->nOBSat;
   110937 }
   110938 
   110939 /*
   110940 ** Return the VDBE address or label to jump to in order to continue
   110941 ** immediately with the next row of a WHERE clause.
   110942 */
   110943 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
   110944   assert( pWInfo->iContinue!=0 );
   110945   return pWInfo->iContinue;
   110946 }
   110947 
   110948 /*
   110949 ** Return the VDBE address or label to jump to in order to break
   110950 ** out of a WHERE loop.
   110951 */
   110952 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
   110953   return pWInfo->iBreak;
   110954 }
   110955 
   110956 /*
   110957 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
   110958 ** the rowids returned by a WHERE clause.  Return FALSE if doing an
   110959 ** UPDATE or DELETE might change subsequent WHERE clause results.
   110960 **
   110961 ** If the ONEPASS optimization is used (if this routine returns true)
   110962 ** then also write the indices of open cursors used by ONEPASS
   110963 ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
   110964 ** table and iaCur[1] gets the cursor used by an auxiliary index.
   110965 ** Either value may be -1, indicating that cursor is not used.
   110966 ** Any cursors returned will have been opened for writing.
   110967 **
   110968 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
   110969 ** unable to use the ONEPASS optimization.
   110970 */
   110971 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
   110972   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
   110973   return pWInfo->okOnePass;
   110974 }
   110975 
   110976 /*
   110977 ** Move the content of pSrc into pDest
   110978 */
   110979 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
   110980   pDest->n = pSrc->n;
   110981   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
   110982 }
   110983 
   110984 /*
   110985 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
   110986 **
   110987 ** The new entry might overwrite an existing entry, or it might be
   110988 ** appended, or it might be discarded.  Do whatever is the right thing
   110989 ** so that pSet keeps the N_OR_COST best entries seen so far.
   110990 */
   110991 static int whereOrInsert(
   110992   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
   110993   Bitmask prereq,        /* Prerequisites of the new entry */
   110994   LogEst rRun,           /* Run-cost of the new entry */
   110995   LogEst nOut            /* Number of outputs for the new entry */
   110996 ){
   110997   u16 i;
   110998   WhereOrCost *p;
   110999   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
   111000     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
   111001       goto whereOrInsert_done;
   111002     }
   111003     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
   111004       return 0;
   111005     }
   111006   }
   111007   if( pSet->n<N_OR_COST ){
   111008     p = &pSet->a[pSet->n++];
   111009     p->nOut = nOut;
   111010   }else{
   111011     p = pSet->a;
   111012     for(i=1; i<pSet->n; i++){
   111013       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
   111014     }
   111015     if( p->rRun<=rRun ) return 0;
   111016   }
   111017 whereOrInsert_done:
   111018   p->prereq = prereq;
   111019   p->rRun = rRun;
   111020   if( p->nOut>nOut ) p->nOut = nOut;
   111021   return 1;
   111022 }
   111023 
   111024 /*
   111025 ** Initialize a preallocated WhereClause structure.
   111026 */
   111027 static void whereClauseInit(
   111028   WhereClause *pWC,        /* The WhereClause to be initialized */
   111029   WhereInfo *pWInfo        /* The WHERE processing context */
   111030 ){
   111031   pWC->pWInfo = pWInfo;
   111032   pWC->pOuter = 0;
   111033   pWC->nTerm = 0;
   111034   pWC->nSlot = ArraySize(pWC->aStatic);
   111035   pWC->a = pWC->aStatic;
   111036 }
   111037 
   111038 /* Forward reference */
   111039 static void whereClauseClear(WhereClause*);
   111040 
   111041 /*
   111042 ** Deallocate all memory associated with a WhereOrInfo object.
   111043 */
   111044 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
   111045   whereClauseClear(&p->wc);
   111046   sqlite3DbFree(db, p);
   111047 }
   111048 
   111049 /*
   111050 ** Deallocate all memory associated with a WhereAndInfo object.
   111051 */
   111052 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
   111053   whereClauseClear(&p->wc);
   111054   sqlite3DbFree(db, p);
   111055 }
   111056 
   111057 /*
   111058 ** Deallocate a WhereClause structure.  The WhereClause structure
   111059 ** itself is not freed.  This routine is the inverse of whereClauseInit().
   111060 */
   111061 static void whereClauseClear(WhereClause *pWC){
   111062   int i;
   111063   WhereTerm *a;
   111064   sqlite3 *db = pWC->pWInfo->pParse->db;
   111065   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
   111066     if( a->wtFlags & TERM_DYNAMIC ){
   111067       sqlite3ExprDelete(db, a->pExpr);
   111068     }
   111069     if( a->wtFlags & TERM_ORINFO ){
   111070       whereOrInfoDelete(db, a->u.pOrInfo);
   111071     }else if( a->wtFlags & TERM_ANDINFO ){
   111072       whereAndInfoDelete(db, a->u.pAndInfo);
   111073     }
   111074   }
   111075   if( pWC->a!=pWC->aStatic ){
   111076     sqlite3DbFree(db, pWC->a);
   111077   }
   111078 }
   111079 
   111080 /*
   111081 ** Add a single new WhereTerm entry to the WhereClause object pWC.
   111082 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
   111083 ** The index in pWC->a[] of the new WhereTerm is returned on success.
   111084 ** 0 is returned if the new WhereTerm could not be added due to a memory
   111085 ** allocation error.  The memory allocation failure will be recorded in
   111086 ** the db->mallocFailed flag so that higher-level functions can detect it.
   111087 **
   111088 ** This routine will increase the size of the pWC->a[] array as necessary.
   111089 **
   111090 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
   111091 ** for freeing the expression p is assumed by the WhereClause object pWC.
   111092 ** This is true even if this routine fails to allocate a new WhereTerm.
   111093 **
   111094 ** WARNING:  This routine might reallocate the space used to store
   111095 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
   111096 ** calling this routine.  Such pointers may be reinitialized by referencing
   111097 ** the pWC->a[] array.
   111098 */
   111099 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
   111100   WhereTerm *pTerm;
   111101   int idx;
   111102   testcase( wtFlags & TERM_VIRTUAL );
   111103   if( pWC->nTerm>=pWC->nSlot ){
   111104     WhereTerm *pOld = pWC->a;
   111105     sqlite3 *db = pWC->pWInfo->pParse->db;
   111106     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
   111107     if( pWC->a==0 ){
   111108       if( wtFlags & TERM_DYNAMIC ){
   111109         sqlite3ExprDelete(db, p);
   111110       }
   111111       pWC->a = pOld;
   111112       return 0;
   111113     }
   111114     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
   111115     if( pOld!=pWC->aStatic ){
   111116       sqlite3DbFree(db, pOld);
   111117     }
   111118     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
   111119   }
   111120   pTerm = &pWC->a[idx = pWC->nTerm++];
   111121   if( p && ExprHasProperty(p, EP_Unlikely) ){
   111122     pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
   111123   }else{
   111124     pTerm->truthProb = 1;
   111125   }
   111126   pTerm->pExpr = sqlite3ExprSkipCollate(p);
   111127   pTerm->wtFlags = wtFlags;
   111128   pTerm->pWC = pWC;
   111129   pTerm->iParent = -1;
   111130   return idx;
   111131 }
   111132 
   111133 /*
   111134 ** This routine identifies subexpressions in the WHERE clause where
   111135 ** each subexpression is separated by the AND operator or some other
   111136 ** operator specified in the op parameter.  The WhereClause structure
   111137 ** is filled with pointers to subexpressions.  For example:
   111138 **
   111139 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
   111140 **           \________/     \_______________/     \________________/
   111141 **            slot[0]            slot[1]               slot[2]
   111142 **
   111143 ** The original WHERE clause in pExpr is unaltered.  All this routine
   111144 ** does is make slot[] entries point to substructure within pExpr.
   111145 **
   111146 ** In the previous sentence and in the diagram, "slot[]" refers to
   111147 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
   111148 ** all terms of the WHERE clause.
   111149 */
   111150 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
   111151   pWC->op = op;
   111152   if( pExpr==0 ) return;
   111153   if( pExpr->op!=op ){
   111154     whereClauseInsert(pWC, pExpr, 0);
   111155   }else{
   111156     whereSplit(pWC, pExpr->pLeft, op);
   111157     whereSplit(pWC, pExpr->pRight, op);
   111158   }
   111159 }
   111160 
   111161 /*
   111162 ** Initialize a WhereMaskSet object
   111163 */
   111164 #define initMaskSet(P)  (P)->n=0
   111165 
   111166 /*
   111167 ** Return the bitmask for the given cursor number.  Return 0 if
   111168 ** iCursor is not in the set.
   111169 */
   111170 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
   111171   int i;
   111172   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
   111173   for(i=0; i<pMaskSet->n; i++){
   111174     if( pMaskSet->ix[i]==iCursor ){
   111175       return MASKBIT(i);
   111176     }
   111177   }
   111178   return 0;
   111179 }
   111180 
   111181 /*
   111182 ** Create a new mask for cursor iCursor.
   111183 **
   111184 ** There is one cursor per table in the FROM clause.  The number of
   111185 ** tables in the FROM clause is limited by a test early in the
   111186 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
   111187 ** array will never overflow.
   111188 */
   111189 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
   111190   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
   111191   pMaskSet->ix[pMaskSet->n++] = iCursor;
   111192 }
   111193 
   111194 /*
   111195 ** These routines walk (recursively) an expression tree and generate
   111196 ** a bitmask indicating which tables are used in that expression
   111197 ** tree.
   111198 */
   111199 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
   111200 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
   111201 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
   111202   Bitmask mask = 0;
   111203   if( p==0 ) return 0;
   111204   if( p->op==TK_COLUMN ){
   111205     mask = getMask(pMaskSet, p->iTable);
   111206     return mask;
   111207   }
   111208   mask = exprTableUsage(pMaskSet, p->pRight);
   111209   mask |= exprTableUsage(pMaskSet, p->pLeft);
   111210   if( ExprHasProperty(p, EP_xIsSelect) ){
   111211     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
   111212   }else{
   111213     mask |= exprListTableUsage(pMaskSet, p->x.pList);
   111214   }
   111215   return mask;
   111216 }
   111217 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
   111218   int i;
   111219   Bitmask mask = 0;
   111220   if( pList ){
   111221     for(i=0; i<pList->nExpr; i++){
   111222       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
   111223     }
   111224   }
   111225   return mask;
   111226 }
   111227 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
   111228   Bitmask mask = 0;
   111229   while( pS ){
   111230     SrcList *pSrc = pS->pSrc;
   111231     mask |= exprListTableUsage(pMaskSet, pS->pEList);
   111232     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
   111233     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
   111234     mask |= exprTableUsage(pMaskSet, pS->pWhere);
   111235     mask |= exprTableUsage(pMaskSet, pS->pHaving);
   111236     if( ALWAYS(pSrc!=0) ){
   111237       int i;
   111238       for(i=0; i<pSrc->nSrc; i++){
   111239         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
   111240         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
   111241       }
   111242     }
   111243     pS = pS->pPrior;
   111244   }
   111245   return mask;
   111246 }
   111247 
   111248 /*
   111249 ** Return TRUE if the given operator is one of the operators that is
   111250 ** allowed for an indexable WHERE clause term.  The allowed operators are
   111251 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
   111252 */
   111253 static int allowedOp(int op){
   111254   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
   111255   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
   111256   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
   111257   assert( TK_GE==TK_EQ+4 );
   111258   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
   111259 }
   111260 
   111261 /*
   111262 ** Swap two objects of type TYPE.
   111263 */
   111264 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
   111265 
   111266 /*
   111267 ** Commute a comparison operator.  Expressions of the form "X op Y"
   111268 ** are converted into "Y op X".
   111269 **
   111270 ** If left/right precedence rules come into play when determining the
   111271 ** collating sequence, then COLLATE operators are adjusted to ensure
   111272 ** that the collating sequence does not change.  For example:
   111273 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
   111274 ** the left hand side of a comparison overrides any collation sequence
   111275 ** attached to the right. For the same reason the EP_Collate flag
   111276 ** is not commuted.
   111277 */
   111278 static void exprCommute(Parse *pParse, Expr *pExpr){
   111279   u16 expRight = (pExpr->pRight->flags & EP_Collate);
   111280   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
   111281   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
   111282   if( expRight==expLeft ){
   111283     /* Either X and Y both have COLLATE operator or neither do */
   111284     if( expRight ){
   111285       /* Both X and Y have COLLATE operators.  Make sure X is always
   111286       ** used by clearing the EP_Collate flag from Y. */
   111287       pExpr->pRight->flags &= ~EP_Collate;
   111288     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
   111289       /* Neither X nor Y have COLLATE operators, but X has a non-default
   111290       ** collating sequence.  So add the EP_Collate marker on X to cause
   111291       ** it to be searched first. */
   111292       pExpr->pLeft->flags |= EP_Collate;
   111293     }
   111294   }
   111295   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
   111296   if( pExpr->op>=TK_GT ){
   111297     assert( TK_LT==TK_GT+2 );
   111298     assert( TK_GE==TK_LE+2 );
   111299     assert( TK_GT>TK_EQ );
   111300     assert( TK_GT<TK_LE );
   111301     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
   111302     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
   111303   }
   111304 }
   111305 
   111306 /*
   111307 ** Translate from TK_xx operator to WO_xx bitmask.
   111308 */
   111309 static u16 operatorMask(int op){
   111310   u16 c;
   111311   assert( allowedOp(op) );
   111312   if( op==TK_IN ){
   111313     c = WO_IN;
   111314   }else if( op==TK_ISNULL ){
   111315     c = WO_ISNULL;
   111316   }else{
   111317     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
   111318     c = (u16)(WO_EQ<<(op-TK_EQ));
   111319   }
   111320   assert( op!=TK_ISNULL || c==WO_ISNULL );
   111321   assert( op!=TK_IN || c==WO_IN );
   111322   assert( op!=TK_EQ || c==WO_EQ );
   111323   assert( op!=TK_LT || c==WO_LT );
   111324   assert( op!=TK_LE || c==WO_LE );
   111325   assert( op!=TK_GT || c==WO_GT );
   111326   assert( op!=TK_GE || c==WO_GE );
   111327   return c;
   111328 }
   111329 
   111330 /*
   111331 ** Advance to the next WhereTerm that matches according to the criteria
   111332 ** established when the pScan object was initialized by whereScanInit().
   111333 ** Return NULL if there are no more matching WhereTerms.
   111334 */
   111335 static WhereTerm *whereScanNext(WhereScan *pScan){
   111336   int iCur;            /* The cursor on the LHS of the term */
   111337   int iColumn;         /* The column on the LHS of the term.  -1 for IPK */
   111338   Expr *pX;            /* An expression being tested */
   111339   WhereClause *pWC;    /* Shorthand for pScan->pWC */
   111340   WhereTerm *pTerm;    /* The term being tested */
   111341   int k = pScan->k;    /* Where to start scanning */
   111342 
   111343   while( pScan->iEquiv<=pScan->nEquiv ){
   111344     iCur = pScan->aEquiv[pScan->iEquiv-2];
   111345     iColumn = pScan->aEquiv[pScan->iEquiv-1];
   111346     while( (pWC = pScan->pWC)!=0 ){
   111347       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
   111348         if( pTerm->leftCursor==iCur
   111349          && pTerm->u.leftColumn==iColumn
   111350          && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   111351         ){
   111352           if( (pTerm->eOperator & WO_EQUIV)!=0
   111353            && pScan->nEquiv<ArraySize(pScan->aEquiv)
   111354           ){
   111355             int j;
   111356             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
   111357             assert( pX->op==TK_COLUMN );
   111358             for(j=0; j<pScan->nEquiv; j+=2){
   111359               if( pScan->aEquiv[j]==pX->iTable
   111360                && pScan->aEquiv[j+1]==pX->iColumn ){
   111361                   break;
   111362               }
   111363             }
   111364             if( j==pScan->nEquiv ){
   111365               pScan->aEquiv[j] = pX->iTable;
   111366               pScan->aEquiv[j+1] = pX->iColumn;
   111367               pScan->nEquiv += 2;
   111368             }
   111369           }
   111370           if( (pTerm->eOperator & pScan->opMask)!=0 ){
   111371             /* Verify the affinity and collating sequence match */
   111372             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
   111373               CollSeq *pColl;
   111374               Parse *pParse = pWC->pWInfo->pParse;
   111375               pX = pTerm->pExpr;
   111376               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
   111377                 continue;
   111378               }
   111379               assert(pX->pLeft);
   111380               pColl = sqlite3BinaryCompareCollSeq(pParse,
   111381                                                   pX->pLeft, pX->pRight);
   111382               if( pColl==0 ) pColl = pParse->db->pDfltColl;
   111383               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
   111384                 continue;
   111385               }
   111386             }
   111387             if( (pTerm->eOperator & WO_EQ)!=0
   111388              && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
   111389              && pX->iTable==pScan->aEquiv[0]
   111390              && pX->iColumn==pScan->aEquiv[1]
   111391             ){
   111392               continue;
   111393             }
   111394             pScan->k = k+1;
   111395             return pTerm;
   111396           }
   111397         }
   111398       }
   111399       pScan->pWC = pScan->pWC->pOuter;
   111400       k = 0;
   111401     }
   111402     pScan->pWC = pScan->pOrigWC;
   111403     k = 0;
   111404     pScan->iEquiv += 2;
   111405   }
   111406   return 0;
   111407 }
   111408 
   111409 /*
   111410 ** Initialize a WHERE clause scanner object.  Return a pointer to the
   111411 ** first match.  Return NULL if there are no matches.
   111412 **
   111413 ** The scanner will be searching the WHERE clause pWC.  It will look
   111414 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
   111415 ** iCur.  The <op> must be one of the operators described by opMask.
   111416 **
   111417 ** If the search is for X and the WHERE clause contains terms of the
   111418 ** form X=Y then this routine might also return terms of the form
   111419 ** "Y <op> <expr>".  The number of levels of transitivity is limited,
   111420 ** but is enough to handle most commonly occurring SQL statements.
   111421 **
   111422 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
   111423 ** index pIdx.
   111424 */
   111425 static WhereTerm *whereScanInit(
   111426   WhereScan *pScan,       /* The WhereScan object being initialized */
   111427   WhereClause *pWC,       /* The WHERE clause to be scanned */
   111428   int iCur,               /* Cursor to scan for */
   111429   int iColumn,            /* Column to scan for */
   111430   u32 opMask,             /* Operator(s) to scan for */
   111431   Index *pIdx             /* Must be compatible with this index */
   111432 ){
   111433   int j;
   111434 
   111435   /* memset(pScan, 0, sizeof(*pScan)); */
   111436   pScan->pOrigWC = pWC;
   111437   pScan->pWC = pWC;
   111438   if( pIdx && iColumn>=0 ){
   111439     pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
   111440     for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
   111441       if( NEVER(j>pIdx->nColumn) ) return 0;
   111442     }
   111443     pScan->zCollName = pIdx->azColl[j];
   111444   }else{
   111445     pScan->idxaff = 0;
   111446     pScan->zCollName = 0;
   111447   }
   111448   pScan->opMask = opMask;
   111449   pScan->k = 0;
   111450   pScan->aEquiv[0] = iCur;
   111451   pScan->aEquiv[1] = iColumn;
   111452   pScan->nEquiv = 2;
   111453   pScan->iEquiv = 2;
   111454   return whereScanNext(pScan);
   111455 }
   111456 
   111457 /*
   111458 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
   111459 ** where X is a reference to the iColumn of table iCur and <op> is one of
   111460 ** the WO_xx operator codes specified by the op parameter.
   111461 ** Return a pointer to the term.  Return 0 if not found.
   111462 **
   111463 ** The term returned might by Y=<expr> if there is another constraint in
   111464 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
   111465 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
   111466 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
   111467 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
   111468 ** and the second is for the column number.  There are 22 slots in aEquiv[]
   111469 ** so that means we can look for X plus up to 10 other equivalent values.
   111470 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
   111471 ** and ... and A9=A10 and A10=<expr>.
   111472 **
   111473 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
   111474 ** then try for the one with no dependencies on <expr> - in other words where
   111475 ** <expr> is a constant expression of some kind.  Only return entries of
   111476 ** the form "X <op> Y" where Y is a column in another table if no terms of
   111477 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
   111478 ** exist, try to return a term that does not use WO_EQUIV.
   111479 */
   111480 static WhereTerm *findTerm(
   111481   WhereClause *pWC,     /* The WHERE clause to be searched */
   111482   int iCur,             /* Cursor number of LHS */
   111483   int iColumn,          /* Column number of LHS */
   111484   Bitmask notReady,     /* RHS must not overlap with this mask */
   111485   u32 op,               /* Mask of WO_xx values describing operator */
   111486   Index *pIdx           /* Must be compatible with this index, if not NULL */
   111487 ){
   111488   WhereTerm *pResult = 0;
   111489   WhereTerm *p;
   111490   WhereScan scan;
   111491 
   111492   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
   111493   while( p ){
   111494     if( (p->prereqRight & notReady)==0 ){
   111495       if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
   111496         return p;
   111497       }
   111498       if( pResult==0 ) pResult = p;
   111499     }
   111500     p = whereScanNext(&scan);
   111501   }
   111502   return pResult;
   111503 }
   111504 
   111505 /* Forward reference */
   111506 static void exprAnalyze(SrcList*, WhereClause*, int);
   111507 
   111508 /*
   111509 ** Call exprAnalyze on all terms in a WHERE clause.
   111510 */
   111511 static void exprAnalyzeAll(
   111512   SrcList *pTabList,       /* the FROM clause */
   111513   WhereClause *pWC         /* the WHERE clause to be analyzed */
   111514 ){
   111515   int i;
   111516   for(i=pWC->nTerm-1; i>=0; i--){
   111517     exprAnalyze(pTabList, pWC, i);
   111518   }
   111519 }
   111520 
   111521 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   111522 /*
   111523 ** Check to see if the given expression is a LIKE or GLOB operator that
   111524 ** can be optimized using inequality constraints.  Return TRUE if it is
   111525 ** so and false if not.
   111526 **
   111527 ** In order for the operator to be optimizible, the RHS must be a string
   111528 ** literal that does not begin with a wildcard.
   111529 */
   111530 static int isLikeOrGlob(
   111531   Parse *pParse,    /* Parsing and code generating context */
   111532   Expr *pExpr,      /* Test this expression */
   111533   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
   111534   int *pisComplete, /* True if the only wildcard is % in the last character */
   111535   int *pnoCase      /* True if uppercase is equivalent to lowercase */
   111536 ){
   111537   const char *z = 0;         /* String on RHS of LIKE operator */
   111538   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
   111539   ExprList *pList;           /* List of operands to the LIKE operator */
   111540   int c;                     /* One character in z[] */
   111541   int cnt;                   /* Number of non-wildcard prefix characters */
   111542   char wc[3];                /* Wildcard characters */
   111543   sqlite3 *db = pParse->db;  /* Database connection */
   111544   sqlite3_value *pVal = 0;
   111545   int op;                    /* Opcode of pRight */
   111546 
   111547   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
   111548     return 0;
   111549   }
   111550 #ifdef SQLITE_EBCDIC
   111551   if( *pnoCase ) return 0;
   111552 #endif
   111553   pList = pExpr->x.pList;
   111554   pLeft = pList->a[1].pExpr;
   111555   if( pLeft->op!=TK_COLUMN
   111556    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
   111557    || IsVirtual(pLeft->pTab)
   111558   ){
   111559     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
   111560     ** be the name of an indexed column with TEXT affinity. */
   111561     return 0;
   111562   }
   111563   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
   111564 
   111565   pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
   111566   op = pRight->op;
   111567   if( op==TK_VARIABLE ){
   111568     Vdbe *pReprepare = pParse->pReprepare;
   111569     int iCol = pRight->iColumn;
   111570     pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
   111571     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
   111572       z = (char *)sqlite3_value_text(pVal);
   111573     }
   111574     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
   111575     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
   111576   }else if( op==TK_STRING ){
   111577     z = pRight->u.zToken;
   111578   }
   111579   if( z ){
   111580     cnt = 0;
   111581     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
   111582       cnt++;
   111583     }
   111584     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
   111585       Expr *pPrefix;
   111586       *pisComplete = c==wc[0] && z[cnt+1]==0;
   111587       pPrefix = sqlite3Expr(db, TK_STRING, z);
   111588       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
   111589       *ppPrefix = pPrefix;
   111590       if( op==TK_VARIABLE ){
   111591         Vdbe *v = pParse->pVdbe;
   111592         sqlite3VdbeSetVarmask(v, pRight->iColumn);
   111593         if( *pisComplete && pRight->u.zToken[1] ){
   111594           /* If the rhs of the LIKE expression is a variable, and the current
   111595           ** value of the variable means there is no need to invoke the LIKE
   111596           ** function, then no OP_Variable will be added to the program.
   111597           ** This causes problems for the sqlite3_bind_parameter_name()
   111598           ** API. To workaround them, add a dummy OP_Variable here.
   111599           */
   111600           int r1 = sqlite3GetTempReg(pParse);
   111601           sqlite3ExprCodeTarget(pParse, pRight, r1);
   111602           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
   111603           sqlite3ReleaseTempReg(pParse, r1);
   111604         }
   111605       }
   111606     }else{
   111607       z = 0;
   111608     }
   111609   }
   111610 
   111611   sqlite3ValueFree(pVal);
   111612   return (z!=0);
   111613 }
   111614 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   111615 
   111616 
   111617 #ifndef SQLITE_OMIT_VIRTUALTABLE
   111618 /*
   111619 ** Check to see if the given expression is of the form
   111620 **
   111621 **         column MATCH expr
   111622 **
   111623 ** If it is then return TRUE.  If not, return FALSE.
   111624 */
   111625 static int isMatchOfColumn(
   111626   Expr *pExpr      /* Test this expression */
   111627 ){
   111628   ExprList *pList;
   111629 
   111630   if( pExpr->op!=TK_FUNCTION ){
   111631     return 0;
   111632   }
   111633   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
   111634     return 0;
   111635   }
   111636   pList = pExpr->x.pList;
   111637   if( pList->nExpr!=2 ){
   111638     return 0;
   111639   }
   111640   if( pList->a[1].pExpr->op != TK_COLUMN ){
   111641     return 0;
   111642   }
   111643   return 1;
   111644 }
   111645 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   111646 
   111647 /*
   111648 ** If the pBase expression originated in the ON or USING clause of
   111649 ** a join, then transfer the appropriate markings over to derived.
   111650 */
   111651 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
   111652   if( pDerived ){
   111653     pDerived->flags |= pBase->flags & EP_FromJoin;
   111654     pDerived->iRightJoinTable = pBase->iRightJoinTable;
   111655   }
   111656 }
   111657 
   111658 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   111659 /*
   111660 ** Analyze a term that consists of two or more OR-connected
   111661 ** subterms.  So in:
   111662 **
   111663 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
   111664 **                          ^^^^^^^^^^^^^^^^^^^^
   111665 **
   111666 ** This routine analyzes terms such as the middle term in the above example.
   111667 ** A WhereOrTerm object is computed and attached to the term under
   111668 ** analysis, regardless of the outcome of the analysis.  Hence:
   111669 **
   111670 **     WhereTerm.wtFlags   |=  TERM_ORINFO
   111671 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
   111672 **
   111673 ** The term being analyzed must have two or more of OR-connected subterms.
   111674 ** A single subterm might be a set of AND-connected sub-subterms.
   111675 ** Examples of terms under analysis:
   111676 **
   111677 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
   111678 **     (B)     x=expr1 OR expr2=x OR x=expr3
   111679 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
   111680 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
   111681 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
   111682 **
   111683 ** CASE 1:
   111684 **
   111685 ** If all subterms are of the form T.C=expr for some single column of C and
   111686 ** a single table T (as shown in example B above) then create a new virtual
   111687 ** term that is an equivalent IN expression.  In other words, if the term
   111688 ** being analyzed is:
   111689 **
   111690 **      x = expr1  OR  expr2 = x  OR  x = expr3
   111691 **
   111692 ** then create a new virtual term like this:
   111693 **
   111694 **      x IN (expr1,expr2,expr3)
   111695 **
   111696 ** CASE 2:
   111697 **
   111698 ** If all subterms are indexable by a single table T, then set
   111699 **
   111700 **     WhereTerm.eOperator              =  WO_OR
   111701 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
   111702 **
   111703 ** A subterm is "indexable" if it is of the form
   111704 ** "T.C <op> <expr>" where C is any column of table T and
   111705 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
   111706 ** A subterm is also indexable if it is an AND of two or more
   111707 ** subsubterms at least one of which is indexable.  Indexable AND
   111708 ** subterms have their eOperator set to WO_AND and they have
   111709 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
   111710 **
   111711 ** From another point of view, "indexable" means that the subterm could
   111712 ** potentially be used with an index if an appropriate index exists.
   111713 ** This analysis does not consider whether or not the index exists; that
   111714 ** is decided elsewhere.  This analysis only looks at whether subterms
   111715 ** appropriate for indexing exist.
   111716 **
   111717 ** All examples A through E above satisfy case 2.  But if a term
   111718 ** also statisfies case 1 (such as B) we know that the optimizer will
   111719 ** always prefer case 1, so in that case we pretend that case 2 is not
   111720 ** satisfied.
   111721 **
   111722 ** It might be the case that multiple tables are indexable.  For example,
   111723 ** (E) above is indexable on tables P, Q, and R.
   111724 **
   111725 ** Terms that satisfy case 2 are candidates for lookup by using
   111726 ** separate indices to find rowids for each subterm and composing
   111727 ** the union of all rowids using a RowSet object.  This is similar
   111728 ** to "bitmap indices" in other database engines.
   111729 **
   111730 ** OTHERWISE:
   111731 **
   111732 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
   111733 ** zero.  This term is not useful for search.
   111734 */
   111735 static void exprAnalyzeOrTerm(
   111736   SrcList *pSrc,            /* the FROM clause */
   111737   WhereClause *pWC,         /* the complete WHERE clause */
   111738   int idxTerm               /* Index of the OR-term to be analyzed */
   111739 ){
   111740   WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
   111741   Parse *pParse = pWInfo->pParse;         /* Parser context */
   111742   sqlite3 *db = pParse->db;               /* Database connection */
   111743   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
   111744   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
   111745   int i;                                  /* Loop counters */
   111746   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
   111747   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
   111748   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
   111749   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
   111750   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
   111751 
   111752   /*
   111753   ** Break the OR clause into its separate subterms.  The subterms are
   111754   ** stored in a WhereClause structure containing within the WhereOrInfo
   111755   ** object that is attached to the original OR clause term.
   111756   */
   111757   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
   111758   assert( pExpr->op==TK_OR );
   111759   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
   111760   if( pOrInfo==0 ) return;
   111761   pTerm->wtFlags |= TERM_ORINFO;
   111762   pOrWc = &pOrInfo->wc;
   111763   whereClauseInit(pOrWc, pWInfo);
   111764   whereSplit(pOrWc, pExpr, TK_OR);
   111765   exprAnalyzeAll(pSrc, pOrWc);
   111766   if( db->mallocFailed ) return;
   111767   assert( pOrWc->nTerm>=2 );
   111768 
   111769   /*
   111770   ** Compute the set of tables that might satisfy cases 1 or 2.
   111771   */
   111772   indexable = ~(Bitmask)0;
   111773   chngToIN = ~(Bitmask)0;
   111774   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
   111775     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
   111776       WhereAndInfo *pAndInfo;
   111777       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
   111778       chngToIN = 0;
   111779       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
   111780       if( pAndInfo ){
   111781         WhereClause *pAndWC;
   111782         WhereTerm *pAndTerm;
   111783         int j;
   111784         Bitmask b = 0;
   111785         pOrTerm->u.pAndInfo = pAndInfo;
   111786         pOrTerm->wtFlags |= TERM_ANDINFO;
   111787         pOrTerm->eOperator = WO_AND;
   111788         pAndWC = &pAndInfo->wc;
   111789         whereClauseInit(pAndWC, pWC->pWInfo);
   111790         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
   111791         exprAnalyzeAll(pSrc, pAndWC);
   111792         pAndWC->pOuter = pWC;
   111793         testcase( db->mallocFailed );
   111794         if( !db->mallocFailed ){
   111795           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
   111796             assert( pAndTerm->pExpr );
   111797             if( allowedOp(pAndTerm->pExpr->op) ){
   111798               b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
   111799             }
   111800           }
   111801         }
   111802         indexable &= b;
   111803       }
   111804     }else if( pOrTerm->wtFlags & TERM_COPIED ){
   111805       /* Skip this term for now.  We revisit it when we process the
   111806       ** corresponding TERM_VIRTUAL term */
   111807     }else{
   111808       Bitmask b;
   111809       b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
   111810       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
   111811         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
   111812         b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
   111813       }
   111814       indexable &= b;
   111815       if( (pOrTerm->eOperator & WO_EQ)==0 ){
   111816         chngToIN = 0;
   111817       }else{
   111818         chngToIN &= b;
   111819       }
   111820     }
   111821   }
   111822 
   111823   /*
   111824   ** Record the set of tables that satisfy case 2.  The set might be
   111825   ** empty.
   111826   */
   111827   pOrInfo->indexable = indexable;
   111828   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
   111829 
   111830   /*
   111831   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
   111832   ** we have to do some additional checking to see if case 1 really
   111833   ** is satisfied.
   111834   **
   111835   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
   111836   ** that there is no possibility of transforming the OR clause into an
   111837   ** IN operator because one or more terms in the OR clause contain
   111838   ** something other than == on a column in the single table.  The 1-bit
   111839   ** case means that every term of the OR clause is of the form
   111840   ** "table.column=expr" for some single table.  The one bit that is set
   111841   ** will correspond to the common table.  We still need to check to make
   111842   ** sure the same column is used on all terms.  The 2-bit case is when
   111843   ** the all terms are of the form "table1.column=table2.column".  It
   111844   ** might be possible to form an IN operator with either table1.column
   111845   ** or table2.column as the LHS if either is common to every term of
   111846   ** the OR clause.
   111847   **
   111848   ** Note that terms of the form "table.column1=table.column2" (the
   111849   ** same table on both sizes of the ==) cannot be optimized.
   111850   */
   111851   if( chngToIN ){
   111852     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
   111853     int iColumn = -1;         /* Column index on lhs of IN operator */
   111854     int iCursor = -1;         /* Table cursor common to all terms */
   111855     int j = 0;                /* Loop counter */
   111856 
   111857     /* Search for a table and column that appears on one side or the
   111858     ** other of the == operator in every subterm.  That table and column
   111859     ** will be recorded in iCursor and iColumn.  There might not be any
   111860     ** such table and column.  Set okToChngToIN if an appropriate table
   111861     ** and column is found but leave okToChngToIN false if not found.
   111862     */
   111863     for(j=0; j<2 && !okToChngToIN; j++){
   111864       pOrTerm = pOrWc->a;
   111865       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
   111866         assert( pOrTerm->eOperator & WO_EQ );
   111867         pOrTerm->wtFlags &= ~TERM_OR_OK;
   111868         if( pOrTerm->leftCursor==iCursor ){
   111869           /* This is the 2-bit case and we are on the second iteration and
   111870           ** current term is from the first iteration.  So skip this term. */
   111871           assert( j==1 );
   111872           continue;
   111873         }
   111874         if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
   111875           /* This term must be of the form t1.a==t2.b where t2 is in the
   111876           ** chngToIN set but t1 is not.  This term will be either preceeded
   111877           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
   111878           ** and use its inversion. */
   111879           testcase( pOrTerm->wtFlags & TERM_COPIED );
   111880           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
   111881           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
   111882           continue;
   111883         }
   111884         iColumn = pOrTerm->u.leftColumn;
   111885         iCursor = pOrTerm->leftCursor;
   111886         break;
   111887       }
   111888       if( i<0 ){
   111889         /* No candidate table+column was found.  This can only occur
   111890         ** on the second iteration */
   111891         assert( j==1 );
   111892         assert( IsPowerOfTwo(chngToIN) );
   111893         assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
   111894         break;
   111895       }
   111896       testcase( j==1 );
   111897 
   111898       /* We have found a candidate table and column.  Check to see if that
   111899       ** table and column is common to every term in the OR clause */
   111900       okToChngToIN = 1;
   111901       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
   111902         assert( pOrTerm->eOperator & WO_EQ );
   111903         if( pOrTerm->leftCursor!=iCursor ){
   111904           pOrTerm->wtFlags &= ~TERM_OR_OK;
   111905         }else if( pOrTerm->u.leftColumn!=iColumn ){
   111906           okToChngToIN = 0;
   111907         }else{
   111908           int affLeft, affRight;
   111909           /* If the right-hand side is also a column, then the affinities
   111910           ** of both right and left sides must be such that no type
   111911           ** conversions are required on the right.  (Ticket #2249)
   111912           */
   111913           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
   111914           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
   111915           if( affRight!=0 && affRight!=affLeft ){
   111916             okToChngToIN = 0;
   111917           }else{
   111918             pOrTerm->wtFlags |= TERM_OR_OK;
   111919           }
   111920         }
   111921       }
   111922     }
   111923 
   111924     /* At this point, okToChngToIN is true if original pTerm satisfies
   111925     ** case 1.  In that case, construct a new virtual term that is
   111926     ** pTerm converted into an IN operator.
   111927     */
   111928     if( okToChngToIN ){
   111929       Expr *pDup;            /* A transient duplicate expression */
   111930       ExprList *pList = 0;   /* The RHS of the IN operator */
   111931       Expr *pLeft = 0;       /* The LHS of the IN operator */
   111932       Expr *pNew;            /* The complete IN operator */
   111933 
   111934       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
   111935         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
   111936         assert( pOrTerm->eOperator & WO_EQ );
   111937         assert( pOrTerm->leftCursor==iCursor );
   111938         assert( pOrTerm->u.leftColumn==iColumn );
   111939         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
   111940         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
   111941         pLeft = pOrTerm->pExpr->pLeft;
   111942       }
   111943       assert( pLeft!=0 );
   111944       pDup = sqlite3ExprDup(db, pLeft, 0);
   111945       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
   111946       if( pNew ){
   111947         int idxNew;
   111948         transferJoinMarkings(pNew, pExpr);
   111949         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   111950         pNew->x.pList = pList;
   111951         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   111952         testcase( idxNew==0 );
   111953         exprAnalyze(pSrc, pWC, idxNew);
   111954         pTerm = &pWC->a[idxTerm];
   111955         pWC->a[idxNew].iParent = idxTerm;
   111956         pTerm->nChild = 1;
   111957       }else{
   111958         sqlite3ExprListDelete(db, pList);
   111959       }
   111960       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
   111961     }
   111962   }
   111963 }
   111964 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
   111965 
   111966 /*
   111967 ** The input to this routine is an WhereTerm structure with only the
   111968 ** "pExpr" field filled in.  The job of this routine is to analyze the
   111969 ** subexpression and populate all the other fields of the WhereTerm
   111970 ** structure.
   111971 **
   111972 ** If the expression is of the form "<expr> <op> X" it gets commuted
   111973 ** to the standard form of "X <op> <expr>".
   111974 **
   111975 ** If the expression is of the form "X <op> Y" where both X and Y are
   111976 ** columns, then the original expression is unchanged and a new virtual
   111977 ** term of the form "Y <op> X" is added to the WHERE clause and
   111978 ** analyzed separately.  The original term is marked with TERM_COPIED
   111979 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
   111980 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
   111981 ** is a commuted copy of a prior term.)  The original term has nChild=1
   111982 ** and the copy has idxParent set to the index of the original term.
   111983 */
   111984 static void exprAnalyze(
   111985   SrcList *pSrc,            /* the FROM clause */
   111986   WhereClause *pWC,         /* the WHERE clause */
   111987   int idxTerm               /* Index of the term to be analyzed */
   111988 ){
   111989   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
   111990   WhereTerm *pTerm;                /* The term to be analyzed */
   111991   WhereMaskSet *pMaskSet;          /* Set of table index masks */
   111992   Expr *pExpr;                     /* The expression to be analyzed */
   111993   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
   111994   Bitmask prereqAll;               /* Prerequesites of pExpr */
   111995   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
   111996   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
   111997   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
   111998   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
   111999   int op;                          /* Top-level operator.  pExpr->op */
   112000   Parse *pParse = pWInfo->pParse;  /* Parsing context */
   112001   sqlite3 *db = pParse->db;        /* Database connection */
   112002 
   112003   if( db->mallocFailed ){
   112004     return;
   112005   }
   112006   pTerm = &pWC->a[idxTerm];
   112007   pMaskSet = &pWInfo->sMaskSet;
   112008   pExpr = pTerm->pExpr;
   112009   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
   112010   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
   112011   op = pExpr->op;
   112012   if( op==TK_IN ){
   112013     assert( pExpr->pRight==0 );
   112014     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   112015       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
   112016     }else{
   112017       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
   112018     }
   112019   }else if( op==TK_ISNULL ){
   112020     pTerm->prereqRight = 0;
   112021   }else{
   112022     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
   112023   }
   112024   prereqAll = exprTableUsage(pMaskSet, pExpr);
   112025   if( ExprHasProperty(pExpr, EP_FromJoin) ){
   112026     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
   112027     prereqAll |= x;
   112028     extraRight = x-1;  /* ON clause terms may not be used with an index
   112029                        ** on left table of a LEFT JOIN.  Ticket #3015 */
   112030   }
   112031   pTerm->prereqAll = prereqAll;
   112032   pTerm->leftCursor = -1;
   112033   pTerm->iParent = -1;
   112034   pTerm->eOperator = 0;
   112035   if( allowedOp(op) ){
   112036     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
   112037     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
   112038     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
   112039     if( pLeft->op==TK_COLUMN ){
   112040       pTerm->leftCursor = pLeft->iTable;
   112041       pTerm->u.leftColumn = pLeft->iColumn;
   112042       pTerm->eOperator = operatorMask(op) & opMask;
   112043     }
   112044     if( pRight && pRight->op==TK_COLUMN ){
   112045       WhereTerm *pNew;
   112046       Expr *pDup;
   112047       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
   112048       if( pTerm->leftCursor>=0 ){
   112049         int idxNew;
   112050         pDup = sqlite3ExprDup(db, pExpr, 0);
   112051         if( db->mallocFailed ){
   112052           sqlite3ExprDelete(db, pDup);
   112053           return;
   112054         }
   112055         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
   112056         if( idxNew==0 ) return;
   112057         pNew = &pWC->a[idxNew];
   112058         pNew->iParent = idxTerm;
   112059         pTerm = &pWC->a[idxTerm];
   112060         pTerm->nChild = 1;
   112061         pTerm->wtFlags |= TERM_COPIED;
   112062         if( pExpr->op==TK_EQ
   112063          && !ExprHasProperty(pExpr, EP_FromJoin)
   112064          && OptimizationEnabled(db, SQLITE_Transitive)
   112065         ){
   112066           pTerm->eOperator |= WO_EQUIV;
   112067           eExtraOp = WO_EQUIV;
   112068         }
   112069       }else{
   112070         pDup = pExpr;
   112071         pNew = pTerm;
   112072       }
   112073       exprCommute(pParse, pDup);
   112074       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
   112075       pNew->leftCursor = pLeft->iTable;
   112076       pNew->u.leftColumn = pLeft->iColumn;
   112077       testcase( (prereqLeft | extraRight) != prereqLeft );
   112078       pNew->prereqRight = prereqLeft | extraRight;
   112079       pNew->prereqAll = prereqAll;
   112080       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
   112081     }
   112082   }
   112083 
   112084 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   112085   /* If a term is the BETWEEN operator, create two new virtual terms
   112086   ** that define the range that the BETWEEN implements.  For example:
   112087   **
   112088   **      a BETWEEN b AND c
   112089   **
   112090   ** is converted into:
   112091   **
   112092   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
   112093   **
   112094   ** The two new terms are added onto the end of the WhereClause object.
   112095   ** The new terms are "dynamic" and are children of the original BETWEEN
   112096   ** term.  That means that if the BETWEEN term is coded, the children are
   112097   ** skipped.  Or, if the children are satisfied by an index, the original
   112098   ** BETWEEN term is skipped.
   112099   */
   112100   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
   112101     ExprList *pList = pExpr->x.pList;
   112102     int i;
   112103     static const u8 ops[] = {TK_GE, TK_LE};
   112104     assert( pList!=0 );
   112105     assert( pList->nExpr==2 );
   112106     for(i=0; i<2; i++){
   112107       Expr *pNewExpr;
   112108       int idxNew;
   112109       pNewExpr = sqlite3PExpr(pParse, ops[i],
   112110                              sqlite3ExprDup(db, pExpr->pLeft, 0),
   112111                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
   112112       transferJoinMarkings(pNewExpr, pExpr);
   112113       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   112114       testcase( idxNew==0 );
   112115       exprAnalyze(pSrc, pWC, idxNew);
   112116       pTerm = &pWC->a[idxTerm];
   112117       pWC->a[idxNew].iParent = idxTerm;
   112118     }
   112119     pTerm->nChild = 2;
   112120   }
   112121 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
   112122 
   112123 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   112124   /* Analyze a term that is composed of two or more subterms connected by
   112125   ** an OR operator.
   112126   */
   112127   else if( pExpr->op==TK_OR ){
   112128     assert( pWC->op==TK_AND );
   112129     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
   112130     pTerm = &pWC->a[idxTerm];
   112131   }
   112132 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   112133 
   112134 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   112135   /* Add constraints to reduce the search space on a LIKE or GLOB
   112136   ** operator.
   112137   **
   112138   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
   112139   **
   112140   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
   112141   **
   112142   ** The last character of the prefix "abc" is incremented to form the
   112143   ** termination condition "abd".
   112144   */
   112145   if( pWC->op==TK_AND
   112146    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   112147   ){
   112148     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
   112149     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
   112150     Expr *pNewExpr1;
   112151     Expr *pNewExpr2;
   112152     int idxNew1;
   112153     int idxNew2;
   112154     Token sCollSeqName;  /* Name of collating sequence */
   112155 
   112156     pLeft = pExpr->x.pList->a[1].pExpr;
   112157     pStr2 = sqlite3ExprDup(db, pStr1, 0);
   112158     if( !db->mallocFailed ){
   112159       u8 c, *pC;       /* Last character before the first wildcard */
   112160       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
   112161       c = *pC;
   112162       if( noCase ){
   112163         /* The point is to increment the last character before the first
   112164         ** wildcard.  But if we increment '@', that will push it into the
   112165         ** alphabetic range where case conversions will mess up the
   112166         ** inequality.  To avoid this, make sure to also run the full
   112167         ** LIKE on all candidate expressions by clearing the isComplete flag
   112168         */
   112169         if( c=='A'-1 ) isComplete = 0;
   112170         c = sqlite3UpperToLower[c];
   112171       }
   112172       *pC = c + 1;
   112173     }
   112174     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
   112175     sCollSeqName.n = 6;
   112176     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
   112177     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
   112178            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
   112179            pStr1, 0);
   112180     transferJoinMarkings(pNewExpr1, pExpr);
   112181     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
   112182     testcase( idxNew1==0 );
   112183     exprAnalyze(pSrc, pWC, idxNew1);
   112184     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
   112185     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
   112186            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
   112187            pStr2, 0);
   112188     transferJoinMarkings(pNewExpr2, pExpr);
   112189     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
   112190     testcase( idxNew2==0 );
   112191     exprAnalyze(pSrc, pWC, idxNew2);
   112192     pTerm = &pWC->a[idxTerm];
   112193     if( isComplete ){
   112194       pWC->a[idxNew1].iParent = idxTerm;
   112195       pWC->a[idxNew2].iParent = idxTerm;
   112196       pTerm->nChild = 2;
   112197     }
   112198   }
   112199 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   112200 
   112201 #ifndef SQLITE_OMIT_VIRTUALTABLE
   112202   /* Add a WO_MATCH auxiliary term to the constraint set if the
   112203   ** current expression is of the form:  column MATCH expr.
   112204   ** This information is used by the xBestIndex methods of
   112205   ** virtual tables.  The native query optimizer does not attempt
   112206   ** to do anything with MATCH functions.
   112207   */
   112208   if( isMatchOfColumn(pExpr) ){
   112209     int idxNew;
   112210     Expr *pRight, *pLeft;
   112211     WhereTerm *pNewTerm;
   112212     Bitmask prereqColumn, prereqExpr;
   112213 
   112214     pRight = pExpr->x.pList->a[0].pExpr;
   112215     pLeft = pExpr->x.pList->a[1].pExpr;
   112216     prereqExpr = exprTableUsage(pMaskSet, pRight);
   112217     prereqColumn = exprTableUsage(pMaskSet, pLeft);
   112218     if( (prereqExpr & prereqColumn)==0 ){
   112219       Expr *pNewExpr;
   112220       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
   112221                               0, sqlite3ExprDup(db, pRight, 0), 0);
   112222       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   112223       testcase( idxNew==0 );
   112224       pNewTerm = &pWC->a[idxNew];
   112225       pNewTerm->prereqRight = prereqExpr;
   112226       pNewTerm->leftCursor = pLeft->iTable;
   112227       pNewTerm->u.leftColumn = pLeft->iColumn;
   112228       pNewTerm->eOperator = WO_MATCH;
   112229       pNewTerm->iParent = idxTerm;
   112230       pTerm = &pWC->a[idxTerm];
   112231       pTerm->nChild = 1;
   112232       pTerm->wtFlags |= TERM_COPIED;
   112233       pNewTerm->prereqAll = pTerm->prereqAll;
   112234     }
   112235   }
   112236 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   112237 
   112238 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   112239   /* When sqlite_stat3 histogram data is available an operator of the
   112240   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
   112241   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
   112242   ** virtual term of that form.
   112243   **
   112244   ** Note that the virtual term must be tagged with TERM_VNULL.  This
   112245   ** TERM_VNULL tag will suppress the not-null check at the beginning
   112246   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
   112247   ** the start of the loop will prevent any results from being returned.
   112248   */
   112249   if( pExpr->op==TK_NOTNULL
   112250    && pExpr->pLeft->op==TK_COLUMN
   112251    && pExpr->pLeft->iColumn>=0
   112252    && OptimizationEnabled(db, SQLITE_Stat3)
   112253   ){
   112254     Expr *pNewExpr;
   112255     Expr *pLeft = pExpr->pLeft;
   112256     int idxNew;
   112257     WhereTerm *pNewTerm;
   112258 
   112259     pNewExpr = sqlite3PExpr(pParse, TK_GT,
   112260                             sqlite3ExprDup(db, pLeft, 0),
   112261                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
   112262 
   112263     idxNew = whereClauseInsert(pWC, pNewExpr,
   112264                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
   112265     if( idxNew ){
   112266       pNewTerm = &pWC->a[idxNew];
   112267       pNewTerm->prereqRight = 0;
   112268       pNewTerm->leftCursor = pLeft->iTable;
   112269       pNewTerm->u.leftColumn = pLeft->iColumn;
   112270       pNewTerm->eOperator = WO_GT;
   112271       pNewTerm->iParent = idxTerm;
   112272       pTerm = &pWC->a[idxTerm];
   112273       pTerm->nChild = 1;
   112274       pTerm->wtFlags |= TERM_COPIED;
   112275       pNewTerm->prereqAll = pTerm->prereqAll;
   112276     }
   112277   }
   112278 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   112279 
   112280   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
   112281   ** an index for tables to the left of the join.
   112282   */
   112283   pTerm->prereqRight |= extraRight;
   112284 }
   112285 
   112286 /*
   112287 ** This function searches pList for a entry that matches the iCol-th column
   112288 ** of index pIdx.
   112289 **
   112290 ** If such an expression is found, its index in pList->a[] is returned. If
   112291 ** no expression is found, -1 is returned.
   112292 */
   112293 static int findIndexCol(
   112294   Parse *pParse,                  /* Parse context */
   112295   ExprList *pList,                /* Expression list to search */
   112296   int iBase,                      /* Cursor for table associated with pIdx */
   112297   Index *pIdx,                    /* Index to match column of */
   112298   int iCol                        /* Column of index to match */
   112299 ){
   112300   int i;
   112301   const char *zColl = pIdx->azColl[iCol];
   112302 
   112303   for(i=0; i<pList->nExpr; i++){
   112304     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
   112305     if( p->op==TK_COLUMN
   112306      && p->iColumn==pIdx->aiColumn[iCol]
   112307      && p->iTable==iBase
   112308     ){
   112309       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
   112310       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
   112311         return i;
   112312       }
   112313     }
   112314   }
   112315 
   112316   return -1;
   112317 }
   112318 
   112319 /*
   112320 ** Return true if the DISTINCT expression-list passed as the third argument
   112321 ** is redundant.
   112322 **
   112323 ** A DISTINCT list is redundant if the database contains some subset of
   112324 ** columns that are unique and non-null.
   112325 */
   112326 static int isDistinctRedundant(
   112327   Parse *pParse,            /* Parsing context */
   112328   SrcList *pTabList,        /* The FROM clause */
   112329   WhereClause *pWC,         /* The WHERE clause */
   112330   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
   112331 ){
   112332   Table *pTab;
   112333   Index *pIdx;
   112334   int i;
   112335   int iBase;
   112336 
   112337   /* If there is more than one table or sub-select in the FROM clause of
   112338   ** this query, then it will not be possible to show that the DISTINCT
   112339   ** clause is redundant. */
   112340   if( pTabList->nSrc!=1 ) return 0;
   112341   iBase = pTabList->a[0].iCursor;
   112342   pTab = pTabList->a[0].pTab;
   112343 
   112344   /* If any of the expressions is an IPK column on table iBase, then return
   112345   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
   112346   ** current SELECT is a correlated sub-query.
   112347   */
   112348   for(i=0; i<pDistinct->nExpr; i++){
   112349     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
   112350     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
   112351   }
   112352 
   112353   /* Loop through all indices on the table, checking each to see if it makes
   112354   ** the DISTINCT qualifier redundant. It does so if:
   112355   **
   112356   **   1. The index is itself UNIQUE, and
   112357   **
   112358   **   2. All of the columns in the index are either part of the pDistinct
   112359   **      list, or else the WHERE clause contains a term of the form "col=X",
   112360   **      where X is a constant value. The collation sequences of the
   112361   **      comparison and select-list expressions must match those of the index.
   112362   **
   112363   **   3. All of those index columns for which the WHERE clause does not
   112364   **      contain a "col=X" term are subject to a NOT NULL constraint.
   112365   */
   112366   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   112367     if( !IsUniqueIndex(pIdx) ) continue;
   112368     for(i=0; i<pIdx->nKeyCol; i++){
   112369       i16 iCol = pIdx->aiColumn[i];
   112370       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
   112371         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
   112372         if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
   112373           break;
   112374         }
   112375       }
   112376     }
   112377     if( i==pIdx->nKeyCol ){
   112378       /* This index implies that the DISTINCT qualifier is redundant. */
   112379       return 1;
   112380     }
   112381   }
   112382 
   112383   return 0;
   112384 }
   112385 
   112386 
   112387 /*
   112388 ** Estimate the logarithm of the input value to base 2.
   112389 */
   112390 static LogEst estLog(LogEst N){
   112391   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
   112392 }
   112393 
   112394 /*
   112395 ** Two routines for printing the content of an sqlite3_index_info
   112396 ** structure.  Used for testing and debugging only.  If neither
   112397 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
   112398 ** are no-ops.
   112399 */
   112400 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
   112401 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
   112402   int i;
   112403   if( !sqlite3WhereTrace ) return;
   112404   for(i=0; i<p->nConstraint; i++){
   112405     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
   112406        i,
   112407        p->aConstraint[i].iColumn,
   112408        p->aConstraint[i].iTermOffset,
   112409        p->aConstraint[i].op,
   112410        p->aConstraint[i].usable);
   112411   }
   112412   for(i=0; i<p->nOrderBy; i++){
   112413     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
   112414        i,
   112415        p->aOrderBy[i].iColumn,
   112416        p->aOrderBy[i].desc);
   112417   }
   112418 }
   112419 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
   112420   int i;
   112421   if( !sqlite3WhereTrace ) return;
   112422   for(i=0; i<p->nConstraint; i++){
   112423     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
   112424        i,
   112425        p->aConstraintUsage[i].argvIndex,
   112426        p->aConstraintUsage[i].omit);
   112427   }
   112428   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
   112429   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
   112430   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
   112431   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
   112432   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
   112433 }
   112434 #else
   112435 #define TRACE_IDX_INPUTS(A)
   112436 #define TRACE_IDX_OUTPUTS(A)
   112437 #endif
   112438 
   112439 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   112440 /*
   112441 ** Return TRUE if the WHERE clause term pTerm is of a form where it
   112442 ** could be used with an index to access pSrc, assuming an appropriate
   112443 ** index existed.
   112444 */
   112445 static int termCanDriveIndex(
   112446   WhereTerm *pTerm,              /* WHERE clause term to check */
   112447   struct SrcList_item *pSrc,     /* Table we are trying to access */
   112448   Bitmask notReady               /* Tables in outer loops of the join */
   112449 ){
   112450   char aff;
   112451   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
   112452   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
   112453   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
   112454   if( pTerm->u.leftColumn<0 ) return 0;
   112455   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
   112456   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
   112457   return 1;
   112458 }
   112459 #endif
   112460 
   112461 
   112462 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   112463 /*
   112464 ** Generate code to construct the Index object for an automatic index
   112465 ** and to set up the WhereLevel object pLevel so that the code generator
   112466 ** makes use of the automatic index.
   112467 */
   112468 static void constructAutomaticIndex(
   112469   Parse *pParse,              /* The parsing context */
   112470   WhereClause *pWC,           /* The WHERE clause */
   112471   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
   112472   Bitmask notReady,           /* Mask of cursors that are not available */
   112473   WhereLevel *pLevel          /* Write new index here */
   112474 ){
   112475   int nKeyCol;                /* Number of columns in the constructed index */
   112476   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   112477   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   112478   Index *pIdx;                /* Object describing the transient index */
   112479   Vdbe *v;                    /* Prepared statement under construction */
   112480   int addrInit;               /* Address of the initialization bypass jump */
   112481   Table *pTable;              /* The table being indexed */
   112482   int addrTop;                /* Top of the index fill loop */
   112483   int regRecord;              /* Register holding an index record */
   112484   int n;                      /* Column counter */
   112485   int i;                      /* Loop counter */
   112486   int mxBitCol;               /* Maximum column in pSrc->colUsed */
   112487   CollSeq *pColl;             /* Collating sequence to on a column */
   112488   WhereLoop *pLoop;           /* The Loop object */
   112489   char *zNotUsed;             /* Extra space on the end of pIdx */
   112490   Bitmask idxCols;            /* Bitmap of columns used for indexing */
   112491   Bitmask extraCols;          /* Bitmap of additional columns */
   112492   u8 sentWarning = 0;         /* True if a warnning has been issued */
   112493 
   112494   /* Generate code to skip over the creation and initialization of the
   112495   ** transient index on 2nd and subsequent iterations of the loop. */
   112496   v = pParse->pVdbe;
   112497   assert( v!=0 );
   112498   addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
   112499 
   112500   /* Count the number of columns that will be added to the index
   112501   ** and used to match WHERE clause constraints */
   112502   nKeyCol = 0;
   112503   pTable = pSrc->pTab;
   112504   pWCEnd = &pWC->a[pWC->nTerm];
   112505   pLoop = pLevel->pWLoop;
   112506   idxCols = 0;
   112507   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   112508     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   112509       int iCol = pTerm->u.leftColumn;
   112510       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
   112511       testcase( iCol==BMS );
   112512       testcase( iCol==BMS-1 );
   112513       if( !sentWarning ){
   112514         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
   112515             "automatic index on %s(%s)", pTable->zName,
   112516             pTable->aCol[iCol].zName);
   112517         sentWarning = 1;
   112518       }
   112519       if( (idxCols & cMask)==0 ){
   112520         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
   112521         pLoop->aLTerm[nKeyCol++] = pTerm;
   112522         idxCols |= cMask;
   112523       }
   112524     }
   112525   }
   112526   assert( nKeyCol>0 );
   112527   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
   112528   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
   112529                      | WHERE_AUTO_INDEX;
   112530 
   112531   /* Count the number of additional columns needed to create a
   112532   ** covering index.  A "covering index" is an index that contains all
   112533   ** columns that are needed by the query.  With a covering index, the
   112534   ** original table never needs to be accessed.  Automatic indices must
   112535   ** be a covering index because the index will not be updated if the
   112536   ** original table changes and the index and table cannot both be used
   112537   ** if they go out of sync.
   112538   */
   112539   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
   112540   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
   112541   testcase( pTable->nCol==BMS-1 );
   112542   testcase( pTable->nCol==BMS-2 );
   112543   for(i=0; i<mxBitCol; i++){
   112544     if( extraCols & MASKBIT(i) ) nKeyCol++;
   112545   }
   112546   if( pSrc->colUsed & MASKBIT(BMS-1) ){
   112547     nKeyCol += pTable->nCol - BMS + 1;
   112548   }
   112549   pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
   112550 
   112551   /* Construct the Index object to describe this index */
   112552   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
   112553   if( pIdx==0 ) return;
   112554   pLoop->u.btree.pIndex = pIdx;
   112555   pIdx->zName = "auto-index";
   112556   pIdx->pTable = pTable;
   112557   n = 0;
   112558   idxCols = 0;
   112559   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   112560     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   112561       int iCol = pTerm->u.leftColumn;
   112562       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
   112563       testcase( iCol==BMS-1 );
   112564       testcase( iCol==BMS );
   112565       if( (idxCols & cMask)==0 ){
   112566         Expr *pX = pTerm->pExpr;
   112567         idxCols |= cMask;
   112568         pIdx->aiColumn[n] = pTerm->u.leftColumn;
   112569         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   112570         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
   112571         n++;
   112572       }
   112573     }
   112574   }
   112575   assert( (u32)n==pLoop->u.btree.nEq );
   112576 
   112577   /* Add additional columns needed to make the automatic index into
   112578   ** a covering index */
   112579   for(i=0; i<mxBitCol; i++){
   112580     if( extraCols & MASKBIT(i) ){
   112581       pIdx->aiColumn[n] = i;
   112582       pIdx->azColl[n] = "BINARY";
   112583       n++;
   112584     }
   112585   }
   112586   if( pSrc->colUsed & MASKBIT(BMS-1) ){
   112587     for(i=BMS-1; i<pTable->nCol; i++){
   112588       pIdx->aiColumn[n] = i;
   112589       pIdx->azColl[n] = "BINARY";
   112590       n++;
   112591     }
   112592   }
   112593   assert( n==nKeyCol );
   112594   pIdx->aiColumn[n] = -1;
   112595   pIdx->azColl[n] = "BINARY";
   112596 
   112597   /* Create the automatic index */
   112598   assert( pLevel->iIdxCur>=0 );
   112599   pLevel->iIdxCur = pParse->nTab++;
   112600   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
   112601   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   112602   VdbeComment((v, "for %s", pTable->zName));
   112603 
   112604   /* Fill the automatic index with content */
   112605   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
   112606   regRecord = sqlite3GetTempReg(pParse);
   112607   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
   112608   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
   112609   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   112610   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
   112611   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
   112612   sqlite3VdbeJumpHere(v, addrTop);
   112613   sqlite3ReleaseTempReg(pParse, regRecord);
   112614 
   112615   /* Jump here when skipping the initialization */
   112616   sqlite3VdbeJumpHere(v, addrInit);
   112617 }
   112618 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   112619 
   112620 #ifndef SQLITE_OMIT_VIRTUALTABLE
   112621 /*
   112622 ** Allocate and populate an sqlite3_index_info structure. It is the
   112623 ** responsibility of the caller to eventually release the structure
   112624 ** by passing the pointer returned by this function to sqlite3_free().
   112625 */
   112626 static sqlite3_index_info *allocateIndexInfo(
   112627   Parse *pParse,
   112628   WhereClause *pWC,
   112629   struct SrcList_item *pSrc,
   112630   ExprList *pOrderBy
   112631 ){
   112632   int i, j;
   112633   int nTerm;
   112634   struct sqlite3_index_constraint *pIdxCons;
   112635   struct sqlite3_index_orderby *pIdxOrderBy;
   112636   struct sqlite3_index_constraint_usage *pUsage;
   112637   WhereTerm *pTerm;
   112638   int nOrderBy;
   112639   sqlite3_index_info *pIdxInfo;
   112640 
   112641   /* Count the number of possible WHERE clause constraints referring
   112642   ** to this virtual table */
   112643   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   112644     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   112645     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
   112646     testcase( pTerm->eOperator & WO_IN );
   112647     testcase( pTerm->eOperator & WO_ISNULL );
   112648     testcase( pTerm->eOperator & WO_ALL );
   112649     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
   112650     if( pTerm->wtFlags & TERM_VNULL ) continue;
   112651     nTerm++;
   112652   }
   112653 
   112654   /* If the ORDER BY clause contains only columns in the current
   112655   ** virtual table then allocate space for the aOrderBy part of
   112656   ** the sqlite3_index_info structure.
   112657   */
   112658   nOrderBy = 0;
   112659   if( pOrderBy ){
   112660     int n = pOrderBy->nExpr;
   112661     for(i=0; i<n; i++){
   112662       Expr *pExpr = pOrderBy->a[i].pExpr;
   112663       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
   112664     }
   112665     if( i==n){
   112666       nOrderBy = n;
   112667     }
   112668   }
   112669 
   112670   /* Allocate the sqlite3_index_info structure
   112671   */
   112672   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
   112673                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
   112674                            + sizeof(*pIdxOrderBy)*nOrderBy );
   112675   if( pIdxInfo==0 ){
   112676     sqlite3ErrorMsg(pParse, "out of memory");
   112677     return 0;
   112678   }
   112679 
   112680   /* Initialize the structure.  The sqlite3_index_info structure contains
   112681   ** many fields that are declared "const" to prevent xBestIndex from
   112682   ** changing them.  We have to do some funky casting in order to
   112683   ** initialize those fields.
   112684   */
   112685   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
   112686   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   112687   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
   112688   *(int*)&pIdxInfo->nConstraint = nTerm;
   112689   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
   112690   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
   112691   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
   112692   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
   112693                                                                    pUsage;
   112694 
   112695   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   112696     u8 op;
   112697     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   112698     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
   112699     testcase( pTerm->eOperator & WO_IN );
   112700     testcase( pTerm->eOperator & WO_ISNULL );
   112701     testcase( pTerm->eOperator & WO_ALL );
   112702     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
   112703     if( pTerm->wtFlags & TERM_VNULL ) continue;
   112704     pIdxCons[j].iColumn = pTerm->u.leftColumn;
   112705     pIdxCons[j].iTermOffset = i;
   112706     op = (u8)pTerm->eOperator & WO_ALL;
   112707     if( op==WO_IN ) op = WO_EQ;
   112708     pIdxCons[j].op = op;
   112709     /* The direct assignment in the previous line is possible only because
   112710     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
   112711     ** following asserts verify this fact. */
   112712     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
   112713     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
   112714     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
   112715     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
   112716     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
   112717     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
   112718     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
   112719     j++;
   112720   }
   112721   for(i=0; i<nOrderBy; i++){
   112722     Expr *pExpr = pOrderBy->a[i].pExpr;
   112723     pIdxOrderBy[i].iColumn = pExpr->iColumn;
   112724     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
   112725   }
   112726 
   112727   return pIdxInfo;
   112728 }
   112729 
   112730 /*
   112731 ** The table object reference passed as the second argument to this function
   112732 ** must represent a virtual table. This function invokes the xBestIndex()
   112733 ** method of the virtual table with the sqlite3_index_info object that
   112734 ** comes in as the 3rd argument to this function.
   112735 **
   112736 ** If an error occurs, pParse is populated with an error message and a
   112737 ** non-zero value is returned. Otherwise, 0 is returned and the output
   112738 ** part of the sqlite3_index_info structure is left populated.
   112739 **
   112740 ** Whether or not an error is returned, it is the responsibility of the
   112741 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
   112742 ** that this is required.
   112743 */
   112744 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   112745   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
   112746   int i;
   112747   int rc;
   112748 
   112749   TRACE_IDX_INPUTS(p);
   112750   rc = pVtab->pModule->xBestIndex(pVtab, p);
   112751   TRACE_IDX_OUTPUTS(p);
   112752 
   112753   if( rc!=SQLITE_OK ){
   112754     if( rc==SQLITE_NOMEM ){
   112755       pParse->db->mallocFailed = 1;
   112756     }else if( !pVtab->zErrMsg ){
   112757       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
   112758     }else{
   112759       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
   112760     }
   112761   }
   112762   sqlite3_free(pVtab->zErrMsg);
   112763   pVtab->zErrMsg = 0;
   112764 
   112765   for(i=0; i<p->nConstraint; i++){
   112766     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
   112767       sqlite3ErrorMsg(pParse,
   112768           "table %s: xBestIndex returned an invalid plan", pTab->zName);
   112769     }
   112770   }
   112771 
   112772   return pParse->nErr;
   112773 }
   112774 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
   112775 
   112776 
   112777 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   112778 /*
   112779 ** Estimate the location of a particular key among all keys in an
   112780 ** index.  Store the results in aStat as follows:
   112781 **
   112782 **    aStat[0]      Est. number of rows less than pVal
   112783 **    aStat[1]      Est. number of rows equal to pVal
   112784 **
   112785 ** Return SQLITE_OK on success.
   112786 */
   112787 static void whereKeyStats(
   112788   Parse *pParse,              /* Database connection */
   112789   Index *pIdx,                /* Index to consider domain of */
   112790   UnpackedRecord *pRec,       /* Vector of values to consider */
   112791   int roundUp,                /* Round up if true.  Round down if false */
   112792   tRowcnt *aStat              /* OUT: stats written here */
   112793 ){
   112794   IndexSample *aSample = pIdx->aSample;
   112795   int iCol;                   /* Index of required stats in anEq[] etc. */
   112796   int iMin = 0;               /* Smallest sample not yet tested */
   112797   int i = pIdx->nSample;      /* Smallest sample larger than or equal to pRec */
   112798   int iTest;                  /* Next sample to test */
   112799   int res;                    /* Result of comparison operation */
   112800 
   112801 #ifndef SQLITE_DEBUG
   112802   UNUSED_PARAMETER( pParse );
   112803 #endif
   112804   assert( pRec!=0 );
   112805   iCol = pRec->nField - 1;
   112806   assert( pIdx->nSample>0 );
   112807   assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
   112808   do{
   112809     iTest = (iMin+i)/2;
   112810     res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec, 0);
   112811     if( res<0 ){
   112812       iMin = iTest+1;
   112813     }else{
   112814       i = iTest;
   112815     }
   112816   }while( res && iMin<i );
   112817 
   112818 #ifdef SQLITE_DEBUG
   112819   /* The following assert statements check that the binary search code
   112820   ** above found the right answer. This block serves no purpose other
   112821   ** than to invoke the asserts.  */
   112822   if( res==0 ){
   112823     /* If (res==0) is true, then sample $i must be equal to pRec */
   112824     assert( i<pIdx->nSample );
   112825     assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)
   112826          || pParse->db->mallocFailed );
   112827   }else{
   112828     /* Otherwise, pRec must be smaller than sample $i and larger than
   112829     ** sample ($i-1).  */
   112830     assert( i==pIdx->nSample
   112831          || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)>0
   112832          || pParse->db->mallocFailed );
   112833     assert( i==0
   112834          || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec, 0)<0
   112835          || pParse->db->mallocFailed );
   112836   }
   112837 #endif /* ifdef SQLITE_DEBUG */
   112838 
   112839   /* At this point, aSample[i] is the first sample that is greater than
   112840   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
   112841   ** than pVal.  If aSample[i]==pVal, then res==0.
   112842   */
   112843   if( res==0 ){
   112844     aStat[0] = aSample[i].anLt[iCol];
   112845     aStat[1] = aSample[i].anEq[iCol];
   112846   }else{
   112847     tRowcnt iLower, iUpper, iGap;
   112848     if( i==0 ){
   112849       iLower = 0;
   112850       iUpper = aSample[0].anLt[iCol];
   112851     }else{
   112852       i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
   112853       iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
   112854       iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
   112855     }
   112856     aStat[1] = pIdx->aAvgEq[iCol];
   112857     if( iLower>=iUpper ){
   112858       iGap = 0;
   112859     }else{
   112860       iGap = iUpper - iLower;
   112861     }
   112862     if( roundUp ){
   112863       iGap = (iGap*2)/3;
   112864     }else{
   112865       iGap = iGap/3;
   112866     }
   112867     aStat[0] = iLower + iGap;
   112868   }
   112869 }
   112870 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   112871 
   112872 /*
   112873 ** If it is not NULL, pTerm is a term that provides an upper or lower
   112874 ** bound on a range scan. Without considering pTerm, it is estimated
   112875 ** that the scan will visit nNew rows. This function returns the number
   112876 ** estimated to be visited after taking pTerm into account.
   112877 **
   112878 ** If the user explicitly specified a likelihood() value for this term,
   112879 ** then the return value is the likelihood multiplied by the number of
   112880 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
   112881 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
   112882 */
   112883 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
   112884   LogEst nRet = nNew;
   112885   if( pTerm ){
   112886     if( pTerm->truthProb<=0 ){
   112887       nRet += pTerm->truthProb;
   112888     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
   112889       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
   112890     }
   112891   }
   112892   return nRet;
   112893 }
   112894 
   112895 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   112896 /*
   112897 ** This function is called to estimate the number of rows visited by a
   112898 ** range-scan on a skip-scan index. For example:
   112899 **
   112900 **   CREATE INDEX i1 ON t1(a, b, c);
   112901 **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
   112902 **
   112903 ** Value pLoop->nOut is currently set to the estimated number of rows
   112904 ** visited for scanning (a=? AND b=?). This function reduces that estimate
   112905 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
   112906 ** on the stat4 data for the index. this scan will be peformed multiple
   112907 ** times (once for each (a,b) combination that matches a=?) is dealt with
   112908 ** by the caller.
   112909 **
   112910 ** It does this by scanning through all stat4 samples, comparing values
   112911 ** extracted from pLower and pUpper with the corresponding column in each
   112912 ** sample. If L and U are the number of samples found to be less than or
   112913 ** equal to the values extracted from pLower and pUpper respectively, and
   112914 ** N is the total number of samples, the pLoop->nOut value is adjusted
   112915 ** as follows:
   112916 **
   112917 **   nOut = nOut * ( min(U - L, 1) / N )
   112918 **
   112919 ** If pLower is NULL, or a value cannot be extracted from the term, L is
   112920 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
   112921 ** U is set to N.
   112922 **
   112923 ** Normally, this function sets *pbDone to 1 before returning. However,
   112924 ** if no value can be extracted from either pLower or pUpper (and so the
   112925 ** estimate of the number of rows delivered remains unchanged), *pbDone
   112926 ** is left as is.
   112927 **
   112928 ** If an error occurs, an SQLite error code is returned. Otherwise,
   112929 ** SQLITE_OK.
   112930 */
   112931 static int whereRangeSkipScanEst(
   112932   Parse *pParse,       /* Parsing & code generating context */
   112933   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   112934   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   112935   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
   112936   int *pbDone          /* Set to true if at least one expr. value extracted */
   112937 ){
   112938   Index *p = pLoop->u.btree.pIndex;
   112939   int nEq = pLoop->u.btree.nEq;
   112940   sqlite3 *db = pParse->db;
   112941   int nLower = -1;
   112942   int nUpper = p->nSample+1;
   112943   int rc = SQLITE_OK;
   112944   int iCol = p->aiColumn[nEq];
   112945   u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
   112946   CollSeq *pColl;
   112947 
   112948   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
   112949   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
   112950   sqlite3_value *pVal = 0;        /* Value extracted from record */
   112951 
   112952   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
   112953   if( pLower ){
   112954     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
   112955     nLower = 0;
   112956   }
   112957   if( pUpper && rc==SQLITE_OK ){
   112958     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
   112959     nUpper = p2 ? 0 : p->nSample;
   112960   }
   112961 
   112962   if( p1 || p2 ){
   112963     int i;
   112964     int nDiff;
   112965     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
   112966       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
   112967       if( rc==SQLITE_OK && p1 ){
   112968         int res = sqlite3MemCompare(p1, pVal, pColl);
   112969         if( res>=0 ) nLower++;
   112970       }
   112971       if( rc==SQLITE_OK && p2 ){
   112972         int res = sqlite3MemCompare(p2, pVal, pColl);
   112973         if( res>=0 ) nUpper++;
   112974       }
   112975     }
   112976     nDiff = (nUpper - nLower);
   112977     if( nDiff<=0 ) nDiff = 1;
   112978 
   112979     /* If there is both an upper and lower bound specified, and the
   112980     ** comparisons indicate that they are close together, use the fallback
   112981     ** method (assume that the scan visits 1/64 of the rows) for estimating
   112982     ** the number of rows visited. Otherwise, estimate the number of rows
   112983     ** using the method described in the header comment for this function. */
   112984     if( nDiff!=1 || pUpper==0 || pLower==0 ){
   112985       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
   112986       pLoop->nOut -= nAdjust;
   112987       *pbDone = 1;
   112988       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
   112989                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
   112990     }
   112991 
   112992   }else{
   112993     assert( *pbDone==0 );
   112994   }
   112995 
   112996   sqlite3ValueFree(p1);
   112997   sqlite3ValueFree(p2);
   112998   sqlite3ValueFree(pVal);
   112999 
   113000   return rc;
   113001 }
   113002 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   113003 
   113004 /*
   113005 ** This function is used to estimate the number of rows that will be visited
   113006 ** by scanning an index for a range of values. The range may have an upper
   113007 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
   113008 ** and lower bounds are represented by pLower and pUpper respectively. For
   113009 ** example, assuming that index p is on t1(a):
   113010 **
   113011 **   ... FROM t1 WHERE a > ? AND a < ? ...
   113012 **                    |_____|   |_____|
   113013 **                       |         |
   113014 **                     pLower    pUpper
   113015 **
   113016 ** If either of the upper or lower bound is not present, then NULL is passed in
   113017 ** place of the corresponding WhereTerm.
   113018 **
   113019 ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
   113020 ** column subject to the range constraint. Or, equivalently, the number of
   113021 ** equality constraints optimized by the proposed index scan. For example,
   113022 ** assuming index p is on t1(a, b), and the SQL query is:
   113023 **
   113024 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
   113025 **
   113026 ** then nEq is set to 1 (as the range restricted column, b, is the second
   113027 ** left-most column of the index). Or, if the query is:
   113028 **
   113029 **   ... FROM t1 WHERE a > ? AND a < ? ...
   113030 **
   113031 ** then nEq is set to 0.
   113032 **
   113033 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
   113034 ** number of rows that the index scan is expected to visit without
   113035 ** considering the range constraints. If nEq is 0, this is the number of
   113036 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
   113037 ** to account for the range contraints pLower and pUpper.
   113038 **
   113039 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
   113040 ** used, a single range inequality reduces the search space by a factor of 4.
   113041 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
   113042 ** rows visited by a factor of 64.
   113043 */
   113044 static int whereRangeScanEst(
   113045   Parse *pParse,       /* Parsing & code generating context */
   113046   WhereLoopBuilder *pBuilder,
   113047   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   113048   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   113049   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
   113050 ){
   113051   int rc = SQLITE_OK;
   113052   int nOut = pLoop->nOut;
   113053   LogEst nNew;
   113054 
   113055 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   113056   Index *p = pLoop->u.btree.pIndex;
   113057   int nEq = pLoop->u.btree.nEq;
   113058 
   113059   if( p->nSample>0
   113060    && nEq<p->nSampleCol
   113061    && OptimizationEnabled(pParse->db, SQLITE_Stat3)
   113062   ){
   113063     if( nEq==pBuilder->nRecValid ){
   113064       UnpackedRecord *pRec = pBuilder->pRec;
   113065       tRowcnt a[2];
   113066       u8 aff;
   113067 
   113068       /* Variable iLower will be set to the estimate of the number of rows in
   113069       ** the index that are less than the lower bound of the range query. The
   113070       ** lower bound being the concatenation of $P and $L, where $P is the
   113071       ** key-prefix formed by the nEq values matched against the nEq left-most
   113072       ** columns of the index, and $L is the value in pLower.
   113073       **
   113074       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
   113075       ** is not a simple variable or literal value), the lower bound of the
   113076       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
   113077       ** if $L is available, whereKeyStats() is called for both ($P) and
   113078       ** ($P:$L) and the larger of the two returned values used.
   113079       **
   113080       ** Similarly, iUpper is to be set to the estimate of the number of rows
   113081       ** less than the upper bound of the range query. Where the upper bound
   113082       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
   113083       ** of iUpper are requested of whereKeyStats() and the smaller used.
   113084       */
   113085       tRowcnt iLower;
   113086       tRowcnt iUpper;
   113087 
   113088       if( nEq==p->nKeyCol ){
   113089         aff = SQLITE_AFF_INTEGER;
   113090       }else{
   113091         aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
   113092       }
   113093       /* Determine iLower and iUpper using ($P) only. */
   113094       if( nEq==0 ){
   113095         iLower = 0;
   113096         iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
   113097       }else{
   113098         /* Note: this call could be optimized away - since the same values must
   113099         ** have been requested when testing key $P in whereEqualScanEst().  */
   113100         whereKeyStats(pParse, p, pRec, 0, a);
   113101         iLower = a[0];
   113102         iUpper = a[0] + a[1];
   113103       }
   113104 
   113105       /* If possible, improve on the iLower estimate using ($P:$L). */
   113106       if( pLower ){
   113107         int bOk;                    /* True if value is extracted from pExpr */
   113108         Expr *pExpr = pLower->pExpr->pRight;
   113109         assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
   113110         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
   113111         if( rc==SQLITE_OK && bOk ){
   113112           tRowcnt iNew;
   113113           whereKeyStats(pParse, p, pRec, 0, a);
   113114           iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
   113115           if( iNew>iLower ) iLower = iNew;
   113116           nOut--;
   113117         }
   113118       }
   113119 
   113120       /* If possible, improve on the iUpper estimate using ($P:$U). */
   113121       if( pUpper ){
   113122         int bOk;                    /* True if value is extracted from pExpr */
   113123         Expr *pExpr = pUpper->pExpr->pRight;
   113124         assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
   113125         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
   113126         if( rc==SQLITE_OK && bOk ){
   113127           tRowcnt iNew;
   113128           whereKeyStats(pParse, p, pRec, 1, a);
   113129           iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
   113130           if( iNew<iUpper ) iUpper = iNew;
   113131           nOut--;
   113132         }
   113133       }
   113134 
   113135       pBuilder->pRec = pRec;
   113136       if( rc==SQLITE_OK ){
   113137         if( iUpper>iLower ){
   113138           nNew = sqlite3LogEst(iUpper - iLower);
   113139         }else{
   113140           nNew = 10;        assert( 10==sqlite3LogEst(2) );
   113141         }
   113142         if( nNew<nOut ){
   113143           nOut = nNew;
   113144         }
   113145         pLoop->nOut = (LogEst)nOut;
   113146         WHERETRACE(0x10, ("range scan regions: %u..%u  est=%d\n",
   113147                            (u32)iLower, (u32)iUpper, nOut));
   113148         return SQLITE_OK;
   113149       }
   113150     }else{
   113151       int bDone = 0;
   113152       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
   113153       if( bDone ) return rc;
   113154     }
   113155   }
   113156 #else
   113157   UNUSED_PARAMETER(pParse);
   113158   UNUSED_PARAMETER(pBuilder);
   113159 #endif
   113160   assert( pLower || pUpper );
   113161   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
   113162   nNew = whereRangeAdjust(pLower, nOut);
   113163   nNew = whereRangeAdjust(pUpper, nNew);
   113164 
   113165   /* TUNING: If there is both an upper and lower limit, assume the range is
   113166   ** reduced by an additional 75%. This means that, by default, an open-ended
   113167   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
   113168   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
   113169   ** match 1/64 of the index. */
   113170   if( pLower && pUpper ) nNew -= 20;
   113171 
   113172   nOut -= (pLower!=0) + (pUpper!=0);
   113173   if( nNew<10 ) nNew = 10;
   113174   if( nNew<nOut ) nOut = nNew;
   113175   pLoop->nOut = (LogEst)nOut;
   113176   return rc;
   113177 }
   113178 
   113179 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   113180 /*
   113181 ** Estimate the number of rows that will be returned based on
   113182 ** an equality constraint x=VALUE and where that VALUE occurs in
   113183 ** the histogram data.  This only works when x is the left-most
   113184 ** column of an index and sqlite_stat3 histogram data is available
   113185 ** for that index.  When pExpr==NULL that means the constraint is
   113186 ** "x IS NULL" instead of "x=VALUE".
   113187 **
   113188 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   113189 ** If unable to make an estimate, leave *pnRow unchanged and return
   113190 ** non-zero.
   113191 **
   113192 ** This routine can fail if it is unable to load a collating sequence
   113193 ** required for string comparison, or if unable to allocate memory
   113194 ** for a UTF conversion required for comparison.  The error is stored
   113195 ** in the pParse structure.
   113196 */
   113197 static int whereEqualScanEst(
   113198   Parse *pParse,       /* Parsing & code generating context */
   113199   WhereLoopBuilder *pBuilder,
   113200   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
   113201   tRowcnt *pnRow       /* Write the revised row estimate here */
   113202 ){
   113203   Index *p = pBuilder->pNew->u.btree.pIndex;
   113204   int nEq = pBuilder->pNew->u.btree.nEq;
   113205   UnpackedRecord *pRec = pBuilder->pRec;
   113206   u8 aff;                   /* Column affinity */
   113207   int rc;                   /* Subfunction return code */
   113208   tRowcnt a[2];             /* Statistics */
   113209   int bOk;
   113210 
   113211   assert( nEq>=1 );
   113212   assert( nEq<=p->nColumn );
   113213   assert( p->aSample!=0 );
   113214   assert( p->nSample>0 );
   113215   assert( pBuilder->nRecValid<nEq );
   113216 
   113217   /* If values are not available for all fields of the index to the left
   113218   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
   113219   if( pBuilder->nRecValid<(nEq-1) ){
   113220     return SQLITE_NOTFOUND;
   113221   }
   113222 
   113223   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
   113224   ** below would return the same value.  */
   113225   if( nEq>=p->nColumn ){
   113226     *pnRow = 1;
   113227     return SQLITE_OK;
   113228   }
   113229 
   113230   aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
   113231   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
   113232   pBuilder->pRec = pRec;
   113233   if( rc!=SQLITE_OK ) return rc;
   113234   if( bOk==0 ) return SQLITE_NOTFOUND;
   113235   pBuilder->nRecValid = nEq;
   113236 
   113237   whereKeyStats(pParse, p, pRec, 0, a);
   113238   WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
   113239   *pnRow = a[1];
   113240 
   113241   return rc;
   113242 }
   113243 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   113244 
   113245 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   113246 /*
   113247 ** Estimate the number of rows that will be returned based on
   113248 ** an IN constraint where the right-hand side of the IN operator
   113249 ** is a list of values.  Example:
   113250 **
   113251 **        WHERE x IN (1,2,3,4)
   113252 **
   113253 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   113254 ** If unable to make an estimate, leave *pnRow unchanged and return
   113255 ** non-zero.
   113256 **
   113257 ** This routine can fail if it is unable to load a collating sequence
   113258 ** required for string comparison, or if unable to allocate memory
   113259 ** for a UTF conversion required for comparison.  The error is stored
   113260 ** in the pParse structure.
   113261 */
   113262 static int whereInScanEst(
   113263   Parse *pParse,       /* Parsing & code generating context */
   113264   WhereLoopBuilder *pBuilder,
   113265   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
   113266   tRowcnt *pnRow       /* Write the revised row estimate here */
   113267 ){
   113268   Index *p = pBuilder->pNew->u.btree.pIndex;
   113269   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
   113270   int nRecValid = pBuilder->nRecValid;
   113271   int rc = SQLITE_OK;     /* Subfunction return code */
   113272   tRowcnt nEst;           /* Number of rows for a single term */
   113273   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
   113274   int i;                  /* Loop counter */
   113275 
   113276   assert( p->aSample!=0 );
   113277   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
   113278     nEst = nRow0;
   113279     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
   113280     nRowEst += nEst;
   113281     pBuilder->nRecValid = nRecValid;
   113282   }
   113283 
   113284   if( rc==SQLITE_OK ){
   113285     if( nRowEst > nRow0 ) nRowEst = nRow0;
   113286     *pnRow = nRowEst;
   113287     WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst));
   113288   }
   113289   assert( pBuilder->nRecValid==nRecValid );
   113290   return rc;
   113291 }
   113292 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   113293 
   113294 /*
   113295 ** Disable a term in the WHERE clause.  Except, do not disable the term
   113296 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
   113297 ** or USING clause of that join.
   113298 **
   113299 ** Consider the term t2.z='ok' in the following queries:
   113300 **
   113301 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
   113302 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
   113303 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
   113304 **
   113305 ** The t2.z='ok' is disabled in the in (2) because it originates
   113306 ** in the ON clause.  The term is disabled in (3) because it is not part
   113307 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
   113308 **
   113309 ** Disabling a term causes that term to not be tested in the inner loop
   113310 ** of the join.  Disabling is an optimization.  When terms are satisfied
   113311 ** by indices, we disable them to prevent redundant tests in the inner
   113312 ** loop.  We would get the correct results if nothing were ever disabled,
   113313 ** but joins might run a little slower.  The trick is to disable as much
   113314 ** as we can without disabling too much.  If we disabled in (1), we'd get
   113315 ** the wrong answer.  See ticket #813.
   113316 */
   113317 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
   113318   if( pTerm
   113319       && (pTerm->wtFlags & TERM_CODED)==0
   113320       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   113321       && (pLevel->notReady & pTerm->prereqAll)==0
   113322   ){
   113323     pTerm->wtFlags |= TERM_CODED;
   113324     if( pTerm->iParent>=0 ){
   113325       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
   113326       if( (--pOther->nChild)==0 ){
   113327         disableTerm(pLevel, pOther);
   113328       }
   113329     }
   113330   }
   113331 }
   113332 
   113333 /*
   113334 ** Code an OP_Affinity opcode to apply the column affinity string zAff
   113335 ** to the n registers starting at base.
   113336 **
   113337 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
   113338 ** beginning and end of zAff are ignored.  If all entries in zAff are
   113339 ** SQLITE_AFF_NONE, then no code gets generated.
   113340 **
   113341 ** This routine makes its own copy of zAff so that the caller is free
   113342 ** to modify zAff after this routine returns.
   113343 */
   113344 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
   113345   Vdbe *v = pParse->pVdbe;
   113346   if( zAff==0 ){
   113347     assert( pParse->db->mallocFailed );
   113348     return;
   113349   }
   113350   assert( v!=0 );
   113351 
   113352   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
   113353   ** and end of the affinity string.
   113354   */
   113355   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
   113356     n--;
   113357     base++;
   113358     zAff++;
   113359   }
   113360   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
   113361     n--;
   113362   }
   113363 
   113364   /* Code the OP_Affinity opcode if there is anything left to do. */
   113365   if( n>0 ){
   113366     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
   113367     sqlite3VdbeChangeP4(v, -1, zAff, n);
   113368     sqlite3ExprCacheAffinityChange(pParse, base, n);
   113369   }
   113370 }
   113371 
   113372 
   113373 /*
   113374 ** Generate code for a single equality term of the WHERE clause.  An equality
   113375 ** term can be either X=expr or X IN (...).   pTerm is the term to be
   113376 ** coded.
   113377 **
   113378 ** The current value for the constraint is left in register iReg.
   113379 **
   113380 ** For a constraint of the form X=expr, the expression is evaluated and its
   113381 ** result is left on the stack.  For constraints of the form X IN (...)
   113382 ** this routine sets up a loop that will iterate over all values of X.
   113383 */
   113384 static int codeEqualityTerm(
   113385   Parse *pParse,      /* The parsing context */
   113386   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
   113387   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
   113388   int iEq,            /* Index of the equality term within this level */
   113389   int bRev,           /* True for reverse-order IN operations */
   113390   int iTarget         /* Attempt to leave results in this register */
   113391 ){
   113392   Expr *pX = pTerm->pExpr;
   113393   Vdbe *v = pParse->pVdbe;
   113394   int iReg;                  /* Register holding results */
   113395 
   113396   assert( iTarget>0 );
   113397   if( pX->op==TK_EQ ){
   113398     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
   113399   }else if( pX->op==TK_ISNULL ){
   113400     iReg = iTarget;
   113401     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
   113402 #ifndef SQLITE_OMIT_SUBQUERY
   113403   }else{
   113404     int eType;
   113405     int iTab;
   113406     struct InLoop *pIn;
   113407     WhereLoop *pLoop = pLevel->pWLoop;
   113408 
   113409     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
   113410       && pLoop->u.btree.pIndex!=0
   113411       && pLoop->u.btree.pIndex->aSortOrder[iEq]
   113412     ){
   113413       testcase( iEq==0 );
   113414       testcase( bRev );
   113415       bRev = !bRev;
   113416     }
   113417     assert( pX->op==TK_IN );
   113418     iReg = iTarget;
   113419     eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
   113420     if( eType==IN_INDEX_INDEX_DESC ){
   113421       testcase( bRev );
   113422       bRev = !bRev;
   113423     }
   113424     iTab = pX->iTable;
   113425     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
   113426     VdbeCoverageIf(v, bRev);
   113427     VdbeCoverageIf(v, !bRev);
   113428     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
   113429     pLoop->wsFlags |= WHERE_IN_ABLE;
   113430     if( pLevel->u.in.nIn==0 ){
   113431       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   113432     }
   113433     pLevel->u.in.nIn++;
   113434     pLevel->u.in.aInLoop =
   113435        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
   113436                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
   113437     pIn = pLevel->u.in.aInLoop;
   113438     if( pIn ){
   113439       pIn += pLevel->u.in.nIn - 1;
   113440       pIn->iCur = iTab;
   113441       if( eType==IN_INDEX_ROWID ){
   113442         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
   113443       }else{
   113444         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
   113445       }
   113446       pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
   113447       sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
   113448     }else{
   113449       pLevel->u.in.nIn = 0;
   113450     }
   113451 #endif
   113452   }
   113453   disableTerm(pLevel, pTerm);
   113454   return iReg;
   113455 }
   113456 
   113457 /*
   113458 ** Generate code that will evaluate all == and IN constraints for an
   113459 ** index scan.
   113460 **
   113461 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
   113462 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
   113463 ** The index has as many as three equality constraints, but in this
   113464 ** example, the third "c" value is an inequality.  So only two
   113465 ** constraints are coded.  This routine will generate code to evaluate
   113466 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
   113467 ** in consecutive registers and the index of the first register is returned.
   113468 **
   113469 ** In the example above nEq==2.  But this subroutine works for any value
   113470 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
   113471 ** The only thing it does is allocate the pLevel->iMem memory cell and
   113472 ** compute the affinity string.
   113473 **
   113474 ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
   113475 ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
   113476 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
   113477 ** occurs after the nEq quality constraints.
   113478 **
   113479 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
   113480 ** the index of the first memory cell in that range. The code that
   113481 ** calls this routine will use that memory range to store keys for
   113482 ** start and termination conditions of the loop.
   113483 ** key value of the loop.  If one or more IN operators appear, then
   113484 ** this routine allocates an additional nEq memory cells for internal
   113485 ** use.
   113486 **
   113487 ** Before returning, *pzAff is set to point to a buffer containing a
   113488 ** copy of the column affinity string of the index allocated using
   113489 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
   113490 ** with equality constraints that use NONE affinity are set to
   113491 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
   113492 **
   113493 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
   113494 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
   113495 **
   113496 ** In the example above, the index on t1(a) has TEXT affinity. But since
   113497 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
   113498 ** no conversion should be attempted before using a t2.b value as part of
   113499 ** a key to search the index. Hence the first byte in the returned affinity
   113500 ** string in this example would be set to SQLITE_AFF_NONE.
   113501 */
   113502 static int codeAllEqualityTerms(
   113503   Parse *pParse,        /* Parsing context */
   113504   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
   113505   int bRev,             /* Reverse the order of IN operators */
   113506   int nExtraReg,        /* Number of extra registers to allocate */
   113507   char **pzAff          /* OUT: Set to point to affinity string */
   113508 ){
   113509   u16 nEq;                      /* The number of == or IN constraints to code */
   113510   u16 nSkip;                    /* Number of left-most columns to skip */
   113511   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
   113512   Index *pIdx;                  /* The index being used for this loop */
   113513   WhereTerm *pTerm;             /* A single constraint term */
   113514   WhereLoop *pLoop;             /* The WhereLoop object */
   113515   int j;                        /* Loop counter */
   113516   int regBase;                  /* Base register */
   113517   int nReg;                     /* Number of registers to allocate */
   113518   char *zAff;                   /* Affinity string to return */
   113519 
   113520   /* This module is only called on query plans that use an index. */
   113521   pLoop = pLevel->pWLoop;
   113522   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
   113523   nEq = pLoop->u.btree.nEq;
   113524   nSkip = pLoop->u.btree.nSkip;
   113525   pIdx = pLoop->u.btree.pIndex;
   113526   assert( pIdx!=0 );
   113527 
   113528   /* Figure out how many memory cells we will need then allocate them.
   113529   */
   113530   regBase = pParse->nMem + 1;
   113531   nReg = pLoop->u.btree.nEq + nExtraReg;
   113532   pParse->nMem += nReg;
   113533 
   113534   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
   113535   if( !zAff ){
   113536     pParse->db->mallocFailed = 1;
   113537   }
   113538 
   113539   if( nSkip ){
   113540     int iIdxCur = pLevel->iIdxCur;
   113541     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
   113542     VdbeCoverageIf(v, bRev==0);
   113543     VdbeCoverageIf(v, bRev!=0);
   113544     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
   113545     j = sqlite3VdbeAddOp0(v, OP_Goto);
   113546     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
   113547                             iIdxCur, 0, regBase, nSkip);
   113548     VdbeCoverageIf(v, bRev==0);
   113549     VdbeCoverageIf(v, bRev!=0);
   113550     sqlite3VdbeJumpHere(v, j);
   113551     for(j=0; j<nSkip; j++){
   113552       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
   113553       assert( pIdx->aiColumn[j]>=0 );
   113554       VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
   113555     }
   113556   }
   113557 
   113558   /* Evaluate the equality constraints
   113559   */
   113560   assert( zAff==0 || (int)strlen(zAff)>=nEq );
   113561   for(j=nSkip; j<nEq; j++){
   113562     int r1;
   113563     pTerm = pLoop->aLTerm[j];
   113564     assert( pTerm!=0 );
   113565     /* The following testcase is true for indices with redundant columns.
   113566     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
   113567     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
   113568     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   113569     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
   113570     if( r1!=regBase+j ){
   113571       if( nReg==1 ){
   113572         sqlite3ReleaseTempReg(pParse, regBase);
   113573         regBase = r1;
   113574       }else{
   113575         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
   113576       }
   113577     }
   113578     testcase( pTerm->eOperator & WO_ISNULL );
   113579     testcase( pTerm->eOperator & WO_IN );
   113580     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
   113581       Expr *pRight = pTerm->pExpr->pRight;
   113582       if( sqlite3ExprCanBeNull(pRight) ){
   113583         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
   113584         VdbeCoverage(v);
   113585       }
   113586       if( zAff ){
   113587         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
   113588           zAff[j] = SQLITE_AFF_NONE;
   113589         }
   113590         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
   113591           zAff[j] = SQLITE_AFF_NONE;
   113592         }
   113593       }
   113594     }
   113595   }
   113596   *pzAff = zAff;
   113597   return regBase;
   113598 }
   113599 
   113600 #ifndef SQLITE_OMIT_EXPLAIN
   113601 /*
   113602 ** This routine is a helper for explainIndexRange() below
   113603 **
   113604 ** pStr holds the text of an expression that we are building up one term
   113605 ** at a time.  This routine adds a new term to the end of the expression.
   113606 ** Terms are separated by AND so add the "AND" text for second and subsequent
   113607 ** terms only.
   113608 */
   113609 static void explainAppendTerm(
   113610   StrAccum *pStr,             /* The text expression being built */
   113611   int iTerm,                  /* Index of this term.  First is zero */
   113612   const char *zColumn,        /* Name of the column */
   113613   const char *zOp             /* Name of the operator */
   113614 ){
   113615   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
   113616   sqlite3StrAccumAppendAll(pStr, zColumn);
   113617   sqlite3StrAccumAppend(pStr, zOp, 1);
   113618   sqlite3StrAccumAppend(pStr, "?", 1);
   113619 }
   113620 
   113621 /*
   113622 ** Argument pLevel describes a strategy for scanning table pTab. This
   113623 ** function returns a pointer to a string buffer containing a description
   113624 ** of the subset of table rows scanned by the strategy in the form of an
   113625 ** SQL expression. Or, if all rows are scanned, NULL is returned.
   113626 **
   113627 ** For example, if the query:
   113628 **
   113629 **   SELECT * FROM t1 WHERE a=1 AND b>2;
   113630 **
   113631 ** is run and there is an index on (a, b), then this function returns a
   113632 ** string similar to:
   113633 **
   113634 **   "a=? AND b>?"
   113635 **
   113636 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
   113637 ** It is the responsibility of the caller to free the buffer when it is
   113638 ** no longer required.
   113639 */
   113640 static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
   113641   Index *pIndex = pLoop->u.btree.pIndex;
   113642   u16 nEq = pLoop->u.btree.nEq;
   113643   u16 nSkip = pLoop->u.btree.nSkip;
   113644   int i, j;
   113645   Column *aCol = pTab->aCol;
   113646   i16 *aiColumn = pIndex->aiColumn;
   113647   StrAccum txt;
   113648 
   113649   if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
   113650     return 0;
   113651   }
   113652   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
   113653   txt.db = db;
   113654   sqlite3StrAccumAppend(&txt, " (", 2);
   113655   for(i=0; i<nEq; i++){
   113656     char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
   113657     if( i>=nSkip ){
   113658       explainAppendTerm(&txt, i, z, "=");
   113659     }else{
   113660       if( i ) sqlite3StrAccumAppend(&txt, " AND ", 5);
   113661       sqlite3StrAccumAppend(&txt, "ANY(", 4);
   113662       sqlite3StrAccumAppendAll(&txt, z);
   113663       sqlite3StrAccumAppend(&txt, ")", 1);
   113664     }
   113665   }
   113666 
   113667   j = i;
   113668   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
   113669     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
   113670     explainAppendTerm(&txt, i++, z, ">");
   113671   }
   113672   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
   113673     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
   113674     explainAppendTerm(&txt, i, z, "<");
   113675   }
   113676   sqlite3StrAccumAppend(&txt, ")", 1);
   113677   return sqlite3StrAccumFinish(&txt);
   113678 }
   113679 
   113680 /*
   113681 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
   113682 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
   113683 ** record is added to the output to describe the table scan strategy in
   113684 ** pLevel.
   113685 */
   113686 static void explainOneScan(
   113687   Parse *pParse,                  /* Parse context */
   113688   SrcList *pTabList,              /* Table list this loop refers to */
   113689   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
   113690   int iLevel,                     /* Value for "level" column of output */
   113691   int iFrom,                      /* Value for "from" column of output */
   113692   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
   113693 ){
   113694 #ifndef SQLITE_DEBUG
   113695   if( pParse->explain==2 )
   113696 #endif
   113697   {
   113698     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
   113699     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
   113700     sqlite3 *db = pParse->db;     /* Database handle */
   113701     char *zMsg;                   /* Text to add to EQP output */
   113702     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
   113703     int isSearch;                 /* True for a SEARCH. False for SCAN. */
   113704     WhereLoop *pLoop;             /* The controlling WhereLoop object */
   113705     u32 flags;                    /* Flags that describe this loop */
   113706 
   113707     pLoop = pLevel->pWLoop;
   113708     flags = pLoop->wsFlags;
   113709     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
   113710 
   113711     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
   113712             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
   113713             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
   113714 
   113715     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
   113716     if( pItem->pSelect ){
   113717       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
   113718     }else{
   113719       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
   113720     }
   113721 
   113722     if( pItem->zAlias ){
   113723       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
   113724     }
   113725     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
   113726      && ALWAYS(pLoop->u.btree.pIndex!=0)
   113727     ){
   113728       const char *zFmt;
   113729       Index *pIdx = pLoop->u.btree.pIndex;
   113730       char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
   113731       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
   113732       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
   113733         zFmt = zWhere ? "%s USING PRIMARY KEY%.0s%s" : "%s%.0s%s";
   113734       }else if( flags & WHERE_AUTO_INDEX ){
   113735         zFmt = "%s USING AUTOMATIC COVERING INDEX%.0s%s";
   113736       }else if( flags & WHERE_IDX_ONLY ){
   113737         zFmt = "%s USING COVERING INDEX %s%s";
   113738       }else{
   113739         zFmt = "%s USING INDEX %s%s";
   113740       }
   113741       zMsg = sqlite3MAppendf(db, zMsg, zFmt, zMsg, pIdx->zName, zWhere);
   113742       sqlite3DbFree(db, zWhere);
   113743     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
   113744       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
   113745 
   113746       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
   113747         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
   113748       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
   113749         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
   113750       }else if( flags&WHERE_BTM_LIMIT ){
   113751         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
   113752       }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
   113753         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
   113754       }
   113755     }
   113756 #ifndef SQLITE_OMIT_VIRTUALTABLE
   113757     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
   113758       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
   113759                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
   113760     }
   113761 #endif
   113762     zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
   113763     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
   113764   }
   113765 }
   113766 #else
   113767 # define explainOneScan(u,v,w,x,y,z)
   113768 #endif /* SQLITE_OMIT_EXPLAIN */
   113769 
   113770 
   113771 /*
   113772 ** Generate code for the start of the iLevel-th loop in the WHERE clause
   113773 ** implementation described by pWInfo.
   113774 */
   113775 static Bitmask codeOneLoopStart(
   113776   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
   113777   int iLevel,          /* Which level of pWInfo->a[] should be coded */
   113778   Bitmask notReady     /* Which tables are currently available */
   113779 ){
   113780   int j, k;            /* Loop counters */
   113781   int iCur;            /* The VDBE cursor for the table */
   113782   int addrNxt;         /* Where to jump to continue with the next IN case */
   113783   int omitTable;       /* True if we use the index only */
   113784   int bRev;            /* True if we need to scan in reverse order */
   113785   WhereLevel *pLevel;  /* The where level to be coded */
   113786   WhereLoop *pLoop;    /* The WhereLoop object being coded */
   113787   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
   113788   WhereTerm *pTerm;               /* A WHERE clause term */
   113789   Parse *pParse;                  /* Parsing context */
   113790   sqlite3 *db;                    /* Database connection */
   113791   Vdbe *v;                        /* The prepared stmt under constructions */
   113792   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
   113793   int addrBrk;                    /* Jump here to break out of the loop */
   113794   int addrCont;                   /* Jump here to continue with next cycle */
   113795   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
   113796   int iReleaseReg = 0;      /* Temp register to free before returning */
   113797 
   113798   pParse = pWInfo->pParse;
   113799   v = pParse->pVdbe;
   113800   pWC = &pWInfo->sWC;
   113801   db = pParse->db;
   113802   pLevel = &pWInfo->a[iLevel];
   113803   pLoop = pLevel->pWLoop;
   113804   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
   113805   iCur = pTabItem->iCursor;
   113806   pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
   113807   bRev = (pWInfo->revMask>>iLevel)&1;
   113808   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
   113809            && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
   113810   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
   113811 
   113812   /* Create labels for the "break" and "continue" instructions
   113813   ** for the current loop.  Jump to addrBrk to break out of a loop.
   113814   ** Jump to cont to go immediately to the next iteration of the
   113815   ** loop.
   113816   **
   113817   ** When there is an IN operator, we also have a "addrNxt" label that
   113818   ** means to continue with the next IN value combination.  When
   113819   ** there are no IN operators in the constraints, the "addrNxt" label
   113820   ** is the same as "addrBrk".
   113821   */
   113822   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   113823   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
   113824 
   113825   /* If this is the right table of a LEFT OUTER JOIN, allocate and
   113826   ** initialize a memory cell that records if this table matches any
   113827   ** row of the left table of the join.
   113828   */
   113829   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
   113830     pLevel->iLeftJoin = ++pParse->nMem;
   113831     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
   113832     VdbeComment((v, "init LEFT JOIN no-match flag"));
   113833   }
   113834 
   113835   /* Special case of a FROM clause subquery implemented as a co-routine */
   113836   if( pTabItem->viaCoroutine ){
   113837     int regYield = pTabItem->regReturn;
   113838     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
   113839     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
   113840     VdbeCoverage(v);
   113841     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
   113842     pLevel->op = OP_Goto;
   113843   }else
   113844 
   113845 #ifndef SQLITE_OMIT_VIRTUALTABLE
   113846   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   113847     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
   113848     **          to access the data.
   113849     */
   113850     int iReg;   /* P3 Value for OP_VFilter */
   113851     int addrNotFound;
   113852     int nConstraint = pLoop->nLTerm;
   113853 
   113854     sqlite3ExprCachePush(pParse);
   113855     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
   113856     addrNotFound = pLevel->addrBrk;
   113857     for(j=0; j<nConstraint; j++){
   113858       int iTarget = iReg+j+2;
   113859       pTerm = pLoop->aLTerm[j];
   113860       if( pTerm==0 ) continue;
   113861       if( pTerm->eOperator & WO_IN ){
   113862         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
   113863         addrNotFound = pLevel->addrNxt;
   113864       }else{
   113865         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
   113866       }
   113867     }
   113868     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
   113869     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
   113870     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
   113871                       pLoop->u.vtab.idxStr,
   113872                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
   113873     VdbeCoverage(v);
   113874     pLoop->u.vtab.needFree = 0;
   113875     for(j=0; j<nConstraint && j<16; j++){
   113876       if( (pLoop->u.vtab.omitMask>>j)&1 ){
   113877         disableTerm(pLevel, pLoop->aLTerm[j]);
   113878       }
   113879     }
   113880     pLevel->op = OP_VNext;
   113881     pLevel->p1 = iCur;
   113882     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   113883     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
   113884     sqlite3ExprCachePop(pParse);
   113885   }else
   113886 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   113887 
   113888   if( (pLoop->wsFlags & WHERE_IPK)!=0
   113889    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
   113890   ){
   113891     /* Case 2:  We can directly reference a single row using an
   113892     **          equality comparison against the ROWID field.  Or
   113893     **          we reference multiple rows using a "rowid IN (...)"
   113894     **          construct.
   113895     */
   113896     assert( pLoop->u.btree.nEq==1 );
   113897     pTerm = pLoop->aLTerm[0];
   113898     assert( pTerm!=0 );
   113899     assert( pTerm->pExpr!=0 );
   113900     assert( omitTable==0 );
   113901     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   113902     iReleaseReg = ++pParse->nMem;
   113903     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
   113904     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
   113905     addrNxt = pLevel->addrNxt;
   113906     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
   113907     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
   113908     VdbeCoverage(v);
   113909     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
   113910     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   113911     VdbeComment((v, "pk"));
   113912     pLevel->op = OP_Noop;
   113913   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
   113914          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
   113915   ){
   113916     /* Case 3:  We have an inequality comparison against the ROWID field.
   113917     */
   113918     int testOp = OP_Noop;
   113919     int start;
   113920     int memEndValue = 0;
   113921     WhereTerm *pStart, *pEnd;
   113922 
   113923     assert( omitTable==0 );
   113924     j = 0;
   113925     pStart = pEnd = 0;
   113926     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
   113927     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
   113928     assert( pStart!=0 || pEnd!=0 );
   113929     if( bRev ){
   113930       pTerm = pStart;
   113931       pStart = pEnd;
   113932       pEnd = pTerm;
   113933     }
   113934     if( pStart ){
   113935       Expr *pX;             /* The expression that defines the start bound */
   113936       int r1, rTemp;        /* Registers for holding the start boundary */
   113937 
   113938       /* The following constant maps TK_xx codes into corresponding
   113939       ** seek opcodes.  It depends on a particular ordering of TK_xx
   113940       */
   113941       const u8 aMoveOp[] = {
   113942            /* TK_GT */  OP_SeekGT,
   113943            /* TK_LE */  OP_SeekLE,
   113944            /* TK_LT */  OP_SeekLT,
   113945            /* TK_GE */  OP_SeekGE
   113946       };
   113947       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
   113948       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
   113949       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
   113950 
   113951       assert( (pStart->wtFlags & TERM_VNULL)==0 );
   113952       testcase( pStart->wtFlags & TERM_VIRTUAL );
   113953       pX = pStart->pExpr;
   113954       assert( pX!=0 );
   113955       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
   113956       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
   113957       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
   113958       VdbeComment((v, "pk"));
   113959       VdbeCoverageIf(v, pX->op==TK_GT);
   113960       VdbeCoverageIf(v, pX->op==TK_LE);
   113961       VdbeCoverageIf(v, pX->op==TK_LT);
   113962       VdbeCoverageIf(v, pX->op==TK_GE);
   113963       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
   113964       sqlite3ReleaseTempReg(pParse, rTemp);
   113965       disableTerm(pLevel, pStart);
   113966     }else{
   113967       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
   113968       VdbeCoverageIf(v, bRev==0);
   113969       VdbeCoverageIf(v, bRev!=0);
   113970     }
   113971     if( pEnd ){
   113972       Expr *pX;
   113973       pX = pEnd->pExpr;
   113974       assert( pX!=0 );
   113975       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
   113976       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
   113977       testcase( pEnd->wtFlags & TERM_VIRTUAL );
   113978       memEndValue = ++pParse->nMem;
   113979       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
   113980       if( pX->op==TK_LT || pX->op==TK_GT ){
   113981         testOp = bRev ? OP_Le : OP_Ge;
   113982       }else{
   113983         testOp = bRev ? OP_Lt : OP_Gt;
   113984       }
   113985       disableTerm(pLevel, pEnd);
   113986     }
   113987     start = sqlite3VdbeCurrentAddr(v);
   113988     pLevel->op = bRev ? OP_Prev : OP_Next;
   113989     pLevel->p1 = iCur;
   113990     pLevel->p2 = start;
   113991     assert( pLevel->p5==0 );
   113992     if( testOp!=OP_Noop ){
   113993       iRowidReg = ++pParse->nMem;
   113994       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
   113995       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   113996       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
   113997       VdbeCoverageIf(v, testOp==OP_Le);
   113998       VdbeCoverageIf(v, testOp==OP_Lt);
   113999       VdbeCoverageIf(v, testOp==OP_Ge);
   114000       VdbeCoverageIf(v, testOp==OP_Gt);
   114001       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
   114002     }
   114003   }else if( pLoop->wsFlags & WHERE_INDEXED ){
   114004     /* Case 4: A scan using an index.
   114005     **
   114006     **         The WHERE clause may contain zero or more equality
   114007     **         terms ("==" or "IN" operators) that refer to the N
   114008     **         left-most columns of the index. It may also contain
   114009     **         inequality constraints (>, <, >= or <=) on the indexed
   114010     **         column that immediately follows the N equalities. Only
   114011     **         the right-most column can be an inequality - the rest must
   114012     **         use the "==" and "IN" operators. For example, if the
   114013     **         index is on (x,y,z), then the following clauses are all
   114014     **         optimized:
   114015     **
   114016     **            x=5
   114017     **            x=5 AND y=10
   114018     **            x=5 AND y<10
   114019     **            x=5 AND y>5 AND y<10
   114020     **            x=5 AND y=5 AND z<=10
   114021     **
   114022     **         The z<10 term of the following cannot be used, only
   114023     **         the x=5 term:
   114024     **
   114025     **            x=5 AND z<10
   114026     **
   114027     **         N may be zero if there are inequality constraints.
   114028     **         If there are no inequality constraints, then N is at
   114029     **         least one.
   114030     **
   114031     **         This case is also used when there are no WHERE clause
   114032     **         constraints but an index is selected anyway, in order
   114033     **         to force the output order to conform to an ORDER BY.
   114034     */
   114035     static const u8 aStartOp[] = {
   114036       0,
   114037       0,
   114038       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
   114039       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
   114040       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
   114041       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
   114042       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
   114043       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
   114044     };
   114045     static const u8 aEndOp[] = {
   114046       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
   114047       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
   114048       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
   114049       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
   114050     };
   114051     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
   114052     int regBase;                 /* Base register holding constraint values */
   114053     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
   114054     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
   114055     int startEq;                 /* True if range start uses ==, >= or <= */
   114056     int endEq;                   /* True if range end uses ==, >= or <= */
   114057     int start_constraints;       /* Start of range is constrained */
   114058     int nConstraint;             /* Number of constraint terms */
   114059     Index *pIdx;                 /* The index we will be using */
   114060     int iIdxCur;                 /* The VDBE cursor for the index */
   114061     int nExtraReg = 0;           /* Number of extra registers needed */
   114062     int op;                      /* Instruction opcode */
   114063     char *zStartAff;             /* Affinity for start of range constraint */
   114064     char cEndAff = 0;            /* Affinity for end of range constraint */
   114065     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
   114066     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
   114067 
   114068     pIdx = pLoop->u.btree.pIndex;
   114069     iIdxCur = pLevel->iIdxCur;
   114070     assert( nEq>=pLoop->u.btree.nSkip );
   114071 
   114072     /* If this loop satisfies a sort order (pOrderBy) request that
   114073     ** was passed to this function to implement a "SELECT min(x) ..."
   114074     ** query, then the caller will only allow the loop to run for
   114075     ** a single iteration. This means that the first row returned
   114076     ** should not have a NULL value stored in 'x'. If column 'x' is
   114077     ** the first one after the nEq equality constraints in the index,
   114078     ** this requires some special handling.
   114079     */
   114080     assert( pWInfo->pOrderBy==0
   114081          || pWInfo->pOrderBy->nExpr==1
   114082          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
   114083     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
   114084      && pWInfo->nOBSat>0
   114085      && (pIdx->nKeyCol>nEq)
   114086     ){
   114087       assert( pLoop->u.btree.nSkip==0 );
   114088       bSeekPastNull = 1;
   114089       nExtraReg = 1;
   114090     }
   114091 
   114092     /* Find any inequality constraint terms for the start and end
   114093     ** of the range.
   114094     */
   114095     j = nEq;
   114096     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
   114097       pRangeStart = pLoop->aLTerm[j++];
   114098       nExtraReg = 1;
   114099     }
   114100     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
   114101       pRangeEnd = pLoop->aLTerm[j++];
   114102       nExtraReg = 1;
   114103       if( pRangeStart==0
   114104        && (j = pIdx->aiColumn[nEq])>=0
   114105        && pIdx->pTable->aCol[j].notNull==0
   114106       ){
   114107         bSeekPastNull = 1;
   114108       }
   114109     }
   114110     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
   114111 
   114112     /* Generate code to evaluate all constraint terms using == or IN
   114113     ** and store the values of those terms in an array of registers
   114114     ** starting at regBase.
   114115     */
   114116     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
   114117     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
   114118     if( zStartAff ) cEndAff = zStartAff[nEq];
   114119     addrNxt = pLevel->addrNxt;
   114120 
   114121     /* If we are doing a reverse order scan on an ascending index, or
   114122     ** a forward order scan on a descending index, interchange the
   114123     ** start and end terms (pRangeStart and pRangeEnd).
   114124     */
   114125     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
   114126      || (bRev && pIdx->nKeyCol==nEq)
   114127     ){
   114128       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
   114129       SWAP(u8, bSeekPastNull, bStopAtNull);
   114130     }
   114131 
   114132     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
   114133     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
   114134     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
   114135     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
   114136     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
   114137     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
   114138     start_constraints = pRangeStart || nEq>0;
   114139 
   114140     /* Seek the index cursor to the start of the range. */
   114141     nConstraint = nEq;
   114142     if( pRangeStart ){
   114143       Expr *pRight = pRangeStart->pExpr->pRight;
   114144       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   114145       if( (pRangeStart->wtFlags & TERM_VNULL)==0
   114146        && sqlite3ExprCanBeNull(pRight)
   114147       ){
   114148         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
   114149         VdbeCoverage(v);
   114150       }
   114151       if( zStartAff ){
   114152         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
   114153           /* Since the comparison is to be performed with no conversions
   114154           ** applied to the operands, set the affinity to apply to pRight to
   114155           ** SQLITE_AFF_NONE.  */
   114156           zStartAff[nEq] = SQLITE_AFF_NONE;
   114157         }
   114158         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
   114159           zStartAff[nEq] = SQLITE_AFF_NONE;
   114160         }
   114161       }
   114162       nConstraint++;
   114163       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
   114164     }else if( bSeekPastNull ){
   114165       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   114166       nConstraint++;
   114167       startEq = 0;
   114168       start_constraints = 1;
   114169     }
   114170     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
   114171     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
   114172     assert( op!=0 );
   114173     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   114174     VdbeCoverage(v);
   114175     VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
   114176     VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
   114177     VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
   114178     VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
   114179     VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
   114180     VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
   114181 
   114182     /* Load the value for the inequality constraint at the end of the
   114183     ** range (if any).
   114184     */
   114185     nConstraint = nEq;
   114186     if( pRangeEnd ){
   114187       Expr *pRight = pRangeEnd->pExpr->pRight;
   114188       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
   114189       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   114190       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
   114191        && sqlite3ExprCanBeNull(pRight)
   114192       ){
   114193         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
   114194         VdbeCoverage(v);
   114195       }
   114196       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
   114197        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
   114198       ){
   114199         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
   114200       }
   114201       nConstraint++;
   114202       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
   114203     }else if( bStopAtNull ){
   114204       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   114205       endEq = 0;
   114206       nConstraint++;
   114207     }
   114208     sqlite3DbFree(db, zStartAff);
   114209 
   114210     /* Top of the loop body */
   114211     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   114212 
   114213     /* Check if the index cursor is past the end of the range. */
   114214     if( nConstraint ){
   114215       op = aEndOp[bRev*2 + endEq];
   114216       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   114217       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
   114218       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
   114219       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
   114220       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
   114221     }
   114222 
   114223     /* Seek the table cursor, if required */
   114224     disableTerm(pLevel, pRangeStart);
   114225     disableTerm(pLevel, pRangeEnd);
   114226     if( omitTable ){
   114227       /* pIdx is a covering index.  No need to access the main table. */
   114228     }else if( HasRowid(pIdx->pTable) ){
   114229       iRowidReg = ++pParse->nMem;
   114230       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
   114231       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   114232       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
   114233     }else if( iCur!=iIdxCur ){
   114234       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
   114235       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
   114236       for(j=0; j<pPk->nKeyCol; j++){
   114237         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
   114238         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
   114239       }
   114240       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
   114241                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
   114242     }
   114243 
   114244     /* Record the instruction used to terminate the loop. Disable
   114245     ** WHERE clause terms made redundant by the index range scan.
   114246     */
   114247     if( pLoop->wsFlags & WHERE_ONEROW ){
   114248       pLevel->op = OP_Noop;
   114249     }else if( bRev ){
   114250       pLevel->op = OP_Prev;
   114251     }else{
   114252       pLevel->op = OP_Next;
   114253     }
   114254     pLevel->p1 = iIdxCur;
   114255     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
   114256     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
   114257       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   114258     }else{
   114259       assert( pLevel->p5==0 );
   114260     }
   114261   }else
   114262 
   114263 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   114264   if( pLoop->wsFlags & WHERE_MULTI_OR ){
   114265     /* Case 5:  Two or more separately indexed terms connected by OR
   114266     **
   114267     ** Example:
   114268     **
   114269     **   CREATE TABLE t1(a,b,c,d);
   114270     **   CREATE INDEX i1 ON t1(a);
   114271     **   CREATE INDEX i2 ON t1(b);
   114272     **   CREATE INDEX i3 ON t1(c);
   114273     **
   114274     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
   114275     **
   114276     ** In the example, there are three indexed terms connected by OR.
   114277     ** The top of the loop looks like this:
   114278     **
   114279     **          Null       1                # Zero the rowset in reg 1
   114280     **
   114281     ** Then, for each indexed term, the following. The arguments to
   114282     ** RowSetTest are such that the rowid of the current row is inserted
   114283     ** into the RowSet. If it is already present, control skips the
   114284     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
   114285     **
   114286     **        sqlite3WhereBegin(<term>)
   114287     **          RowSetTest                  # Insert rowid into rowset
   114288     **          Gosub      2 A
   114289     **        sqlite3WhereEnd()
   114290     **
   114291     ** Following the above, code to terminate the loop. Label A, the target
   114292     ** of the Gosub above, jumps to the instruction right after the Goto.
   114293     **
   114294     **          Null       1                # Zero the rowset in reg 1
   114295     **          Goto       B                # The loop is finished.
   114296     **
   114297     **       A: <loop body>                 # Return data, whatever.
   114298     **
   114299     **          Return     2                # Jump back to the Gosub
   114300     **
   114301     **       B: <after the loop>
   114302     **
   114303     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
   114304     ** use an ephermeral index instead of a RowSet to record the primary
   114305     ** keys of the rows we have already seen.
   114306     **
   114307     */
   114308     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
   114309     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
   114310     Index *pCov = 0;             /* Potential covering index (or NULL) */
   114311     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
   114312 
   114313     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
   114314     int regRowset = 0;                        /* Register for RowSet object */
   114315     int regRowid = 0;                         /* Register holding rowid */
   114316     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
   114317     int iRetInit;                             /* Address of regReturn init */
   114318     int untestedTerms = 0;             /* Some terms not completely tested */
   114319     int ii;                            /* Loop counter */
   114320     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
   114321     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
   114322     Table *pTab = pTabItem->pTab;
   114323 
   114324     pTerm = pLoop->aLTerm[0];
   114325     assert( pTerm!=0 );
   114326     assert( pTerm->eOperator & WO_OR );
   114327     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
   114328     pOrWc = &pTerm->u.pOrInfo->wc;
   114329     pLevel->op = OP_Return;
   114330     pLevel->p1 = regReturn;
   114331 
   114332     /* Set up a new SrcList in pOrTab containing the table being scanned
   114333     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
   114334     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
   114335     */
   114336     if( pWInfo->nLevel>1 ){
   114337       int nNotReady;                 /* The number of notReady tables */
   114338       struct SrcList_item *origSrc;     /* Original list of tables */
   114339       nNotReady = pWInfo->nLevel - iLevel - 1;
   114340       pOrTab = sqlite3StackAllocRaw(db,
   114341                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
   114342       if( pOrTab==0 ) return notReady;
   114343       pOrTab->nAlloc = (u8)(nNotReady + 1);
   114344       pOrTab->nSrc = pOrTab->nAlloc;
   114345       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
   114346       origSrc = pWInfo->pTabList->a;
   114347       for(k=1; k<=nNotReady; k++){
   114348         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
   114349       }
   114350     }else{
   114351       pOrTab = pWInfo->pTabList;
   114352     }
   114353 
   114354     /* Initialize the rowset register to contain NULL. An SQL NULL is
   114355     ** equivalent to an empty rowset.  Or, create an ephermeral index
   114356     ** capable of holding primary keys in the case of a WITHOUT ROWID.
   114357     **
   114358     ** Also initialize regReturn to contain the address of the instruction
   114359     ** immediately following the OP_Return at the bottom of the loop. This
   114360     ** is required in a few obscure LEFT JOIN cases where control jumps
   114361     ** over the top of the loop into the body of it. In this case the
   114362     ** correct response for the end-of-loop code (the OP_Return) is to
   114363     ** fall through to the next instruction, just as an OP_Next does if
   114364     ** called on an uninitialized cursor.
   114365     */
   114366     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   114367       if( HasRowid(pTab) ){
   114368         regRowset = ++pParse->nMem;
   114369         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
   114370       }else{
   114371         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   114372         regRowset = pParse->nTab++;
   114373         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
   114374         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   114375       }
   114376       regRowid = ++pParse->nMem;
   114377     }
   114378     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
   114379 
   114380     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
   114381     ** Then for every term xN, evaluate as the subexpression: xN AND z
   114382     ** That way, terms in y that are factored into the disjunction will
   114383     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
   114384     **
   114385     ** Actually, each subexpression is converted to "xN AND w" where w is
   114386     ** the "interesting" terms of z - terms that did not originate in the
   114387     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
   114388     ** indices.
   114389     **
   114390     ** This optimization also only applies if the (x1 OR x2 OR ...) term
   114391     ** is not contained in the ON clause of a LEFT JOIN.
   114392     ** See ticket http://www.sqlite.org/src/info/f2369304e4
   114393     */
   114394     if( pWC->nTerm>1 ){
   114395       int iTerm;
   114396       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
   114397         Expr *pExpr = pWC->a[iTerm].pExpr;
   114398         if( &pWC->a[iTerm] == pTerm ) continue;
   114399         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
   114400         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
   114401         testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
   114402         if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
   114403         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
   114404         pExpr = sqlite3ExprDup(db, pExpr, 0);
   114405         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
   114406       }
   114407       if( pAndExpr ){
   114408         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
   114409       }
   114410     }
   114411 
   114412     /* Run a separate WHERE clause for each term of the OR clause.  After
   114413     ** eliminating duplicates from other WHERE clauses, the action for each
   114414     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
   114415     */
   114416     wctrlFlags =  WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
   114417                   WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY;
   114418     for(ii=0; ii<pOrWc->nTerm; ii++){
   114419       WhereTerm *pOrTerm = &pOrWc->a[ii];
   114420       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
   114421         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
   114422         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
   114423         int j1 = 0;                     /* Address of jump operation */
   114424         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
   114425           pAndExpr->pLeft = pOrExpr;
   114426           pOrExpr = pAndExpr;
   114427         }
   114428         /* Loop through table entries that match term pOrTerm. */
   114429         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
   114430                                       wctrlFlags, iCovCur);
   114431         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
   114432         if( pSubWInfo ){
   114433           WhereLoop *pSubLoop;
   114434           explainOneScan(
   114435               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
   114436           );
   114437           /* This is the sub-WHERE clause body.  First skip over
   114438           ** duplicate rows from prior sub-WHERE clauses, and record the
   114439           ** rowid (or PRIMARY KEY) for the current row so that the same
   114440           ** row will be skipped in subsequent sub-WHERE clauses.
   114441           */
   114442           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   114443             int r;
   114444             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
   114445             if( HasRowid(pTab) ){
   114446               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
   114447               j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
   114448               VdbeCoverage(v);
   114449             }else{
   114450               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   114451               int nPk = pPk->nKeyCol;
   114452               int iPk;
   114453 
   114454               /* Read the PK into an array of temp registers. */
   114455               r = sqlite3GetTempRange(pParse, nPk);
   114456               for(iPk=0; iPk<nPk; iPk++){
   114457                 int iCol = pPk->aiColumn[iPk];
   114458                 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
   114459               }
   114460 
   114461               /* Check if the temp table already contains this key. If so,
   114462               ** the row has already been included in the result set and
   114463               ** can be ignored (by jumping past the Gosub below). Otherwise,
   114464               ** insert the key into the temp table and proceed with processing
   114465               ** the row.
   114466               **
   114467               ** Use some of the same optimizations as OP_RowSetTest: If iSet
   114468               ** is zero, assume that the key cannot already be present in
   114469               ** the temp table. And if iSet is -1, assume that there is no
   114470               ** need to insert the key into the temp table, as it will never
   114471               ** be tested for.  */
   114472               if( iSet ){
   114473                 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
   114474                 VdbeCoverage(v);
   114475               }
   114476               if( iSet>=0 ){
   114477                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
   114478                 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
   114479                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   114480               }
   114481 
   114482               /* Release the array of temp registers */
   114483               sqlite3ReleaseTempRange(pParse, r, nPk);
   114484             }
   114485           }
   114486 
   114487           /* Invoke the main loop body as a subroutine */
   114488           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
   114489 
   114490           /* Jump here (skipping the main loop body subroutine) if the
   114491           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
   114492           if( j1 ) sqlite3VdbeJumpHere(v, j1);
   114493 
   114494           /* The pSubWInfo->untestedTerms flag means that this OR term
   114495           ** contained one or more AND term from a notReady table.  The
   114496           ** terms from the notReady table could not be tested and will
   114497           ** need to be tested later.
   114498           */
   114499           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
   114500 
   114501           /* If all of the OR-connected terms are optimized using the same
   114502           ** index, and the index is opened using the same cursor number
   114503           ** by each call to sqlite3WhereBegin() made by this loop, it may
   114504           ** be possible to use that index as a covering index.
   114505           **
   114506           ** If the call to sqlite3WhereBegin() above resulted in a scan that
   114507           ** uses an index, and this is either the first OR-connected term
   114508           ** processed or the index is the same as that used by all previous
   114509           ** terms, set pCov to the candidate covering index. Otherwise, set
   114510           ** pCov to NULL to indicate that no candidate covering index will
   114511           ** be available.
   114512           */
   114513           pSubLoop = pSubWInfo->a[0].pWLoop;
   114514           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
   114515           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
   114516            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
   114517            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
   114518           ){
   114519             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
   114520             pCov = pSubLoop->u.btree.pIndex;
   114521             wctrlFlags |= WHERE_REOPEN_IDX;
   114522           }else{
   114523             pCov = 0;
   114524           }
   114525 
   114526           /* Finish the loop through table entries that match term pOrTerm. */
   114527           sqlite3WhereEnd(pSubWInfo);
   114528         }
   114529       }
   114530     }
   114531     pLevel->u.pCovidx = pCov;
   114532     if( pCov ) pLevel->iIdxCur = iCovCur;
   114533     if( pAndExpr ){
   114534       pAndExpr->pLeft = 0;
   114535       sqlite3ExprDelete(db, pAndExpr);
   114536     }
   114537     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
   114538     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
   114539     sqlite3VdbeResolveLabel(v, iLoopBody);
   114540 
   114541     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
   114542     if( !untestedTerms ) disableTerm(pLevel, pTerm);
   114543   }else
   114544 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   114545 
   114546   {
   114547     /* Case 6:  There is no usable index.  We must do a complete
   114548     **          scan of the entire table.
   114549     */
   114550     static const u8 aStep[] = { OP_Next, OP_Prev };
   114551     static const u8 aStart[] = { OP_Rewind, OP_Last };
   114552     assert( bRev==0 || bRev==1 );
   114553     if( pTabItem->isRecursive ){
   114554       /* Tables marked isRecursive have only a single row that is stored in
   114555       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
   114556       pLevel->op = OP_Noop;
   114557     }else{
   114558       pLevel->op = aStep[bRev];
   114559       pLevel->p1 = iCur;
   114560       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
   114561       VdbeCoverageIf(v, bRev==0);
   114562       VdbeCoverageIf(v, bRev!=0);
   114563       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   114564     }
   114565   }
   114566 
   114567   /* Insert code to test every subexpression that can be completely
   114568   ** computed using the current set of tables.
   114569   */
   114570   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   114571     Expr *pE;
   114572     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   114573     testcase( pTerm->wtFlags & TERM_CODED );
   114574     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   114575     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
   114576       testcase( pWInfo->untestedTerms==0
   114577                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
   114578       pWInfo->untestedTerms = 1;
   114579       continue;
   114580     }
   114581     pE = pTerm->pExpr;
   114582     assert( pE!=0 );
   114583     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
   114584       continue;
   114585     }
   114586     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
   114587     pTerm->wtFlags |= TERM_CODED;
   114588   }
   114589 
   114590   /* Insert code to test for implied constraints based on transitivity
   114591   ** of the "==" operator.
   114592   **
   114593   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
   114594   ** and we are coding the t1 loop and the t2 loop has not yet coded,
   114595   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
   114596   ** the implied "t1.a=123" constraint.
   114597   */
   114598   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   114599     Expr *pE, *pEAlt;
   114600     WhereTerm *pAlt;
   114601     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   114602     if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
   114603     if( pTerm->leftCursor!=iCur ) continue;
   114604     if( pLevel->iLeftJoin ) continue;
   114605     pE = pTerm->pExpr;
   114606     assert( !ExprHasProperty(pE, EP_FromJoin) );
   114607     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
   114608     pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
   114609     if( pAlt==0 ) continue;
   114610     if( pAlt->wtFlags & (TERM_CODED) ) continue;
   114611     testcase( pAlt->eOperator & WO_EQ );
   114612     testcase( pAlt->eOperator & WO_IN );
   114613     VdbeModuleComment((v, "begin transitive constraint"));
   114614     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
   114615     if( pEAlt ){
   114616       *pEAlt = *pAlt->pExpr;
   114617       pEAlt->pLeft = pE->pLeft;
   114618       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
   114619       sqlite3StackFree(db, pEAlt);
   114620     }
   114621   }
   114622 
   114623   /* For a LEFT OUTER JOIN, generate code that will record the fact that
   114624   ** at least one row of the right table has matched the left table.
   114625   */
   114626   if( pLevel->iLeftJoin ){
   114627     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
   114628     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
   114629     VdbeComment((v, "record LEFT JOIN hit"));
   114630     sqlite3ExprCacheClear(pParse);
   114631     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
   114632       testcase( pTerm->wtFlags & TERM_VIRTUAL );
   114633       testcase( pTerm->wtFlags & TERM_CODED );
   114634       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   114635       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
   114636         assert( pWInfo->untestedTerms );
   114637         continue;
   114638       }
   114639       assert( pTerm->pExpr );
   114640       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
   114641       pTerm->wtFlags |= TERM_CODED;
   114642     }
   114643   }
   114644 
   114645   return pLevel->notReady;
   114646 }
   114647 
   114648 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
   114649 /*
   114650 ** Generate "Explanation" text for a WhereTerm.
   114651 */
   114652 static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
   114653   char zType[4];
   114654   memcpy(zType, "...", 4);
   114655   if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
   114656   if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
   114657   if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
   114658   sqlite3ExplainPrintf(v, "%s ", zType);
   114659   sqlite3ExplainExpr(v, pTerm->pExpr);
   114660 }
   114661 #endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
   114662 
   114663 
   114664 #ifdef WHERETRACE_ENABLED
   114665 /*
   114666 ** Print a WhereLoop object for debugging purposes
   114667 */
   114668 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
   114669   WhereInfo *pWInfo = pWC->pWInfo;
   114670   int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
   114671   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
   114672   Table *pTab = pItem->pTab;
   114673   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
   114674                      p->iTab, nb, p->maskSelf, nb, p->prereq);
   114675   sqlite3DebugPrintf(" %12s",
   114676                      pItem->zAlias ? pItem->zAlias : pTab->zName);
   114677   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
   114678      const char *zName;
   114679      if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
   114680       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
   114681         int i = sqlite3Strlen30(zName) - 1;
   114682         while( zName[i]!='_' ) i--;
   114683         zName += i;
   114684       }
   114685       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
   114686     }else{
   114687       sqlite3DebugPrintf("%20s","");
   114688     }
   114689   }else{
   114690     char *z;
   114691     if( p->u.vtab.idxStr ){
   114692       z = sqlite3_mprintf("(%d,\"%s\",%x)",
   114693                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
   114694     }else{
   114695       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
   114696     }
   114697     sqlite3DebugPrintf(" %-19s", z);
   114698     sqlite3_free(z);
   114699   }
   114700   sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
   114701   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
   114702 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
   114703   /* If the 0x100 bit of wheretracing is set, then show all of the constraint
   114704   ** expressions in the WhereLoop.aLTerm[] array.
   114705   */
   114706   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){  /* WHERETRACE 0x100 */
   114707     int i;
   114708     Vdbe *v = pWInfo->pParse->pVdbe;
   114709     sqlite3ExplainBegin(v);
   114710     for(i=0; i<p->nLTerm; i++){
   114711       WhereTerm *pTerm = p->aLTerm[i];
   114712       if( pTerm==0 ) continue;
   114713       sqlite3ExplainPrintf(v, "  (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
   114714       sqlite3ExplainPush(v);
   114715       whereExplainTerm(v, pTerm);
   114716       sqlite3ExplainPop(v);
   114717       sqlite3ExplainNL(v);
   114718     }
   114719     sqlite3ExplainFinish(v);
   114720     sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
   114721   }
   114722 #endif
   114723 }
   114724 #endif
   114725 
   114726 /*
   114727 ** Convert bulk memory into a valid WhereLoop that can be passed
   114728 ** to whereLoopClear harmlessly.
   114729 */
   114730 static void whereLoopInit(WhereLoop *p){
   114731   p->aLTerm = p->aLTermSpace;
   114732   p->nLTerm = 0;
   114733   p->nLSlot = ArraySize(p->aLTermSpace);
   114734   p->wsFlags = 0;
   114735 }
   114736 
   114737 /*
   114738 ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
   114739 */
   114740 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
   114741   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
   114742     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
   114743       sqlite3_free(p->u.vtab.idxStr);
   114744       p->u.vtab.needFree = 0;
   114745       p->u.vtab.idxStr = 0;
   114746     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
   114747       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
   114748       sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
   114749       sqlite3DbFree(db, p->u.btree.pIndex);
   114750       p->u.btree.pIndex = 0;
   114751     }
   114752   }
   114753 }
   114754 
   114755 /*
   114756 ** Deallocate internal memory used by a WhereLoop object
   114757 */
   114758 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
   114759   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
   114760   whereLoopClearUnion(db, p);
   114761   whereLoopInit(p);
   114762 }
   114763 
   114764 /*
   114765 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
   114766 */
   114767 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
   114768   WhereTerm **paNew;
   114769   if( p->nLSlot>=n ) return SQLITE_OK;
   114770   n = (n+7)&~7;
   114771   paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
   114772   if( paNew==0 ) return SQLITE_NOMEM;
   114773   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
   114774   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
   114775   p->aLTerm = paNew;
   114776   p->nLSlot = n;
   114777   return SQLITE_OK;
   114778 }
   114779 
   114780 /*
   114781 ** Transfer content from the second pLoop into the first.
   114782 */
   114783 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
   114784   whereLoopClearUnion(db, pTo);
   114785   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
   114786     memset(&pTo->u, 0, sizeof(pTo->u));
   114787     return SQLITE_NOMEM;
   114788   }
   114789   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
   114790   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
   114791   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
   114792     pFrom->u.vtab.needFree = 0;
   114793   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
   114794     pFrom->u.btree.pIndex = 0;
   114795   }
   114796   return SQLITE_OK;
   114797 }
   114798 
   114799 /*
   114800 ** Delete a WhereLoop object
   114801 */
   114802 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
   114803   whereLoopClear(db, p);
   114804   sqlite3DbFree(db, p);
   114805 }
   114806 
   114807 /*
   114808 ** Free a WhereInfo structure
   114809 */
   114810 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   114811   if( ALWAYS(pWInfo) ){
   114812     whereClauseClear(&pWInfo->sWC);
   114813     while( pWInfo->pLoops ){
   114814       WhereLoop *p = pWInfo->pLoops;
   114815       pWInfo->pLoops = p->pNextLoop;
   114816       whereLoopDelete(db, p);
   114817     }
   114818     sqlite3DbFree(db, pWInfo);
   114819   }
   114820 }
   114821 
   114822 /*
   114823 ** Return TRUE if both of the following are true:
   114824 **
   114825 **   (1)  X has the same or lower cost that Y
   114826 **   (2)  X is a proper subset of Y
   114827 **
   114828 ** By "proper subset" we mean that X uses fewer WHERE clause terms
   114829 ** than Y and that every WHERE clause term used by X is also used
   114830 ** by Y.
   114831 **
   114832 ** If X is a proper subset of Y then Y is a better choice and ought
   114833 ** to have a lower cost.  This routine returns TRUE when that cost
   114834 ** relationship is inverted and needs to be adjusted.
   114835 */
   114836 static int whereLoopCheaperProperSubset(
   114837   const WhereLoop *pX,       /* First WhereLoop to compare */
   114838   const WhereLoop *pY        /* Compare against this WhereLoop */
   114839 ){
   114840   int i, j;
   114841   if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
   114842   if( pX->rRun >= pY->rRun ){
   114843     if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
   114844     if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
   114845   }
   114846   for(i=pX->nLTerm-1; i>=0; i--){
   114847     for(j=pY->nLTerm-1; j>=0; j--){
   114848       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
   114849     }
   114850     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
   114851   }
   114852   return 1;  /* All conditions meet */
   114853 }
   114854 
   114855 /*
   114856 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
   114857 ** that:
   114858 **
   114859 **   (1) pTemplate costs less than any other WhereLoops that are a proper
   114860 **       subset of pTemplate
   114861 **
   114862 **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
   114863 **       is a proper subset.
   114864 **
   114865 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
   114866 ** WHERE clause terms than Y and that every WHERE clause term used by X is
   114867 ** also used by Y.
   114868 **
   114869 ** This adjustment is omitted for SKIPSCAN loops.  In a SKIPSCAN loop, the
   114870 ** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE
   114871 ** clause terms covered, since some of the first nLTerm entries in aLTerm[]
   114872 ** will be NULL (because they are skipped).  That makes it more difficult
   114873 ** to compare the loops.  We could add extra code to do the comparison, and
   114874 ** perhaps we will someday.  But SKIPSCAN is sufficiently uncommon, and this
   114875 ** adjustment is sufficient minor, that it is very difficult to construct
   114876 ** a test case where the extra code would improve the query plan.  Better
   114877 ** to avoid the added complexity and just omit cost adjustments to SKIPSCAN
   114878 ** loops.
   114879 */
   114880 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
   114881   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
   114882   if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
   114883   for(; p; p=p->pNextLoop){
   114884     if( p->iTab!=pTemplate->iTab ) continue;
   114885     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
   114886     if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
   114887     if( whereLoopCheaperProperSubset(p, pTemplate) ){
   114888       /* Adjust pTemplate cost downward so that it is cheaper than its
   114889       ** subset p */
   114890       pTemplate->rRun = p->rRun;
   114891       pTemplate->nOut = p->nOut - 1;
   114892     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
   114893       /* Adjust pTemplate cost upward so that it is costlier than p since
   114894       ** pTemplate is a proper subset of p */
   114895       pTemplate->rRun = p->rRun;
   114896       pTemplate->nOut = p->nOut + 1;
   114897     }
   114898   }
   114899 }
   114900 
   114901 /*
   114902 ** Search the list of WhereLoops in *ppPrev looking for one that can be
   114903 ** supplanted by pTemplate.
   114904 **
   114905 ** Return NULL if the WhereLoop list contains an entry that can supplant
   114906 ** pTemplate, in other words if pTemplate does not belong on the list.
   114907 **
   114908 ** If pX is a WhereLoop that pTemplate can supplant, then return the
   114909 ** link that points to pX.
   114910 **
   114911 ** If pTemplate cannot supplant any existing element of the list but needs
   114912 ** to be added to the list, then return a pointer to the tail of the list.
   114913 */
   114914 static WhereLoop **whereLoopFindLesser(
   114915   WhereLoop **ppPrev,
   114916   const WhereLoop *pTemplate
   114917 ){
   114918   WhereLoop *p;
   114919   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
   114920     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
   114921       /* If either the iTab or iSortIdx values for two WhereLoop are different
   114922       ** then those WhereLoops need to be considered separately.  Neither is
   114923       ** a candidate to replace the other. */
   114924       continue;
   114925     }
   114926     /* In the current implementation, the rSetup value is either zero
   114927     ** or the cost of building an automatic index (NlogN) and the NlogN
   114928     ** is the same for compatible WhereLoops. */
   114929     assert( p->rSetup==0 || pTemplate->rSetup==0
   114930                  || p->rSetup==pTemplate->rSetup );
   114931 
   114932     /* whereLoopAddBtree() always generates and inserts the automatic index
   114933     ** case first.  Hence compatible candidate WhereLoops never have a larger
   114934     ** rSetup. Call this SETUP-INVARIANT */
   114935     assert( p->rSetup>=pTemplate->rSetup );
   114936 
   114937     /* Any loop using an appliation-defined index (or PRIMARY KEY or
   114938     ** UNIQUE constraint) with one or more == constraints is better
   114939     ** than an automatic index. */
   114940     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
   114941      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
   114942      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
   114943      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
   114944     ){
   114945       break;
   114946     }
   114947 
   114948     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
   114949     ** discarded.  WhereLoop p is better if:
   114950     **   (1)  p has no more dependencies than pTemplate, and
   114951     **   (2)  p has an equal or lower cost than pTemplate
   114952     */
   114953     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
   114954      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
   114955      && p->rRun<=pTemplate->rRun                      /* (2b) */
   114956      && p->nOut<=pTemplate->nOut                      /* (2c) */
   114957     ){
   114958       return 0;  /* Discard pTemplate */
   114959     }
   114960 
   114961     /* If pTemplate is always better than p, then cause p to be overwritten
   114962     ** with pTemplate.  pTemplate is better than p if:
   114963     **   (1)  pTemplate has no more dependences than p, and
   114964     **   (2)  pTemplate has an equal or lower cost than p.
   114965     */
   114966     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
   114967      && p->rRun>=pTemplate->rRun                             /* (2a) */
   114968      && p->nOut>=pTemplate->nOut                             /* (2b) */
   114969     ){
   114970       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
   114971       break;   /* Cause p to be overwritten by pTemplate */
   114972     }
   114973   }
   114974   return ppPrev;
   114975 }
   114976 
   114977 /*
   114978 ** Insert or replace a WhereLoop entry using the template supplied.
   114979 **
   114980 ** An existing WhereLoop entry might be overwritten if the new template
   114981 ** is better and has fewer dependencies.  Or the template will be ignored
   114982 ** and no insert will occur if an existing WhereLoop is faster and has
   114983 ** fewer dependencies than the template.  Otherwise a new WhereLoop is
   114984 ** added based on the template.
   114985 **
   114986 ** If pBuilder->pOrSet is not NULL then we care about only the
   114987 ** prerequisites and rRun and nOut costs of the N best loops.  That
   114988 ** information is gathered in the pBuilder->pOrSet object.  This special
   114989 ** processing mode is used only for OR clause processing.
   114990 **
   114991 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
   114992 ** still might overwrite similar loops with the new template if the
   114993 ** new template is better.  Loops may be overwritten if the following
   114994 ** conditions are met:
   114995 **
   114996 **    (1)  They have the same iTab.
   114997 **    (2)  They have the same iSortIdx.
   114998 **    (3)  The template has same or fewer dependencies than the current loop
   114999 **    (4)  The template has the same or lower cost than the current loop
   115000 */
   115001 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
   115002   WhereLoop **ppPrev, *p;
   115003   WhereInfo *pWInfo = pBuilder->pWInfo;
   115004   sqlite3 *db = pWInfo->pParse->db;
   115005 
   115006   /* If pBuilder->pOrSet is defined, then only keep track of the costs
   115007   ** and prereqs.
   115008   */
   115009   if( pBuilder->pOrSet!=0 ){
   115010 #if WHERETRACE_ENABLED
   115011     u16 n = pBuilder->pOrSet->n;
   115012     int x =
   115013 #endif
   115014     whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
   115015                                     pTemplate->nOut);
   115016 #if WHERETRACE_ENABLED /* 0x8 */
   115017     if( sqlite3WhereTrace & 0x8 ){
   115018       sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
   115019       whereLoopPrint(pTemplate, pBuilder->pWC);
   115020     }
   115021 #endif
   115022     return SQLITE_OK;
   115023   }
   115024 
   115025   /* Look for an existing WhereLoop to replace with pTemplate
   115026   */
   115027   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
   115028   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
   115029 
   115030   if( ppPrev==0 ){
   115031     /* There already exists a WhereLoop on the list that is better
   115032     ** than pTemplate, so just ignore pTemplate */
   115033 #if WHERETRACE_ENABLED /* 0x8 */
   115034     if( sqlite3WhereTrace & 0x8 ){
   115035       sqlite3DebugPrintf("ins-noop: ");
   115036       whereLoopPrint(pTemplate, pBuilder->pWC);
   115037     }
   115038 #endif
   115039     return SQLITE_OK;
   115040   }else{
   115041     p = *ppPrev;
   115042   }
   115043 
   115044   /* If we reach this point it means that either p[] should be overwritten
   115045   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
   115046   ** WhereLoop and insert it.
   115047   */
   115048 #if WHERETRACE_ENABLED /* 0x8 */
   115049   if( sqlite3WhereTrace & 0x8 ){
   115050     if( p!=0 ){
   115051       sqlite3DebugPrintf("ins-del:  ");
   115052       whereLoopPrint(p, pBuilder->pWC);
   115053     }
   115054     sqlite3DebugPrintf("ins-new:  ");
   115055     whereLoopPrint(pTemplate, pBuilder->pWC);
   115056   }
   115057 #endif
   115058   if( p==0 ){
   115059     /* Allocate a new WhereLoop to add to the end of the list */
   115060     *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
   115061     if( p==0 ) return SQLITE_NOMEM;
   115062     whereLoopInit(p);
   115063     p->pNextLoop = 0;
   115064   }else{
   115065     /* We will be overwriting WhereLoop p[].  But before we do, first
   115066     ** go through the rest of the list and delete any other entries besides
   115067     ** p[] that are also supplated by pTemplate */
   115068     WhereLoop **ppTail = &p->pNextLoop;
   115069     WhereLoop *pToDel;
   115070     while( *ppTail ){
   115071       ppTail = whereLoopFindLesser(ppTail, pTemplate);
   115072       if( ppTail==0 ) break;
   115073       pToDel = *ppTail;
   115074       if( pToDel==0 ) break;
   115075       *ppTail = pToDel->pNextLoop;
   115076 #if WHERETRACE_ENABLED /* 0x8 */
   115077       if( sqlite3WhereTrace & 0x8 ){
   115078         sqlite3DebugPrintf("ins-del:  ");
   115079         whereLoopPrint(pToDel, pBuilder->pWC);
   115080       }
   115081 #endif
   115082       whereLoopDelete(db, pToDel);
   115083     }
   115084   }
   115085   whereLoopXfer(db, p, pTemplate);
   115086   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
   115087     Index *pIndex = p->u.btree.pIndex;
   115088     if( pIndex && pIndex->tnum==0 ){
   115089       p->u.btree.pIndex = 0;
   115090     }
   115091   }
   115092   return SQLITE_OK;
   115093 }
   115094 
   115095 /*
   115096 ** Adjust the WhereLoop.nOut value downward to account for terms of the
   115097 ** WHERE clause that reference the loop but which are not used by an
   115098 ** index.
   115099 **
   115100 ** In the current implementation, the first extra WHERE clause term reduces
   115101 ** the number of output rows by a factor of 10 and each additional term
   115102 ** reduces the number of output rows by sqrt(2).
   115103 */
   115104 static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
   115105   WhereTerm *pTerm, *pX;
   115106   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
   115107   int i, j;
   115108 
   115109   if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
   115110     return;
   115111   }
   115112   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
   115113     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
   115114     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
   115115     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
   115116     for(j=pLoop->nLTerm-1; j>=0; j--){
   115117       pX = pLoop->aLTerm[j];
   115118       if( pX==0 ) continue;
   115119       if( pX==pTerm ) break;
   115120       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
   115121     }
   115122     if( j<0 ){
   115123       pLoop->nOut += (pTerm->truthProb<=0 ? pTerm->truthProb : -1);
   115124     }
   115125   }
   115126 }
   115127 
   115128 /*
   115129 ** Adjust the cost C by the costMult facter T.  This only occurs if
   115130 ** compiled with -DSQLITE_ENABLE_COSTMULT
   115131 */
   115132 #ifdef SQLITE_ENABLE_COSTMULT
   115133 # define ApplyCostMultiplier(C,T)  C += T
   115134 #else
   115135 # define ApplyCostMultiplier(C,T)
   115136 #endif
   115137 
   115138 /*
   115139 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
   115140 ** index pIndex. Try to match one more.
   115141 **
   115142 ** When this function is called, pBuilder->pNew->nOut contains the
   115143 ** number of rows expected to be visited by filtering using the nEq
   115144 ** terms only. If it is modified, this value is restored before this
   115145 ** function returns.
   115146 **
   115147 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
   115148 ** INTEGER PRIMARY KEY.
   115149 */
   115150 static int whereLoopAddBtreeIndex(
   115151   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
   115152   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
   115153   Index *pProbe,                  /* An index on pSrc */
   115154   LogEst nInMul                   /* log(Number of iterations due to IN) */
   115155 ){
   115156   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
   115157   Parse *pParse = pWInfo->pParse;        /* Parsing context */
   115158   sqlite3 *db = pParse->db;       /* Database connection malloc context */
   115159   WhereLoop *pNew;                /* Template WhereLoop under construction */
   115160   WhereTerm *pTerm;               /* A WhereTerm under consideration */
   115161   int opMask;                     /* Valid operators for constraints */
   115162   WhereScan scan;                 /* Iterator for WHERE terms */
   115163   Bitmask saved_prereq;           /* Original value of pNew->prereq */
   115164   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
   115165   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
   115166   u16 saved_nSkip;                /* Original value of pNew->u.btree.nSkip */
   115167   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
   115168   LogEst saved_nOut;              /* Original value of pNew->nOut */
   115169   int iCol;                       /* Index of the column in the table */
   115170   int rc = SQLITE_OK;             /* Return code */
   115171   LogEst rLogSize;                /* Logarithm of table size */
   115172   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
   115173 
   115174   pNew = pBuilder->pNew;
   115175   if( db->mallocFailed ) return SQLITE_NOMEM;
   115176 
   115177   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
   115178   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
   115179   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
   115180     opMask = WO_LT|WO_LE;
   115181   }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
   115182     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
   115183   }else{
   115184     opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
   115185   }
   115186   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
   115187 
   115188   assert( pNew->u.btree.nEq<pProbe->nColumn );
   115189   iCol = pProbe->aiColumn[pNew->u.btree.nEq];
   115190 
   115191   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
   115192                         opMask, pProbe);
   115193   saved_nEq = pNew->u.btree.nEq;
   115194   saved_nSkip = pNew->u.btree.nSkip;
   115195   saved_nLTerm = pNew->nLTerm;
   115196   saved_wsFlags = pNew->wsFlags;
   115197   saved_prereq = pNew->prereq;
   115198   saved_nOut = pNew->nOut;
   115199   pNew->rSetup = 0;
   115200   rLogSize = estLog(pProbe->aiRowLogEst[0]);
   115201 
   115202   /* Consider using a skip-scan if there are no WHERE clause constraints
   115203   ** available for the left-most terms of the index, and if the average
   115204   ** number of repeats in the left-most terms is at least 18.
   115205   **
   115206   ** The magic number 18 is selected on the basis that scanning 17 rows
   115207   ** is almost always quicker than an index seek (even though if the index
   115208   ** contains fewer than 2^17 rows we assume otherwise in other parts of
   115209   ** the code). And, even if it is not, it should not be too much slower.
   115210   ** On the other hand, the extra seeks could end up being significantly
   115211   ** more expensive.  */
   115212   assert( 42==sqlite3LogEst(18) );
   115213   if( pTerm==0
   115214    && saved_nEq==saved_nSkip
   115215    && saved_nEq+1<pProbe->nKeyCol
   115216    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
   115217    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
   115218   ){
   115219     LogEst nIter;
   115220     pNew->u.btree.nEq++;
   115221     pNew->u.btree.nSkip++;
   115222     pNew->aLTerm[pNew->nLTerm++] = 0;
   115223     pNew->wsFlags |= WHERE_SKIPSCAN;
   115224     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
   115225     pNew->nOut -= nIter;
   115226     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
   115227     pNew->nOut = saved_nOut;
   115228   }
   115229   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
   115230     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
   115231     LogEst rCostIdx;
   115232     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
   115233     int nIn = 0;
   115234 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   115235     int nRecValid = pBuilder->nRecValid;
   115236 #endif
   115237     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
   115238      && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
   115239     ){
   115240       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
   115241     }
   115242     if( pTerm->prereqRight & pNew->maskSelf ) continue;
   115243 
   115244     pNew->wsFlags = saved_wsFlags;
   115245     pNew->u.btree.nEq = saved_nEq;
   115246     pNew->nLTerm = saved_nLTerm;
   115247     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
   115248     pNew->aLTerm[pNew->nLTerm++] = pTerm;
   115249     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
   115250 
   115251     assert( nInMul==0
   115252         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
   115253         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
   115254         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
   115255     );
   115256 
   115257     if( eOp & WO_IN ){
   115258       Expr *pExpr = pTerm->pExpr;
   115259       pNew->wsFlags |= WHERE_COLUMN_IN;
   115260       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   115261         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
   115262         nIn = 46;  assert( 46==sqlite3LogEst(25) );
   115263       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
   115264         /* "x IN (value, value, ...)" */
   115265         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
   115266       }
   115267       assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
   115268                         ** changes "x IN (?)" into "x=?". */
   115269 
   115270     }else if( eOp & (WO_EQ) ){
   115271       pNew->wsFlags |= WHERE_COLUMN_EQ;
   115272       if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
   115273         if( iCol>=0 && !IsUniqueIndex(pProbe) ){
   115274           pNew->wsFlags |= WHERE_UNQ_WANTED;
   115275         }else{
   115276           pNew->wsFlags |= WHERE_ONEROW;
   115277         }
   115278       }
   115279     }else if( eOp & WO_ISNULL ){
   115280       pNew->wsFlags |= WHERE_COLUMN_NULL;
   115281     }else if( eOp & (WO_GT|WO_GE) ){
   115282       testcase( eOp & WO_GT );
   115283       testcase( eOp & WO_GE );
   115284       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
   115285       pBtm = pTerm;
   115286       pTop = 0;
   115287     }else{
   115288       assert( eOp & (WO_LT|WO_LE) );
   115289       testcase( eOp & WO_LT );
   115290       testcase( eOp & WO_LE );
   115291       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
   115292       pTop = pTerm;
   115293       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
   115294                      pNew->aLTerm[pNew->nLTerm-2] : 0;
   115295     }
   115296 
   115297     /* At this point pNew->nOut is set to the number of rows expected to
   115298     ** be visited by the index scan before considering term pTerm, or the
   115299     ** values of nIn and nInMul. In other words, assuming that all
   115300     ** "x IN(...)" terms are replaced with "x = ?". This block updates
   115301     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
   115302     assert( pNew->nOut==saved_nOut );
   115303     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
   115304       /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
   115305       ** data, using some other estimate.  */
   115306       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
   115307     }else{
   115308       int nEq = ++pNew->u.btree.nEq;
   115309       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
   115310 
   115311       assert( pNew->nOut==saved_nOut );
   115312       if( pTerm->truthProb<=0 && iCol>=0 ){
   115313         assert( (eOp & WO_IN) || nIn==0 );
   115314         testcase( eOp & WO_IN );
   115315         pNew->nOut += pTerm->truthProb;
   115316         pNew->nOut -= nIn;
   115317       }else{
   115318 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   115319         tRowcnt nOut = 0;
   115320         if( nInMul==0
   115321          && pProbe->nSample
   115322          && pNew->u.btree.nEq<=pProbe->nSampleCol
   115323          && OptimizationEnabled(db, SQLITE_Stat3)
   115324          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
   115325         ){
   115326           Expr *pExpr = pTerm->pExpr;
   115327           if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
   115328             testcase( eOp & WO_EQ );
   115329             testcase( eOp & WO_ISNULL );
   115330             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
   115331           }else{
   115332             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
   115333           }
   115334           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   115335           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
   115336           if( nOut ){
   115337             pNew->nOut = sqlite3LogEst(nOut);
   115338             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
   115339             pNew->nOut -= nIn;
   115340           }
   115341         }
   115342         if( nOut==0 )
   115343 #endif
   115344         {
   115345           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
   115346           if( eOp & WO_ISNULL ){
   115347             /* TUNING: If there is no likelihood() value, assume that a
   115348             ** "col IS NULL" expression matches twice as many rows
   115349             ** as (col=?). */
   115350             pNew->nOut += 10;
   115351           }
   115352         }
   115353       }
   115354     }
   115355 
   115356     /* Set rCostIdx to the cost of visiting selected rows in index. Add
   115357     ** it to pNew->rRun, which is currently set to the cost of the index
   115358     ** seek only. Then, if this is a non-covering index, add the cost of
   115359     ** visiting the rows in the main table.  */
   115360     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
   115361     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
   115362     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
   115363       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
   115364     }
   115365     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
   115366 
   115367     nOutUnadjusted = pNew->nOut;
   115368     pNew->rRun += nInMul + nIn;
   115369     pNew->nOut += nInMul + nIn;
   115370     whereLoopOutputAdjust(pBuilder->pWC, pNew);
   115371     rc = whereLoopInsert(pBuilder, pNew);
   115372 
   115373     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
   115374       pNew->nOut = saved_nOut;
   115375     }else{
   115376       pNew->nOut = nOutUnadjusted;
   115377     }
   115378 
   115379     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
   115380      && pNew->u.btree.nEq<pProbe->nColumn
   115381     ){
   115382       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
   115383     }
   115384     pNew->nOut = saved_nOut;
   115385 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   115386     pBuilder->nRecValid = nRecValid;
   115387 #endif
   115388   }
   115389   pNew->prereq = saved_prereq;
   115390   pNew->u.btree.nEq = saved_nEq;
   115391   pNew->u.btree.nSkip = saved_nSkip;
   115392   pNew->wsFlags = saved_wsFlags;
   115393   pNew->nOut = saved_nOut;
   115394   pNew->nLTerm = saved_nLTerm;
   115395   return rc;
   115396 }
   115397 
   115398 /*
   115399 ** Return True if it is possible that pIndex might be useful in
   115400 ** implementing the ORDER BY clause in pBuilder.
   115401 **
   115402 ** Return False if pBuilder does not contain an ORDER BY clause or
   115403 ** if there is no way for pIndex to be useful in implementing that
   115404 ** ORDER BY clause.
   115405 */
   115406 static int indexMightHelpWithOrderBy(
   115407   WhereLoopBuilder *pBuilder,
   115408   Index *pIndex,
   115409   int iCursor
   115410 ){
   115411   ExprList *pOB;
   115412   int ii, jj;
   115413 
   115414   if( pIndex->bUnordered ) return 0;
   115415   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
   115416   for(ii=0; ii<pOB->nExpr; ii++){
   115417     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
   115418     if( pExpr->op!=TK_COLUMN ) return 0;
   115419     if( pExpr->iTable==iCursor ){
   115420       for(jj=0; jj<pIndex->nKeyCol; jj++){
   115421         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
   115422       }
   115423     }
   115424   }
   115425   return 0;
   115426 }
   115427 
   115428 /*
   115429 ** Return a bitmask where 1s indicate that the corresponding column of
   115430 ** the table is used by an index.  Only the first 63 columns are considered.
   115431 */
   115432 static Bitmask columnsInIndex(Index *pIdx){
   115433   Bitmask m = 0;
   115434   int j;
   115435   for(j=pIdx->nColumn-1; j>=0; j--){
   115436     int x = pIdx->aiColumn[j];
   115437     if( x>=0 ){
   115438       testcase( x==BMS-1 );
   115439       testcase( x==BMS-2 );
   115440       if( x<BMS-1 ) m |= MASKBIT(x);
   115441     }
   115442   }
   115443   return m;
   115444 }
   115445 
   115446 /* Check to see if a partial index with pPartIndexWhere can be used
   115447 ** in the current query.  Return true if it can be and false if not.
   115448 */
   115449 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
   115450   int i;
   115451   WhereTerm *pTerm;
   115452   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   115453     if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
   115454   }
   115455   return 0;
   115456 }
   115457 
   115458 /*
   115459 ** Add all WhereLoop objects for a single table of the join where the table
   115460 ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
   115461 ** a b-tree table, not a virtual table.
   115462 **
   115463 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
   115464 ** are calculated as follows:
   115465 **
   115466 ** For a full scan, assuming the table (or index) contains nRow rows:
   115467 **
   115468 **     cost = nRow * 3.0                    // full-table scan
   115469 **     cost = nRow * K                      // scan of covering index
   115470 **     cost = nRow * (K+3.0)                // scan of non-covering index
   115471 **
   115472 ** where K is a value between 1.1 and 3.0 set based on the relative
   115473 ** estimated average size of the index and table records.
   115474 **
   115475 ** For an index scan, where nVisit is the number of index rows visited
   115476 ** by the scan, and nSeek is the number of seek operations required on
   115477 ** the index b-tree:
   115478 **
   115479 **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
   115480 **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
   115481 **
   115482 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
   115483 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
   115484 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
   115485 **
   115486 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
   115487 ** of uncertainty.  For this reason, scoring is designed to pick plans that
   115488 ** "do the least harm" if the estimates are inaccurate.  For example, a
   115489 ** log(nRow) factor is omitted from a non-covering index scan in order to
   115490 ** bias the scoring in favor of using an index, since the worst-case
   115491 ** performance of using an index is far better than the worst-case performance
   115492 ** of a full table scan.
   115493 */
   115494 static int whereLoopAddBtree(
   115495   WhereLoopBuilder *pBuilder, /* WHERE clause information */
   115496   Bitmask mExtra              /* Extra prerequesites for using this table */
   115497 ){
   115498   WhereInfo *pWInfo;          /* WHERE analysis context */
   115499   Index *pProbe;              /* An index we are evaluating */
   115500   Index sPk;                  /* A fake index object for the primary key */
   115501   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
   115502   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
   115503   SrcList *pTabList;          /* The FROM clause */
   115504   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
   115505   WhereLoop *pNew;            /* Template WhereLoop object */
   115506   int rc = SQLITE_OK;         /* Return code */
   115507   int iSortIdx = 1;           /* Index number */
   115508   int b;                      /* A boolean value */
   115509   LogEst rSize;               /* number of rows in the table */
   115510   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
   115511   WhereClause *pWC;           /* The parsed WHERE clause */
   115512   Table *pTab;                /* Table being queried */
   115513 
   115514   pNew = pBuilder->pNew;
   115515   pWInfo = pBuilder->pWInfo;
   115516   pTabList = pWInfo->pTabList;
   115517   pSrc = pTabList->a + pNew->iTab;
   115518   pTab = pSrc->pTab;
   115519   pWC = pBuilder->pWC;
   115520   assert( !IsVirtual(pSrc->pTab) );
   115521 
   115522   if( pSrc->pIndex ){
   115523     /* An INDEXED BY clause specifies a particular index to use */
   115524     pProbe = pSrc->pIndex;
   115525   }else if( !HasRowid(pTab) ){
   115526     pProbe = pTab->pIndex;
   115527   }else{
   115528     /* There is no INDEXED BY clause.  Create a fake Index object in local
   115529     ** variable sPk to represent the rowid primary key index.  Make this
   115530     ** fake index the first in a chain of Index objects with all of the real
   115531     ** indices to follow */
   115532     Index *pFirst;                  /* First of real indices on the table */
   115533     memset(&sPk, 0, sizeof(Index));
   115534     sPk.nKeyCol = 1;
   115535     sPk.nColumn = 1;
   115536     sPk.aiColumn = &aiColumnPk;
   115537     sPk.aiRowLogEst = aiRowEstPk;
   115538     sPk.onError = OE_Replace;
   115539     sPk.pTable = pTab;
   115540     sPk.szIdxRow = pTab->szTabRow;
   115541     aiRowEstPk[0] = pTab->nRowLogEst;
   115542     aiRowEstPk[1] = 0;
   115543     pFirst = pSrc->pTab->pIndex;
   115544     if( pSrc->notIndexed==0 ){
   115545       /* The real indices of the table are only considered if the
   115546       ** NOT INDEXED qualifier is omitted from the FROM clause */
   115547       sPk.pNext = pFirst;
   115548     }
   115549     pProbe = &sPk;
   115550   }
   115551   rSize = pTab->nRowLogEst;
   115552   rLogSize = estLog(rSize);
   115553 
   115554 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   115555   /* Automatic indexes */
   115556   if( !pBuilder->pOrSet
   115557    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
   115558    && pSrc->pIndex==0
   115559    && !pSrc->viaCoroutine
   115560    && !pSrc->notIndexed
   115561    && HasRowid(pTab)
   115562    && !pSrc->isCorrelated
   115563    && !pSrc->isRecursive
   115564   ){
   115565     /* Generate auto-index WhereLoops */
   115566     WhereTerm *pTerm;
   115567     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
   115568     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
   115569       if( pTerm->prereqRight & pNew->maskSelf ) continue;
   115570       if( termCanDriveIndex(pTerm, pSrc, 0) ){
   115571         pNew->u.btree.nEq = 1;
   115572         pNew->u.btree.nSkip = 0;
   115573         pNew->u.btree.pIndex = 0;
   115574         pNew->nLTerm = 1;
   115575         pNew->aLTerm[0] = pTerm;
   115576         /* TUNING: One-time cost for computing the automatic index is
   115577         ** approximately 7*N*log2(N) where N is the number of rows in
   115578         ** the table being indexed. */
   115579         pNew->rSetup = rLogSize + rSize + 28;  assert( 28==sqlite3LogEst(7) );
   115580         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
   115581         /* TUNING: Each index lookup yields 20 rows in the table.  This
   115582         ** is more than the usual guess of 10 rows, since we have no way
   115583         ** of knowning how selective the index will ultimately be.  It would
   115584         ** not be unreasonable to make this value much larger. */
   115585         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
   115586         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
   115587         pNew->wsFlags = WHERE_AUTO_INDEX;
   115588         pNew->prereq = mExtra | pTerm->prereqRight;
   115589         rc = whereLoopInsert(pBuilder, pNew);
   115590       }
   115591     }
   115592   }
   115593 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   115594 
   115595   /* Loop over all indices
   115596   */
   115597   for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
   115598     if( pProbe->pPartIdxWhere!=0
   115599      && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
   115600       continue;  /* Partial index inappropriate for this query */
   115601     }
   115602     rSize = pProbe->aiRowLogEst[0];
   115603     pNew->u.btree.nEq = 0;
   115604     pNew->u.btree.nSkip = 0;
   115605     pNew->nLTerm = 0;
   115606     pNew->iSortIdx = 0;
   115607     pNew->rSetup = 0;
   115608     pNew->prereq = mExtra;
   115609     pNew->nOut = rSize;
   115610     pNew->u.btree.pIndex = pProbe;
   115611     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
   115612     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
   115613     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
   115614     if( pProbe->tnum<=0 ){
   115615       /* Integer primary key index */
   115616       pNew->wsFlags = WHERE_IPK;
   115617 
   115618       /* Full table scan */
   115619       pNew->iSortIdx = b ? iSortIdx : 0;
   115620       /* TUNING: Cost of full table scan is (N*3.0). */
   115621       pNew->rRun = rSize + 16;
   115622       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
   115623       whereLoopOutputAdjust(pWC, pNew);
   115624       rc = whereLoopInsert(pBuilder, pNew);
   115625       pNew->nOut = rSize;
   115626       if( rc ) break;
   115627     }else{
   115628       Bitmask m;
   115629       if( pProbe->isCovering ){
   115630         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
   115631         m = 0;
   115632       }else{
   115633         m = pSrc->colUsed & ~columnsInIndex(pProbe);
   115634         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
   115635       }
   115636 
   115637       /* Full scan via index */
   115638       if( b
   115639        || !HasRowid(pTab)
   115640        || ( m==0
   115641          && pProbe->bUnordered==0
   115642          && (pProbe->szIdxRow<pTab->szTabRow)
   115643          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
   115644          && sqlite3GlobalConfig.bUseCis
   115645          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
   115646           )
   115647       ){
   115648         pNew->iSortIdx = b ? iSortIdx : 0;
   115649 
   115650         /* The cost of visiting the index rows is N*K, where K is
   115651         ** between 1.1 and 3.0, depending on the relative sizes of the
   115652         ** index and table rows. If this is a non-covering index scan,
   115653         ** also add the cost of visiting table rows (N*3.0).  */
   115654         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
   115655         if( m!=0 ){
   115656           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
   115657         }
   115658         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
   115659         whereLoopOutputAdjust(pWC, pNew);
   115660         rc = whereLoopInsert(pBuilder, pNew);
   115661         pNew->nOut = rSize;
   115662         if( rc ) break;
   115663       }
   115664     }
   115665 
   115666     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
   115667 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   115668     sqlite3Stat4ProbeFree(pBuilder->pRec);
   115669     pBuilder->nRecValid = 0;
   115670     pBuilder->pRec = 0;
   115671 #endif
   115672 
   115673     /* If there was an INDEXED BY clause, then only that one index is
   115674     ** considered. */
   115675     if( pSrc->pIndex ) break;
   115676   }
   115677   return rc;
   115678 }
   115679 
   115680 #ifndef SQLITE_OMIT_VIRTUALTABLE
   115681 /*
   115682 ** Add all WhereLoop objects for a table of the join identified by
   115683 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
   115684 */
   115685 static int whereLoopAddVirtual(
   115686   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
   115687   Bitmask mExtra
   115688 ){
   115689   WhereInfo *pWInfo;           /* WHERE analysis context */
   115690   Parse *pParse;               /* The parsing context */
   115691   WhereClause *pWC;            /* The WHERE clause */
   115692   struct SrcList_item *pSrc;   /* The FROM clause term to search */
   115693   Table *pTab;
   115694   sqlite3 *db;
   115695   sqlite3_index_info *pIdxInfo;
   115696   struct sqlite3_index_constraint *pIdxCons;
   115697   struct sqlite3_index_constraint_usage *pUsage;
   115698   WhereTerm *pTerm;
   115699   int i, j;
   115700   int iTerm, mxTerm;
   115701   int nConstraint;
   115702   int seenIn = 0;              /* True if an IN operator is seen */
   115703   int seenVar = 0;             /* True if a non-constant constraint is seen */
   115704   int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
   115705   WhereLoop *pNew;
   115706   int rc = SQLITE_OK;
   115707 
   115708   pWInfo = pBuilder->pWInfo;
   115709   pParse = pWInfo->pParse;
   115710   db = pParse->db;
   115711   pWC = pBuilder->pWC;
   115712   pNew = pBuilder->pNew;
   115713   pSrc = &pWInfo->pTabList->a[pNew->iTab];
   115714   pTab = pSrc->pTab;
   115715   assert( IsVirtual(pTab) );
   115716   pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
   115717   if( pIdxInfo==0 ) return SQLITE_NOMEM;
   115718   pNew->prereq = 0;
   115719   pNew->rSetup = 0;
   115720   pNew->wsFlags = WHERE_VIRTUALTABLE;
   115721   pNew->nLTerm = 0;
   115722   pNew->u.vtab.needFree = 0;
   115723   pUsage = pIdxInfo->aConstraintUsage;
   115724   nConstraint = pIdxInfo->nConstraint;
   115725   if( whereLoopResize(db, pNew, nConstraint) ){
   115726     sqlite3DbFree(db, pIdxInfo);
   115727     return SQLITE_NOMEM;
   115728   }
   115729 
   115730   for(iPhase=0; iPhase<=3; iPhase++){
   115731     if( !seenIn && (iPhase&1)!=0 ){
   115732       iPhase++;
   115733       if( iPhase>3 ) break;
   115734     }
   115735     if( !seenVar && iPhase>1 ) break;
   115736     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   115737     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
   115738       j = pIdxCons->iTermOffset;
   115739       pTerm = &pWC->a[j];
   115740       switch( iPhase ){
   115741         case 0:    /* Constants without IN operator */
   115742           pIdxCons->usable = 0;
   115743           if( (pTerm->eOperator & WO_IN)!=0 ){
   115744             seenIn = 1;
   115745           }
   115746           if( pTerm->prereqRight!=0 ){
   115747             seenVar = 1;
   115748           }else if( (pTerm->eOperator & WO_IN)==0 ){
   115749             pIdxCons->usable = 1;
   115750           }
   115751           break;
   115752         case 1:    /* Constants with IN operators */
   115753           assert( seenIn );
   115754           pIdxCons->usable = (pTerm->prereqRight==0);
   115755           break;
   115756         case 2:    /* Variables without IN */
   115757           assert( seenVar );
   115758           pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
   115759           break;
   115760         default:   /* Variables with IN */
   115761           assert( seenVar && seenIn );
   115762           pIdxCons->usable = 1;
   115763           break;
   115764       }
   115765     }
   115766     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
   115767     if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
   115768     pIdxInfo->idxStr = 0;
   115769     pIdxInfo->idxNum = 0;
   115770     pIdxInfo->needToFreeIdxStr = 0;
   115771     pIdxInfo->orderByConsumed = 0;
   115772     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
   115773     pIdxInfo->estimatedRows = 25;
   115774     rc = vtabBestIndex(pParse, pTab, pIdxInfo);
   115775     if( rc ) goto whereLoopAddVtab_exit;
   115776     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   115777     pNew->prereq = mExtra;
   115778     mxTerm = -1;
   115779     assert( pNew->nLSlot>=nConstraint );
   115780     for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
   115781     pNew->u.vtab.omitMask = 0;
   115782     for(i=0; i<nConstraint; i++, pIdxCons++){
   115783       if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
   115784         j = pIdxCons->iTermOffset;
   115785         if( iTerm>=nConstraint
   115786          || j<0
   115787          || j>=pWC->nTerm
   115788          || pNew->aLTerm[iTerm]!=0
   115789         ){
   115790           rc = SQLITE_ERROR;
   115791           sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
   115792           goto whereLoopAddVtab_exit;
   115793         }
   115794         testcase( iTerm==nConstraint-1 );
   115795         testcase( j==0 );
   115796         testcase( j==pWC->nTerm-1 );
   115797         pTerm = &pWC->a[j];
   115798         pNew->prereq |= pTerm->prereqRight;
   115799         assert( iTerm<pNew->nLSlot );
   115800         pNew->aLTerm[iTerm] = pTerm;
   115801         if( iTerm>mxTerm ) mxTerm = iTerm;
   115802         testcase( iTerm==15 );
   115803         testcase( iTerm==16 );
   115804         if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
   115805         if( (pTerm->eOperator & WO_IN)!=0 ){
   115806           if( pUsage[i].omit==0 ){
   115807             /* Do not attempt to use an IN constraint if the virtual table
   115808             ** says that the equivalent EQ constraint cannot be safely omitted.
   115809             ** If we do attempt to use such a constraint, some rows might be
   115810             ** repeated in the output. */
   115811             break;
   115812           }
   115813           /* A virtual table that is constrained by an IN clause may not
   115814           ** consume the ORDER BY clause because (1) the order of IN terms
   115815           ** is not necessarily related to the order of output terms and
   115816           ** (2) Multiple outputs from a single IN value will not merge
   115817           ** together.  */
   115818           pIdxInfo->orderByConsumed = 0;
   115819         }
   115820       }
   115821     }
   115822     if( i>=nConstraint ){
   115823       pNew->nLTerm = mxTerm+1;
   115824       assert( pNew->nLTerm<=pNew->nLSlot );
   115825       pNew->u.vtab.idxNum = pIdxInfo->idxNum;
   115826       pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
   115827       pIdxInfo->needToFreeIdxStr = 0;
   115828       pNew->u.vtab.idxStr = pIdxInfo->idxStr;
   115829       pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
   115830                                       pIdxInfo->nOrderBy : 0);
   115831       pNew->rSetup = 0;
   115832       pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
   115833       pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
   115834       whereLoopInsert(pBuilder, pNew);
   115835       if( pNew->u.vtab.needFree ){
   115836         sqlite3_free(pNew->u.vtab.idxStr);
   115837         pNew->u.vtab.needFree = 0;
   115838       }
   115839     }
   115840   }
   115841 
   115842 whereLoopAddVtab_exit:
   115843   if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
   115844   sqlite3DbFree(db, pIdxInfo);
   115845   return rc;
   115846 }
   115847 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   115848 
   115849 /*
   115850 ** Add WhereLoop entries to handle OR terms.  This works for either
   115851 ** btrees or virtual tables.
   115852 */
   115853 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
   115854   WhereInfo *pWInfo = pBuilder->pWInfo;
   115855   WhereClause *pWC;
   115856   WhereLoop *pNew;
   115857   WhereTerm *pTerm, *pWCEnd;
   115858   int rc = SQLITE_OK;
   115859   int iCur;
   115860   WhereClause tempWC;
   115861   WhereLoopBuilder sSubBuild;
   115862   WhereOrSet sSum, sCur;
   115863   struct SrcList_item *pItem;
   115864 
   115865   pWC = pBuilder->pWC;
   115866   if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
   115867   pWCEnd = pWC->a + pWC->nTerm;
   115868   pNew = pBuilder->pNew;
   115869   memset(&sSum, 0, sizeof(sSum));
   115870   pItem = pWInfo->pTabList->a + pNew->iTab;
   115871   iCur = pItem->iCursor;
   115872 
   115873   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
   115874     if( (pTerm->eOperator & WO_OR)!=0
   115875      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
   115876     ){
   115877       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
   115878       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
   115879       WhereTerm *pOrTerm;
   115880       int once = 1;
   115881       int i, j;
   115882 
   115883       sSubBuild = *pBuilder;
   115884       sSubBuild.pOrderBy = 0;
   115885       sSubBuild.pOrSet = &sCur;
   115886 
   115887       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
   115888         if( (pOrTerm->eOperator & WO_AND)!=0 ){
   115889           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
   115890         }else if( pOrTerm->leftCursor==iCur ){
   115891           tempWC.pWInfo = pWC->pWInfo;
   115892           tempWC.pOuter = pWC;
   115893           tempWC.op = TK_AND;
   115894           tempWC.nTerm = 1;
   115895           tempWC.a = pOrTerm;
   115896           sSubBuild.pWC = &tempWC;
   115897         }else{
   115898           continue;
   115899         }
   115900         sCur.n = 0;
   115901 #ifndef SQLITE_OMIT_VIRTUALTABLE
   115902         if( IsVirtual(pItem->pTab) ){
   115903           rc = whereLoopAddVirtual(&sSubBuild, mExtra);
   115904         }else
   115905 #endif
   115906         {
   115907           rc = whereLoopAddBtree(&sSubBuild, mExtra);
   115908         }
   115909         assert( rc==SQLITE_OK || sCur.n==0 );
   115910         if( sCur.n==0 ){
   115911           sSum.n = 0;
   115912           break;
   115913         }else if( once ){
   115914           whereOrMove(&sSum, &sCur);
   115915           once = 0;
   115916         }else{
   115917           WhereOrSet sPrev;
   115918           whereOrMove(&sPrev, &sSum);
   115919           sSum.n = 0;
   115920           for(i=0; i<sPrev.n; i++){
   115921             for(j=0; j<sCur.n; j++){
   115922               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
   115923                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
   115924                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
   115925             }
   115926           }
   115927         }
   115928       }
   115929       pNew->nLTerm = 1;
   115930       pNew->aLTerm[0] = pTerm;
   115931       pNew->wsFlags = WHERE_MULTI_OR;
   115932       pNew->rSetup = 0;
   115933       pNew->iSortIdx = 0;
   115934       memset(&pNew->u, 0, sizeof(pNew->u));
   115935       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
   115936         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
   115937         ** of all sub-scans required by the OR-scan. However, due to rounding
   115938         ** errors, it may be that the cost of the OR-scan is equal to its
   115939         ** most expensive sub-scan. Add the smallest possible penalty
   115940         ** (equivalent to multiplying the cost by 1.07) to ensure that
   115941         ** this does not happen. Otherwise, for WHERE clauses such as the
   115942         ** following where there is an index on "y":
   115943         **
   115944         **     WHERE likelihood(x=?, 0.99) OR y=?
   115945         **
   115946         ** the planner may elect to "OR" together a full-table scan and an
   115947         ** index lookup. And other similarly odd results.  */
   115948         pNew->rRun = sSum.a[i].rRun + 1;
   115949         pNew->nOut = sSum.a[i].nOut;
   115950         pNew->prereq = sSum.a[i].prereq;
   115951         rc = whereLoopInsert(pBuilder, pNew);
   115952       }
   115953     }
   115954   }
   115955   return rc;
   115956 }
   115957 
   115958 /*
   115959 ** Add all WhereLoop objects for all tables
   115960 */
   115961 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
   115962   WhereInfo *pWInfo = pBuilder->pWInfo;
   115963   Bitmask mExtra = 0;
   115964   Bitmask mPrior = 0;
   115965   int iTab;
   115966   SrcList *pTabList = pWInfo->pTabList;
   115967   struct SrcList_item *pItem;
   115968   sqlite3 *db = pWInfo->pParse->db;
   115969   int nTabList = pWInfo->nLevel;
   115970   int rc = SQLITE_OK;
   115971   u8 priorJoinType = 0;
   115972   WhereLoop *pNew;
   115973 
   115974   /* Loop over the tables in the join, from left to right */
   115975   pNew = pBuilder->pNew;
   115976   whereLoopInit(pNew);
   115977   for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
   115978     pNew->iTab = iTab;
   115979     pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
   115980     if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
   115981       mExtra = mPrior;
   115982     }
   115983     priorJoinType = pItem->jointype;
   115984     if( IsVirtual(pItem->pTab) ){
   115985       rc = whereLoopAddVirtual(pBuilder, mExtra);
   115986     }else{
   115987       rc = whereLoopAddBtree(pBuilder, mExtra);
   115988     }
   115989     if( rc==SQLITE_OK ){
   115990       rc = whereLoopAddOr(pBuilder, mExtra);
   115991     }
   115992     mPrior |= pNew->maskSelf;
   115993     if( rc || db->mallocFailed ) break;
   115994   }
   115995   whereLoopClear(db, pNew);
   115996   return rc;
   115997 }
   115998 
   115999 /*
   116000 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
   116001 ** parameters) to see if it outputs rows in the requested ORDER BY
   116002 ** (or GROUP BY) without requiring a separate sort operation.  Return N:
   116003 **
   116004 **   N>0:   N terms of the ORDER BY clause are satisfied
   116005 **   N==0:  No terms of the ORDER BY clause are satisfied
   116006 **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
   116007 **
   116008 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
   116009 ** strict.  With GROUP BY and DISTINCT the only requirement is that
   116010 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
   116011 ** and DISTINCT do not require rows to appear in any particular order as long
   116012 ** as equivelent rows are grouped together.  Thus for GROUP BY and DISTINCT
   116013 ** the pOrderBy terms can be matched in any order.  With ORDER BY, the
   116014 ** pOrderBy terms must be matched in strict left-to-right order.
   116015 */
   116016 static i8 wherePathSatisfiesOrderBy(
   116017   WhereInfo *pWInfo,    /* The WHERE clause */
   116018   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
   116019   WherePath *pPath,     /* The WherePath to check */
   116020   u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
   116021   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
   116022   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
   116023   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
   116024 ){
   116025   u8 revSet;            /* True if rev is known */
   116026   u8 rev;               /* Composite sort order */
   116027   u8 revIdx;            /* Index sort order */
   116028   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
   116029   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
   116030   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
   116031   u16 nKeyCol;          /* Number of key columns in pIndex */
   116032   u16 nColumn;          /* Total number of ordered columns in the index */
   116033   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
   116034   int iLoop;            /* Index of WhereLoop in pPath being processed */
   116035   int i, j;             /* Loop counters */
   116036   int iCur;             /* Cursor number for current WhereLoop */
   116037   int iColumn;          /* A column number within table iCur */
   116038   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
   116039   WhereTerm *pTerm;     /* A single term of the WHERE clause */
   116040   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
   116041   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
   116042   Index *pIndex;        /* The index associated with pLoop */
   116043   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
   116044   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
   116045   Bitmask obDone;       /* Mask of all ORDER BY terms */
   116046   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
   116047   Bitmask ready;              /* Mask of inner loops */
   116048 
   116049   /*
   116050   ** We say the WhereLoop is "one-row" if it generates no more than one
   116051   ** row of output.  A WhereLoop is one-row if all of the following are true:
   116052   **  (a) All index columns match with WHERE_COLUMN_EQ.
   116053   **  (b) The index is unique
   116054   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
   116055   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
   116056   **
   116057   ** We say the WhereLoop is "order-distinct" if the set of columns from
   116058   ** that WhereLoop that are in the ORDER BY clause are different for every
   116059   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
   116060   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
   116061   ** is not order-distinct. To be order-distinct is not quite the same as being
   116062   ** UNIQUE since a UNIQUE column or index can have multiple rows that
   116063   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
   116064   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
   116065   **
   116066   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
   116067   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
   116068   ** automatically order-distinct.
   116069   */
   116070 
   116071   assert( pOrderBy!=0 );
   116072   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
   116073 
   116074   nOrderBy = pOrderBy->nExpr;
   116075   testcase( nOrderBy==BMS-1 );
   116076   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
   116077   isOrderDistinct = 1;
   116078   obDone = MASKBIT(nOrderBy)-1;
   116079   orderDistinctMask = 0;
   116080   ready = 0;
   116081   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
   116082     if( iLoop>0 ) ready |= pLoop->maskSelf;
   116083     pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
   116084     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
   116085       if( pLoop->u.vtab.isOrdered ) obSat = obDone;
   116086       break;
   116087     }
   116088     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
   116089 
   116090     /* Mark off any ORDER BY term X that is a column in the table of
   116091     ** the current loop for which there is term in the WHERE
   116092     ** clause of the form X IS NULL or X=? that reference only outer
   116093     ** loops.
   116094     */
   116095     for(i=0; i<nOrderBy; i++){
   116096       if( MASKBIT(i) & obSat ) continue;
   116097       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
   116098       if( pOBExpr->op!=TK_COLUMN ) continue;
   116099       if( pOBExpr->iTable!=iCur ) continue;
   116100       pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
   116101                        ~ready, WO_EQ|WO_ISNULL, 0);
   116102       if( pTerm==0 ) continue;
   116103       if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
   116104         const char *z1, *z2;
   116105         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
   116106         if( !pColl ) pColl = db->pDfltColl;
   116107         z1 = pColl->zName;
   116108         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
   116109         if( !pColl ) pColl = db->pDfltColl;
   116110         z2 = pColl->zName;
   116111         if( sqlite3StrICmp(z1, z2)!=0 ) continue;
   116112       }
   116113       obSat |= MASKBIT(i);
   116114     }
   116115 
   116116     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
   116117       if( pLoop->wsFlags & WHERE_IPK ){
   116118         pIndex = 0;
   116119         nKeyCol = 0;
   116120         nColumn = 1;
   116121       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
   116122         return 0;
   116123       }else{
   116124         nKeyCol = pIndex->nKeyCol;
   116125         nColumn = pIndex->nColumn;
   116126         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
   116127         assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
   116128         isOrderDistinct = IsUniqueIndex(pIndex);
   116129       }
   116130 
   116131       /* Loop through all columns of the index and deal with the ones
   116132       ** that are not constrained by == or IN.
   116133       */
   116134       rev = revSet = 0;
   116135       distinctColumns = 0;
   116136       for(j=0; j<nColumn; j++){
   116137         u8 bOnce;   /* True to run the ORDER BY search loop */
   116138 
   116139         /* Skip over == and IS NULL terms */
   116140         if( j<pLoop->u.btree.nEq
   116141          && pLoop->u.btree.nSkip==0
   116142          && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
   116143         ){
   116144           if( i & WO_ISNULL ){
   116145             testcase( isOrderDistinct );
   116146             isOrderDistinct = 0;
   116147           }
   116148           continue;
   116149         }
   116150 
   116151         /* Get the column number in the table (iColumn) and sort order
   116152         ** (revIdx) for the j-th column of the index.
   116153         */
   116154         if( pIndex ){
   116155           iColumn = pIndex->aiColumn[j];
   116156           revIdx = pIndex->aSortOrder[j];
   116157           if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
   116158         }else{
   116159           iColumn = -1;
   116160           revIdx = 0;
   116161         }
   116162 
   116163         /* An unconstrained column that might be NULL means that this
   116164         ** WhereLoop is not well-ordered
   116165         */
   116166         if( isOrderDistinct
   116167          && iColumn>=0
   116168          && j>=pLoop->u.btree.nEq
   116169          && pIndex->pTable->aCol[iColumn].notNull==0
   116170         ){
   116171           isOrderDistinct = 0;
   116172         }
   116173 
   116174         /* Find the ORDER BY term that corresponds to the j-th column
   116175         ** of the index and mark that ORDER BY term off
   116176         */
   116177         bOnce = 1;
   116178         isMatch = 0;
   116179         for(i=0; bOnce && i<nOrderBy; i++){
   116180           if( MASKBIT(i) & obSat ) continue;
   116181           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
   116182           testcase( wctrlFlags & WHERE_GROUPBY );
   116183           testcase( wctrlFlags & WHERE_DISTINCTBY );
   116184           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
   116185           if( pOBExpr->op!=TK_COLUMN ) continue;
   116186           if( pOBExpr->iTable!=iCur ) continue;
   116187           if( pOBExpr->iColumn!=iColumn ) continue;
   116188           if( iColumn>=0 ){
   116189             pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
   116190             if( !pColl ) pColl = db->pDfltColl;
   116191             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
   116192           }
   116193           isMatch = 1;
   116194           break;
   116195         }
   116196         if( isMatch && (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
   116197           /* Make sure the sort order is compatible in an ORDER BY clause.
   116198           ** Sort order is irrelevant for a GROUP BY clause. */
   116199           if( revSet ){
   116200             if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
   116201           }else{
   116202             rev = revIdx ^ pOrderBy->a[i].sortOrder;
   116203             if( rev ) *pRevMask |= MASKBIT(iLoop);
   116204             revSet = 1;
   116205           }
   116206         }
   116207         if( isMatch ){
   116208           if( iColumn<0 ){
   116209             testcase( distinctColumns==0 );
   116210             distinctColumns = 1;
   116211           }
   116212           obSat |= MASKBIT(i);
   116213         }else{
   116214           /* No match found */
   116215           if( j==0 || j<nKeyCol ){
   116216             testcase( isOrderDistinct!=0 );
   116217             isOrderDistinct = 0;
   116218           }
   116219           break;
   116220         }
   116221       } /* end Loop over all index columns */
   116222       if( distinctColumns ){
   116223         testcase( isOrderDistinct==0 );
   116224         isOrderDistinct = 1;
   116225       }
   116226     } /* end-if not one-row */
   116227 
   116228     /* Mark off any other ORDER BY terms that reference pLoop */
   116229     if( isOrderDistinct ){
   116230       orderDistinctMask |= pLoop->maskSelf;
   116231       for(i=0; i<nOrderBy; i++){
   116232         Expr *p;
   116233         Bitmask mTerm;
   116234         if( MASKBIT(i) & obSat ) continue;
   116235         p = pOrderBy->a[i].pExpr;
   116236         mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
   116237         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
   116238         if( (mTerm&~orderDistinctMask)==0 ){
   116239           obSat |= MASKBIT(i);
   116240         }
   116241       }
   116242     }
   116243   } /* End the loop over all WhereLoops from outer-most down to inner-most */
   116244   if( obSat==obDone ) return (i8)nOrderBy;
   116245   if( !isOrderDistinct ){
   116246     for(i=nOrderBy-1; i>0; i--){
   116247       Bitmask m = MASKBIT(i) - 1;
   116248       if( (obSat&m)==m ) return i;
   116249     }
   116250     return 0;
   116251   }
   116252   return -1;
   116253 }
   116254 
   116255 
   116256 /*
   116257 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
   116258 ** the planner assumes that the specified pOrderBy list is actually a GROUP
   116259 ** BY clause - and so any order that groups rows as required satisfies the
   116260 ** request.
   116261 **
   116262 ** Normally, in this case it is not possible for the caller to determine
   116263 ** whether or not the rows are really being delivered in sorted order, or
   116264 ** just in some other order that provides the required grouping. However,
   116265 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
   116266 ** this function may be called on the returned WhereInfo object. It returns
   116267 ** true if the rows really will be sorted in the specified order, or false
   116268 ** otherwise.
   116269 **
   116270 ** For example, assuming:
   116271 **
   116272 **   CREATE INDEX i1 ON t1(x, Y);
   116273 **
   116274 ** then
   116275 **
   116276 **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
   116277 **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
   116278 */
   116279 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
   116280   assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
   116281   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
   116282   return pWInfo->sorted;
   116283 }
   116284 
   116285 #ifdef WHERETRACE_ENABLED
   116286 /* For debugging use only: */
   116287 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
   116288   static char zName[65];
   116289   int i;
   116290   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
   116291   if( pLast ) zName[i++] = pLast->cId;
   116292   zName[i] = 0;
   116293   return zName;
   116294 }
   116295 #endif
   116296 
   116297 /*
   116298 ** Return the cost of sorting nRow rows, assuming that the keys have
   116299 ** nOrderby columns and that the first nSorted columns are already in
   116300 ** order.
   116301 */
   116302 static LogEst whereSortingCost(
   116303   WhereInfo *pWInfo,
   116304   LogEst nRow,
   116305   int nOrderBy,
   116306   int nSorted
   116307 ){
   116308   /* TUNING: Estimated cost of a full external sort, where N is
   116309   ** the number of rows to sort is:
   116310   **
   116311   **   cost = (3.0 * N * log(N)).
   116312   **
   116313   ** Or, if the order-by clause has X terms but only the last Y
   116314   ** terms are out of order, then block-sorting will reduce the
   116315   ** sorting cost to:
   116316   **
   116317   **   cost = (3.0 * N * log(N)) * (Y/X)
   116318   **
   116319   ** The (Y/X) term is implemented using stack variable rScale
   116320   ** below.  */
   116321   LogEst rScale, rSortCost;
   116322   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
   116323   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
   116324   rSortCost = nRow + estLog(nRow) + rScale + 16;
   116325 
   116326   /* TUNING: The cost of implementing DISTINCT using a B-TREE is
   116327   ** similar but with a larger constant of proportionality.
   116328   ** Multiply by an additional factor of 3.0.  */
   116329   if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
   116330     rSortCost += 16;
   116331   }
   116332 
   116333   return rSortCost;
   116334 }
   116335 
   116336 /*
   116337 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
   116338 ** attempts to find the lowest cost path that visits each WhereLoop
   116339 ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
   116340 **
   116341 ** Assume that the total number of output rows that will need to be sorted
   116342 ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
   116343 ** costs if nRowEst==0.
   116344 **
   116345 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
   116346 ** error occurs.
   116347 */
   116348 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
   116349   int mxChoice;             /* Maximum number of simultaneous paths tracked */
   116350   int nLoop;                /* Number of terms in the join */
   116351   Parse *pParse;            /* Parsing context */
   116352   sqlite3 *db;              /* The database connection */
   116353   int iLoop;                /* Loop counter over the terms of the join */
   116354   int ii, jj;               /* Loop counters */
   116355   int mxI = 0;              /* Index of next entry to replace */
   116356   int nOrderBy;             /* Number of ORDER BY clause terms */
   116357   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
   116358   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
   116359   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
   116360   WherePath *aFrom;         /* All nFrom paths at the previous level */
   116361   WherePath *aTo;           /* The nTo best paths at the current level */
   116362   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
   116363   WherePath *pTo;           /* An element of aTo[] that we are working on */
   116364   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
   116365   WhereLoop **pX;           /* Used to divy up the pSpace memory */
   116366   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
   116367   char *pSpace;             /* Temporary memory used by this routine */
   116368   int nSpace;               /* Bytes of space allocated at pSpace */
   116369 
   116370   pParse = pWInfo->pParse;
   116371   db = pParse->db;
   116372   nLoop = pWInfo->nLevel;
   116373   /* TUNING: For simple queries, only the best path is tracked.
   116374   ** For 2-way joins, the 5 best paths are followed.
   116375   ** For joins of 3 or more tables, track the 10 best paths */
   116376   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
   116377   assert( nLoop<=pWInfo->pTabList->nSrc );
   116378   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
   116379 
   116380   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
   116381   ** case the purpose of this call is to estimate the number of rows returned
   116382   ** by the overall query. Once this estimate has been obtained, the caller
   116383   ** will invoke this function a second time, passing the estimate as the
   116384   ** nRowEst parameter.  */
   116385   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
   116386     nOrderBy = 0;
   116387   }else{
   116388     nOrderBy = pWInfo->pOrderBy->nExpr;
   116389   }
   116390 
   116391   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
   116392   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
   116393   nSpace += sizeof(LogEst) * nOrderBy;
   116394   pSpace = sqlite3DbMallocRaw(db, nSpace);
   116395   if( pSpace==0 ) return SQLITE_NOMEM;
   116396   aTo = (WherePath*)pSpace;
   116397   aFrom = aTo+mxChoice;
   116398   memset(aFrom, 0, sizeof(aFrom[0]));
   116399   pX = (WhereLoop**)(aFrom+mxChoice);
   116400   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
   116401     pFrom->aLoop = pX;
   116402   }
   116403   if( nOrderBy ){
   116404     /* If there is an ORDER BY clause and it is not being ignored, set up
   116405     ** space for the aSortCost[] array. Each element of the aSortCost array
   116406     ** is either zero - meaning it has not yet been initialized - or the
   116407     ** cost of sorting nRowEst rows of data where the first X terms of
   116408     ** the ORDER BY clause are already in order, where X is the array
   116409     ** index.  */
   116410     aSortCost = (LogEst*)pX;
   116411     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
   116412   }
   116413   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
   116414   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
   116415 
   116416   /* Seed the search with a single WherePath containing zero WhereLoops.
   116417   **
   116418   ** TUNING: Do not let the number of iterations go above 25.  If the cost
   116419   ** of computing an automatic index is not paid back within the first 25
   116420   ** rows, then do not use the automatic index. */
   116421   aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==sqlite3LogEst(25) );
   116422   nFrom = 1;
   116423   assert( aFrom[0].isOrdered==0 );
   116424   if( nOrderBy ){
   116425     /* If nLoop is zero, then there are no FROM terms in the query. Since
   116426     ** in this case the query may return a maximum of one row, the results
   116427     ** are already in the requested order. Set isOrdered to nOrderBy to
   116428     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
   116429     ** -1, indicating that the result set may or may not be ordered,
   116430     ** depending on the loops added to the current plan.  */
   116431     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
   116432   }
   116433 
   116434   /* Compute successively longer WherePaths using the previous generation
   116435   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
   116436   ** best paths at each generation */
   116437   for(iLoop=0; iLoop<nLoop; iLoop++){
   116438     nTo = 0;
   116439     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
   116440       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
   116441         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
   116442         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
   116443         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
   116444         i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
   116445         Bitmask maskNew;                  /* Mask of src visited by (..) */
   116446         Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
   116447 
   116448         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
   116449         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
   116450         /* At this point, pWLoop is a candidate to be the next loop.
   116451         ** Compute its cost */
   116452         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
   116453         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
   116454         nOut = pFrom->nRow + pWLoop->nOut;
   116455         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
   116456         if( isOrdered<0 ){
   116457           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
   116458                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
   116459                        iLoop, pWLoop, &revMask);
   116460         }else{
   116461           revMask = pFrom->revLoop;
   116462         }
   116463         if( isOrdered>=0 && isOrdered<nOrderBy ){
   116464           if( aSortCost[isOrdered]==0 ){
   116465             aSortCost[isOrdered] = whereSortingCost(
   116466                 pWInfo, nRowEst, nOrderBy, isOrdered
   116467             );
   116468           }
   116469           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
   116470 
   116471           WHERETRACE(0x002,
   116472               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
   116473                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
   116474                rUnsorted, rCost));
   116475         }else{
   116476           rCost = rUnsorted;
   116477         }
   116478 
   116479         /* Check to see if pWLoop should be added to the set of
   116480         ** mxChoice best-so-far paths.
   116481         **
   116482         ** First look for an existing path among best-so-far paths
   116483         ** that covers the same set of loops and has the same isOrdered
   116484         ** setting as the current path candidate.
   116485         **
   116486         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
   116487         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
   116488         ** of legal values for isOrdered, -1..64.
   116489         */
   116490         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
   116491           if( pTo->maskLoop==maskNew
   116492            && ((pTo->isOrdered^isOrdered)&0x80)==0
   116493           ){
   116494             testcase( jj==nTo-1 );
   116495             break;
   116496           }
   116497         }
   116498         if( jj>=nTo ){
   116499           /* None of the existing best-so-far paths match the candidate. */
   116500           if( nTo>=mxChoice
   116501            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
   116502           ){
   116503             /* The current candidate is no better than any of the mxChoice
   116504             ** paths currently in the best-so-far buffer.  So discard
   116505             ** this candidate as not viable. */
   116506 #ifdef WHERETRACE_ENABLED /* 0x4 */
   116507             if( sqlite3WhereTrace&0x4 ){
   116508               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
   116509                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
   116510                   isOrdered>=0 ? isOrdered+'0' : '?');
   116511             }
   116512 #endif
   116513             continue;
   116514           }
   116515           /* If we reach this points it means that the new candidate path
   116516           ** needs to be added to the set of best-so-far paths. */
   116517           if( nTo<mxChoice ){
   116518             /* Increase the size of the aTo set by one */
   116519             jj = nTo++;
   116520           }else{
   116521             /* New path replaces the prior worst to keep count below mxChoice */
   116522             jj = mxI;
   116523           }
   116524           pTo = &aTo[jj];
   116525 #ifdef WHERETRACE_ENABLED /* 0x4 */
   116526           if( sqlite3WhereTrace&0x4 ){
   116527             sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
   116528                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
   116529                 isOrdered>=0 ? isOrdered+'0' : '?');
   116530           }
   116531 #endif
   116532         }else{
   116533           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
   116534           ** same set of loops and has the sam isOrdered setting as the
   116535           ** candidate path.  Check to see if the candidate should replace
   116536           ** pTo or if the candidate should be skipped */
   116537           if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
   116538 #ifdef WHERETRACE_ENABLED /* 0x4 */
   116539             if( sqlite3WhereTrace&0x4 ){
   116540               sqlite3DebugPrintf(
   116541                   "Skip   %s cost=%-3d,%3d order=%c",
   116542                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
   116543                   isOrdered>=0 ? isOrdered+'0' : '?');
   116544               sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
   116545                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   116546                   pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
   116547             }
   116548 #endif
   116549             /* Discard the candidate path from further consideration */
   116550             testcase( pTo->rCost==rCost );
   116551             continue;
   116552           }
   116553           testcase( pTo->rCost==rCost+1 );
   116554           /* Control reaches here if the candidate path is better than the
   116555           ** pTo path.  Replace pTo with the candidate. */
   116556 #ifdef WHERETRACE_ENABLED /* 0x4 */
   116557           if( sqlite3WhereTrace&0x4 ){
   116558             sqlite3DebugPrintf(
   116559                 "Update %s cost=%-3d,%3d order=%c",
   116560                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
   116561                 isOrdered>=0 ? isOrdered+'0' : '?');
   116562             sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
   116563                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   116564                 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
   116565           }
   116566 #endif
   116567         }
   116568         /* pWLoop is a winner.  Add it to the set of best so far */
   116569         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
   116570         pTo->revLoop = revMask;
   116571         pTo->nRow = nOut;
   116572         pTo->rCost = rCost;
   116573         pTo->rUnsorted = rUnsorted;
   116574         pTo->isOrdered = isOrdered;
   116575         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
   116576         pTo->aLoop[iLoop] = pWLoop;
   116577         if( nTo>=mxChoice ){
   116578           mxI = 0;
   116579           mxCost = aTo[0].rCost;
   116580           mxUnsorted = aTo[0].nRow;
   116581           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
   116582             if( pTo->rCost>mxCost
   116583              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
   116584             ){
   116585               mxCost = pTo->rCost;
   116586               mxUnsorted = pTo->rUnsorted;
   116587               mxI = jj;
   116588             }
   116589           }
   116590         }
   116591       }
   116592     }
   116593 
   116594 #ifdef WHERETRACE_ENABLED  /* >=2 */
   116595     if( sqlite3WhereTrace>=2 ){
   116596       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
   116597       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
   116598         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
   116599            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   116600            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
   116601         if( pTo->isOrdered>0 ){
   116602           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
   116603         }else{
   116604           sqlite3DebugPrintf("\n");
   116605         }
   116606       }
   116607     }
   116608 #endif
   116609 
   116610     /* Swap the roles of aFrom and aTo for the next generation */
   116611     pFrom = aTo;
   116612     aTo = aFrom;
   116613     aFrom = pFrom;
   116614     nFrom = nTo;
   116615   }
   116616 
   116617   if( nFrom==0 ){
   116618     sqlite3ErrorMsg(pParse, "no query solution");
   116619     sqlite3DbFree(db, pSpace);
   116620     return SQLITE_ERROR;
   116621   }
   116622 
   116623   /* Find the lowest cost path.  pFrom will be left pointing to that path */
   116624   pFrom = aFrom;
   116625   for(ii=1; ii<nFrom; ii++){
   116626     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
   116627   }
   116628   assert( pWInfo->nLevel==nLoop );
   116629   /* Load the lowest cost path into pWInfo */
   116630   for(iLoop=0; iLoop<nLoop; iLoop++){
   116631     WhereLevel *pLevel = pWInfo->a + iLoop;
   116632     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
   116633     pLevel->iFrom = pWLoop->iTab;
   116634     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
   116635   }
   116636   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
   116637    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
   116638    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
   116639    && nRowEst
   116640   ){
   116641     Bitmask notUsed;
   116642     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
   116643                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
   116644     if( rc==pWInfo->pResultSet->nExpr ){
   116645       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
   116646     }
   116647   }
   116648   if( pWInfo->pOrderBy ){
   116649     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
   116650       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
   116651         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
   116652       }
   116653     }else{
   116654       pWInfo->nOBSat = pFrom->isOrdered;
   116655       if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
   116656       pWInfo->revMask = pFrom->revLoop;
   116657     }
   116658     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
   116659         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
   116660     ){
   116661       Bitmask notUsed = 0;
   116662       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
   116663           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed
   116664       );
   116665       assert( pWInfo->sorted==0 );
   116666       pWInfo->sorted = (nOrder==pWInfo->pOrderBy->nExpr);
   116667     }
   116668   }
   116669 
   116670 
   116671   pWInfo->nRowOut = pFrom->nRow;
   116672 
   116673   /* Free temporary memory and return success */
   116674   sqlite3DbFree(db, pSpace);
   116675   return SQLITE_OK;
   116676 }
   116677 
   116678 /*
   116679 ** Most queries use only a single table (they are not joins) and have
   116680 ** simple == constraints against indexed fields.  This routine attempts
   116681 ** to plan those simple cases using much less ceremony than the
   116682 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
   116683 ** times for the common case.
   116684 **
   116685 ** Return non-zero on success, if this query can be handled by this
   116686 ** no-frills query planner.  Return zero if this query needs the
   116687 ** general-purpose query planner.
   116688 */
   116689 static int whereShortCut(WhereLoopBuilder *pBuilder){
   116690   WhereInfo *pWInfo;
   116691   struct SrcList_item *pItem;
   116692   WhereClause *pWC;
   116693   WhereTerm *pTerm;
   116694   WhereLoop *pLoop;
   116695   int iCur;
   116696   int j;
   116697   Table *pTab;
   116698   Index *pIdx;
   116699 
   116700   pWInfo = pBuilder->pWInfo;
   116701   if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
   116702   assert( pWInfo->pTabList->nSrc>=1 );
   116703   pItem = pWInfo->pTabList->a;
   116704   pTab = pItem->pTab;
   116705   if( IsVirtual(pTab) ) return 0;
   116706   if( pItem->zIndex ) return 0;
   116707   iCur = pItem->iCursor;
   116708   pWC = &pWInfo->sWC;
   116709   pLoop = pBuilder->pNew;
   116710   pLoop->wsFlags = 0;
   116711   pLoop->u.btree.nSkip = 0;
   116712   pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
   116713   if( pTerm ){
   116714     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
   116715     pLoop->aLTerm[0] = pTerm;
   116716     pLoop->nLTerm = 1;
   116717     pLoop->u.btree.nEq = 1;
   116718     /* TUNING: Cost of a rowid lookup is 10 */
   116719     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
   116720   }else{
   116721     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   116722       assert( pLoop->aLTermSpace==pLoop->aLTerm );
   116723       assert( ArraySize(pLoop->aLTermSpace)==4 );
   116724       if( !IsUniqueIndex(pIdx)
   116725        || pIdx->pPartIdxWhere!=0
   116726        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
   116727       ) continue;
   116728       for(j=0; j<pIdx->nKeyCol; j++){
   116729         pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
   116730         if( pTerm==0 ) break;
   116731         pLoop->aLTerm[j] = pTerm;
   116732       }
   116733       if( j!=pIdx->nKeyCol ) continue;
   116734       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
   116735       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
   116736         pLoop->wsFlags |= WHERE_IDX_ONLY;
   116737       }
   116738       pLoop->nLTerm = j;
   116739       pLoop->u.btree.nEq = j;
   116740       pLoop->u.btree.pIndex = pIdx;
   116741       /* TUNING: Cost of a unique index lookup is 15 */
   116742       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
   116743       break;
   116744     }
   116745   }
   116746   if( pLoop->wsFlags ){
   116747     pLoop->nOut = (LogEst)1;
   116748     pWInfo->a[0].pWLoop = pLoop;
   116749     pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
   116750     pWInfo->a[0].iTabCur = iCur;
   116751     pWInfo->nRowOut = 1;
   116752     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
   116753     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
   116754       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   116755     }
   116756 #ifdef SQLITE_DEBUG
   116757     pLoop->cId = '0';
   116758 #endif
   116759     return 1;
   116760   }
   116761   return 0;
   116762 }
   116763 
   116764 /*
   116765 ** Generate the beginning of the loop used for WHERE clause processing.
   116766 ** The return value is a pointer to an opaque structure that contains
   116767 ** information needed to terminate the loop.  Later, the calling routine
   116768 ** should invoke sqlite3WhereEnd() with the return value of this function
   116769 ** in order to complete the WHERE clause processing.
   116770 **
   116771 ** If an error occurs, this routine returns NULL.
   116772 **
   116773 ** The basic idea is to do a nested loop, one loop for each table in
   116774 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
   116775 ** same as a SELECT with only a single table in the FROM clause.)  For
   116776 ** example, if the SQL is this:
   116777 **
   116778 **       SELECT * FROM t1, t2, t3 WHERE ...;
   116779 **
   116780 ** Then the code generated is conceptually like the following:
   116781 **
   116782 **      foreach row1 in t1 do       \    Code generated
   116783 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
   116784 **          foreach row3 in t3 do   /
   116785 **            ...
   116786 **          end                     \    Code generated
   116787 **        end                        |-- by sqlite3WhereEnd()
   116788 **      end                         /
   116789 **
   116790 ** Note that the loops might not be nested in the order in which they
   116791 ** appear in the FROM clause if a different order is better able to make
   116792 ** use of indices.  Note also that when the IN operator appears in
   116793 ** the WHERE clause, it might result in additional nested loops for
   116794 ** scanning through all values on the right-hand side of the IN.
   116795 **
   116796 ** There are Btree cursors associated with each table.  t1 uses cursor
   116797 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
   116798 ** And so forth.  This routine generates code to open those VDBE cursors
   116799 ** and sqlite3WhereEnd() generates the code to close them.
   116800 **
   116801 ** The code that sqlite3WhereBegin() generates leaves the cursors named
   116802 ** in pTabList pointing at their appropriate entries.  The [...] code
   116803 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
   116804 ** data from the various tables of the loop.
   116805 **
   116806 ** If the WHERE clause is empty, the foreach loops must each scan their
   116807 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
   116808 ** the tables have indices and there are terms in the WHERE clause that
   116809 ** refer to those indices, a complete table scan can be avoided and the
   116810 ** code will run much faster.  Most of the work of this routine is checking
   116811 ** to see if there are indices that can be used to speed up the loop.
   116812 **
   116813 ** Terms of the WHERE clause are also used to limit which rows actually
   116814 ** make it to the "..." in the middle of the loop.  After each "foreach",
   116815 ** terms of the WHERE clause that use only terms in that loop and outer
   116816 ** loops are evaluated and if false a jump is made around all subsequent
   116817 ** inner loops (or around the "..." if the test occurs within the inner-
   116818 ** most loop)
   116819 **
   116820 ** OUTER JOINS
   116821 **
   116822 ** An outer join of tables t1 and t2 is conceptally coded as follows:
   116823 **
   116824 **    foreach row1 in t1 do
   116825 **      flag = 0
   116826 **      foreach row2 in t2 do
   116827 **        start:
   116828 **          ...
   116829 **          flag = 1
   116830 **      end
   116831 **      if flag==0 then
   116832 **        move the row2 cursor to a null row
   116833 **        goto start
   116834 **      fi
   116835 **    end
   116836 **
   116837 ** ORDER BY CLAUSE PROCESSING
   116838 **
   116839 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
   116840 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
   116841 ** if there is one.  If there is no ORDER BY clause or if this routine
   116842 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
   116843 **
   116844 ** The iIdxCur parameter is the cursor number of an index.  If
   116845 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
   116846 ** to use for OR clause processing.  The WHERE clause should use this
   116847 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
   116848 ** the first cursor in an array of cursors for all indices.  iIdxCur should
   116849 ** be used to compute the appropriate cursor depending on which index is
   116850 ** used.
   116851 */
   116852 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   116853   Parse *pParse,        /* The parser context */
   116854   SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
   116855   Expr *pWhere,         /* The WHERE clause */
   116856   ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
   116857   ExprList *pResultSet, /* Result set of the query */
   116858   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
   116859   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
   116860 ){
   116861   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
   116862   int nTabList;              /* Number of elements in pTabList */
   116863   WhereInfo *pWInfo;         /* Will become the return value of this function */
   116864   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
   116865   Bitmask notReady;          /* Cursors that are not yet positioned */
   116866   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
   116867   WhereMaskSet *pMaskSet;    /* The expression mask set */
   116868   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
   116869   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
   116870   int ii;                    /* Loop counter */
   116871   sqlite3 *db;               /* Database connection */
   116872   int rc;                    /* Return code */
   116873 
   116874 
   116875   /* Variable initialization */
   116876   db = pParse->db;
   116877   memset(&sWLB, 0, sizeof(sWLB));
   116878 
   116879   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
   116880   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
   116881   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
   116882   sWLB.pOrderBy = pOrderBy;
   116883 
   116884   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
   116885   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
   116886   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
   116887     wctrlFlags &= ~WHERE_WANT_DISTINCT;
   116888   }
   116889 
   116890   /* The number of tables in the FROM clause is limited by the number of
   116891   ** bits in a Bitmask
   116892   */
   116893   testcase( pTabList->nSrc==BMS );
   116894   if( pTabList->nSrc>BMS ){
   116895     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
   116896     return 0;
   116897   }
   116898 
   116899   /* This function normally generates a nested loop for all tables in
   116900   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
   116901   ** only generate code for the first table in pTabList and assume that
   116902   ** any cursors associated with subsequent tables are uninitialized.
   116903   */
   116904   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
   116905 
   116906   /* Allocate and initialize the WhereInfo structure that will become the
   116907   ** return value. A single allocation is used to store the WhereInfo
   116908   ** struct, the contents of WhereInfo.a[], the WhereClause structure
   116909   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
   116910   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
   116911   ** some architectures. Hence the ROUND8() below.
   116912   */
   116913   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
   116914   pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
   116915   if( db->mallocFailed ){
   116916     sqlite3DbFree(db, pWInfo);
   116917     pWInfo = 0;
   116918     goto whereBeginError;
   116919   }
   116920   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
   116921   pWInfo->nLevel = nTabList;
   116922   pWInfo->pParse = pParse;
   116923   pWInfo->pTabList = pTabList;
   116924   pWInfo->pOrderBy = pOrderBy;
   116925   pWInfo->pResultSet = pResultSet;
   116926   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
   116927   pWInfo->wctrlFlags = wctrlFlags;
   116928   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
   116929   pMaskSet = &pWInfo->sMaskSet;
   116930   sWLB.pWInfo = pWInfo;
   116931   sWLB.pWC = &pWInfo->sWC;
   116932   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
   116933   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
   116934   whereLoopInit(sWLB.pNew);
   116935 #ifdef SQLITE_DEBUG
   116936   sWLB.pNew->cId = '*';
   116937 #endif
   116938 
   116939   /* Split the WHERE clause into separate subexpressions where each
   116940   ** subexpression is separated by an AND operator.
   116941   */
   116942   initMaskSet(pMaskSet);
   116943   whereClauseInit(&pWInfo->sWC, pWInfo);
   116944   whereSplit(&pWInfo->sWC, pWhere, TK_AND);
   116945 
   116946   /* Special case: a WHERE clause that is constant.  Evaluate the
   116947   ** expression and either jump over all of the code or fall thru.
   116948   */
   116949   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
   116950     if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
   116951       sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
   116952                          SQLITE_JUMPIFNULL);
   116953       sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
   116954     }
   116955   }
   116956 
   116957   /* Special case: No FROM clause
   116958   */
   116959   if( nTabList==0 ){
   116960     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
   116961     if( wctrlFlags & WHERE_WANT_DISTINCT ){
   116962       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   116963     }
   116964   }
   116965 
   116966   /* Assign a bit from the bitmask to every term in the FROM clause.
   116967   **
   116968   ** When assigning bitmask values to FROM clause cursors, it must be
   116969   ** the case that if X is the bitmask for the N-th FROM clause term then
   116970   ** the bitmask for all FROM clause terms to the left of the N-th term
   116971   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
   116972   ** its Expr.iRightJoinTable value to find the bitmask of the right table
   116973   ** of the join.  Subtracting one from the right table bitmask gives a
   116974   ** bitmask for all tables to the left of the join.  Knowing the bitmask
   116975   ** for all tables to the left of a left join is important.  Ticket #3015.
   116976   **
   116977   ** Note that bitmasks are created for all pTabList->nSrc tables in
   116978   ** pTabList, not just the first nTabList tables.  nTabList is normally
   116979   ** equal to pTabList->nSrc but might be shortened to 1 if the
   116980   ** WHERE_ONETABLE_ONLY flag is set.
   116981   */
   116982   for(ii=0; ii<pTabList->nSrc; ii++){
   116983     createMask(pMaskSet, pTabList->a[ii].iCursor);
   116984   }
   116985 #ifndef NDEBUG
   116986   {
   116987     Bitmask toTheLeft = 0;
   116988     for(ii=0; ii<pTabList->nSrc; ii++){
   116989       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
   116990       assert( (m-1)==toTheLeft );
   116991       toTheLeft |= m;
   116992     }
   116993   }
   116994 #endif
   116995 
   116996   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
   116997   ** add new virtual terms onto the end of the WHERE clause.  We do not
   116998   ** want to analyze these virtual terms, so start analyzing at the end
   116999   ** and work forward so that the added virtual terms are never processed.
   117000   */
   117001   exprAnalyzeAll(pTabList, &pWInfo->sWC);
   117002   if( db->mallocFailed ){
   117003     goto whereBeginError;
   117004   }
   117005 
   117006   if( wctrlFlags & WHERE_WANT_DISTINCT ){
   117007     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
   117008       /* The DISTINCT marking is pointless.  Ignore it. */
   117009       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   117010     }else if( pOrderBy==0 ){
   117011       /* Try to ORDER BY the result set to make distinct processing easier */
   117012       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
   117013       pWInfo->pOrderBy = pResultSet;
   117014     }
   117015   }
   117016 
   117017   /* Construct the WhereLoop objects */
   117018   WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
   117019   /* Display all terms of the WHERE clause */
   117020 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
   117021   if( sqlite3WhereTrace & 0x100 ){
   117022     int i;
   117023     Vdbe *v = pParse->pVdbe;
   117024     sqlite3ExplainBegin(v);
   117025     for(i=0; i<sWLB.pWC->nTerm; i++){
   117026       sqlite3ExplainPrintf(v, "#%-2d ", i);
   117027       sqlite3ExplainPush(v);
   117028       whereExplainTerm(v, &sWLB.pWC->a[i]);
   117029       sqlite3ExplainPop(v);
   117030       sqlite3ExplainNL(v);
   117031     }
   117032     sqlite3ExplainFinish(v);
   117033     sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
   117034   }
   117035 #endif
   117036   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
   117037     rc = whereLoopAddAll(&sWLB);
   117038     if( rc ) goto whereBeginError;
   117039 
   117040     /* Display all of the WhereLoop objects if wheretrace is enabled */
   117041 #ifdef WHERETRACE_ENABLED /* !=0 */
   117042     if( sqlite3WhereTrace ){
   117043       WhereLoop *p;
   117044       int i;
   117045       static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
   117046                                        "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
   117047       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
   117048         p->cId = zLabel[i%sizeof(zLabel)];
   117049         whereLoopPrint(p, sWLB.pWC);
   117050       }
   117051     }
   117052 #endif
   117053 
   117054     wherePathSolver(pWInfo, 0);
   117055     if( db->mallocFailed ) goto whereBeginError;
   117056     if( pWInfo->pOrderBy ){
   117057        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
   117058        if( db->mallocFailed ) goto whereBeginError;
   117059     }
   117060   }
   117061   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
   117062      pWInfo->revMask = (Bitmask)(-1);
   117063   }
   117064   if( pParse->nErr || NEVER(db->mallocFailed) ){
   117065     goto whereBeginError;
   117066   }
   117067 #ifdef WHERETRACE_ENABLED /* !=0 */
   117068   if( sqlite3WhereTrace ){
   117069     int ii;
   117070     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
   117071     if( pWInfo->nOBSat>0 ){
   117072       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
   117073     }
   117074     switch( pWInfo->eDistinct ){
   117075       case WHERE_DISTINCT_UNIQUE: {
   117076         sqlite3DebugPrintf("  DISTINCT=unique");
   117077         break;
   117078       }
   117079       case WHERE_DISTINCT_ORDERED: {
   117080         sqlite3DebugPrintf("  DISTINCT=ordered");
   117081         break;
   117082       }
   117083       case WHERE_DISTINCT_UNORDERED: {
   117084         sqlite3DebugPrintf("  DISTINCT=unordered");
   117085         break;
   117086       }
   117087     }
   117088     sqlite3DebugPrintf("\n");
   117089     for(ii=0; ii<pWInfo->nLevel; ii++){
   117090       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
   117091     }
   117092   }
   117093 #endif
   117094   /* Attempt to omit tables from the join that do not effect the result */
   117095   if( pWInfo->nLevel>=2
   117096    && pResultSet!=0
   117097    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
   117098   ){
   117099     Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
   117100     if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
   117101     while( pWInfo->nLevel>=2 ){
   117102       WhereTerm *pTerm, *pEnd;
   117103       pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
   117104       if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
   117105       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
   117106        && (pLoop->wsFlags & WHERE_ONEROW)==0
   117107       ){
   117108         break;
   117109       }
   117110       if( (tabUsed & pLoop->maskSelf)!=0 ) break;
   117111       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
   117112       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
   117113         if( (pTerm->prereqAll & pLoop->maskSelf)!=0
   117114          && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
   117115         ){
   117116           break;
   117117         }
   117118       }
   117119       if( pTerm<pEnd ) break;
   117120       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
   117121       pWInfo->nLevel--;
   117122       nTabList--;
   117123     }
   117124   }
   117125   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
   117126   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
   117127 
   117128   /* If the caller is an UPDATE or DELETE statement that is requesting
   117129   ** to use a one-pass algorithm, determine if this is appropriate.
   117130   ** The one-pass algorithm only works if the WHERE clause constrains
   117131   ** the statement to update a single row.
   117132   */
   117133   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
   117134   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
   117135    && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
   117136     pWInfo->okOnePass = 1;
   117137     if( HasRowid(pTabList->a[0].pTab) ){
   117138       pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
   117139     }
   117140   }
   117141 
   117142   /* Open all tables in the pTabList and any indices selected for
   117143   ** searching those tables.
   117144   */
   117145   notReady = ~(Bitmask)0;
   117146   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
   117147     Table *pTab;     /* Table to open */
   117148     int iDb;         /* Index of database containing table/index */
   117149     struct SrcList_item *pTabItem;
   117150 
   117151     pTabItem = &pTabList->a[pLevel->iFrom];
   117152     pTab = pTabItem->pTab;
   117153     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   117154     pLoop = pLevel->pWLoop;
   117155     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
   117156       /* Do nothing */
   117157     }else
   117158 #ifndef SQLITE_OMIT_VIRTUALTABLE
   117159     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   117160       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   117161       int iCur = pTabItem->iCursor;
   117162       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
   117163     }else if( IsVirtual(pTab) ){
   117164       /* noop */
   117165     }else
   117166 #endif
   117167     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
   117168          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
   117169       int op = OP_OpenRead;
   117170       if( pWInfo->okOnePass ){
   117171         op = OP_OpenWrite;
   117172         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
   117173       };
   117174       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
   117175       assert( pTabItem->iCursor==pLevel->iTabCur );
   117176       testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
   117177       testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
   117178       if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
   117179         Bitmask b = pTabItem->colUsed;
   117180         int n = 0;
   117181         for(; b; b=b>>1, n++){}
   117182         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
   117183                             SQLITE_INT_TO_PTR(n), P4_INT32);
   117184         assert( n<=pTab->nCol );
   117185       }
   117186     }else{
   117187       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   117188     }
   117189     if( pLoop->wsFlags & WHERE_INDEXED ){
   117190       Index *pIx = pLoop->u.btree.pIndex;
   117191       int iIndexCur;
   117192       int op = OP_OpenRead;
   117193       /* iIdxCur is always set if to a positive value if ONEPASS is possible */
   117194       assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
   117195       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
   117196        && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
   117197       ){
   117198         /* This is one term of an OR-optimization using the PRIMARY KEY of a
   117199         ** WITHOUT ROWID table.  No need for a separate index */
   117200         iIndexCur = pLevel->iTabCur;
   117201         op = 0;
   117202       }else if( pWInfo->okOnePass ){
   117203         Index *pJ = pTabItem->pTab->pIndex;
   117204         iIndexCur = iIdxCur;
   117205         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
   117206         while( ALWAYS(pJ) && pJ!=pIx ){
   117207           iIndexCur++;
   117208           pJ = pJ->pNext;
   117209         }
   117210         op = OP_OpenWrite;
   117211         pWInfo->aiCurOnePass[1] = iIndexCur;
   117212       }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
   117213         iIndexCur = iIdxCur;
   117214         if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
   117215       }else{
   117216         iIndexCur = pParse->nTab++;
   117217       }
   117218       pLevel->iIdxCur = iIndexCur;
   117219       assert( pIx->pSchema==pTab->pSchema );
   117220       assert( iIndexCur>=0 );
   117221       if( op ){
   117222         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
   117223         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
   117224         VdbeComment((v, "%s", pIx->zName));
   117225       }
   117226     }
   117227     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
   117228     notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
   117229   }
   117230   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
   117231   if( db->mallocFailed ) goto whereBeginError;
   117232 
   117233   /* Generate the code to do the search.  Each iteration of the for
   117234   ** loop below generates code for a single nested loop of the VM
   117235   ** program.
   117236   */
   117237   notReady = ~(Bitmask)0;
   117238   for(ii=0; ii<nTabList; ii++){
   117239     pLevel = &pWInfo->a[ii];
   117240 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   117241     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
   117242       constructAutomaticIndex(pParse, &pWInfo->sWC,
   117243                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
   117244       if( db->mallocFailed ) goto whereBeginError;
   117245     }
   117246 #endif
   117247     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
   117248     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
   117249     notReady = codeOneLoopStart(pWInfo, ii, notReady);
   117250     pWInfo->iContinue = pLevel->addrCont;
   117251   }
   117252 
   117253   /* Done. */
   117254   VdbeModuleComment((v, "Begin WHERE-core"));
   117255   return pWInfo;
   117256 
   117257   /* Jump here if malloc fails */
   117258 whereBeginError:
   117259   if( pWInfo ){
   117260     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   117261     whereInfoFree(db, pWInfo);
   117262   }
   117263   return 0;
   117264 }
   117265 
   117266 /*
   117267 ** Generate the end of the WHERE loop.  See comments on
   117268 ** sqlite3WhereBegin() for additional information.
   117269 */
   117270 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   117271   Parse *pParse = pWInfo->pParse;
   117272   Vdbe *v = pParse->pVdbe;
   117273   int i;
   117274   WhereLevel *pLevel;
   117275   WhereLoop *pLoop;
   117276   SrcList *pTabList = pWInfo->pTabList;
   117277   sqlite3 *db = pParse->db;
   117278 
   117279   /* Generate loop termination code.
   117280   */
   117281   VdbeModuleComment((v, "End WHERE-core"));
   117282   sqlite3ExprCacheClear(pParse);
   117283   for(i=pWInfo->nLevel-1; i>=0; i--){
   117284     int addr;
   117285     pLevel = &pWInfo->a[i];
   117286     pLoop = pLevel->pWLoop;
   117287     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
   117288     if( pLevel->op!=OP_Noop ){
   117289       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
   117290       sqlite3VdbeChangeP5(v, pLevel->p5);
   117291       VdbeCoverage(v);
   117292       VdbeCoverageIf(v, pLevel->op==OP_Next);
   117293       VdbeCoverageIf(v, pLevel->op==OP_Prev);
   117294       VdbeCoverageIf(v, pLevel->op==OP_VNext);
   117295     }
   117296     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
   117297       struct InLoop *pIn;
   117298       int j;
   117299       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
   117300       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
   117301         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
   117302         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
   117303         VdbeCoverage(v);
   117304         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
   117305         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
   117306         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
   117307       }
   117308       sqlite3DbFree(db, pLevel->u.in.aInLoop);
   117309     }
   117310     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
   117311     if( pLevel->addrSkip ){
   117312       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
   117313       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
   117314       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
   117315       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
   117316     }
   117317     if( pLevel->iLeftJoin ){
   117318       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
   117319       assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
   117320            || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
   117321       if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
   117322         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
   117323       }
   117324       if( pLoop->wsFlags & WHERE_INDEXED ){
   117325         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
   117326       }
   117327       if( pLevel->op==OP_Return ){
   117328         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
   117329       }else{
   117330         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
   117331       }
   117332       sqlite3VdbeJumpHere(v, addr);
   117333     }
   117334     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
   117335                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
   117336   }
   117337 
   117338   /* The "break" point is here, just past the end of the outer loop.
   117339   ** Set it.
   117340   */
   117341   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
   117342 
   117343   assert( pWInfo->nLevel<=pTabList->nSrc );
   117344   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
   117345     int k, last;
   117346     VdbeOp *pOp;
   117347     Index *pIdx = 0;
   117348     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
   117349     Table *pTab = pTabItem->pTab;
   117350     assert( pTab!=0 );
   117351     pLoop = pLevel->pWLoop;
   117352 
   117353     /* For a co-routine, change all OP_Column references to the table of
   117354     ** the co-routine into OP_SCopy of result contained in a register.
   117355     ** OP_Rowid becomes OP_Null.
   117356     */
   117357     if( pTabItem->viaCoroutine && !db->mallocFailed ){
   117358       last = sqlite3VdbeCurrentAddr(v);
   117359       k = pLevel->addrBody;
   117360       pOp = sqlite3VdbeGetOp(v, k);
   117361       for(; k<last; k++, pOp++){
   117362         if( pOp->p1!=pLevel->iTabCur ) continue;
   117363         if( pOp->opcode==OP_Column ){
   117364           pOp->opcode = OP_Copy;
   117365           pOp->p1 = pOp->p2 + pTabItem->regResult;
   117366           pOp->p2 = pOp->p3;
   117367           pOp->p3 = 0;
   117368         }else if( pOp->opcode==OP_Rowid ){
   117369           pOp->opcode = OP_Null;
   117370           pOp->p1 = 0;
   117371           pOp->p3 = 0;
   117372         }
   117373       }
   117374       continue;
   117375     }
   117376 
   117377     /* Close all of the cursors that were opened by sqlite3WhereBegin.
   117378     ** Except, do not close cursors that will be reused by the OR optimization
   117379     ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
   117380     ** created for the ONEPASS optimization.
   117381     */
   117382     if( (pTab->tabFlags & TF_Ephemeral)==0
   117383      && pTab->pSelect==0
   117384      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
   117385     ){
   117386       int ws = pLoop->wsFlags;
   117387       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
   117388         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
   117389       }
   117390       if( (ws & WHERE_INDEXED)!=0
   117391        && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
   117392        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
   117393       ){
   117394         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
   117395       }
   117396     }
   117397 
   117398     /* If this scan uses an index, make VDBE code substitutions to read data
   117399     ** from the index instead of from the table where possible.  In some cases
   117400     ** this optimization prevents the table from ever being read, which can
   117401     ** yield a significant performance boost.
   117402     **
   117403     ** Calls to the code generator in between sqlite3WhereBegin and
   117404     ** sqlite3WhereEnd will have created code that references the table
   117405     ** directly.  This loop scans all that code looking for opcodes
   117406     ** that reference the table and converts them into opcodes that
   117407     ** reference the index.
   117408     */
   117409     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
   117410       pIdx = pLoop->u.btree.pIndex;
   117411     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
   117412       pIdx = pLevel->u.pCovidx;
   117413     }
   117414     if( pIdx && !db->mallocFailed ){
   117415       last = sqlite3VdbeCurrentAddr(v);
   117416       k = pLevel->addrBody;
   117417       pOp = sqlite3VdbeGetOp(v, k);
   117418       for(; k<last; k++, pOp++){
   117419         if( pOp->p1!=pLevel->iTabCur ) continue;
   117420         if( pOp->opcode==OP_Column ){
   117421           int x = pOp->p2;
   117422           assert( pIdx->pTable==pTab );
   117423           if( !HasRowid(pTab) ){
   117424             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   117425             x = pPk->aiColumn[x];
   117426           }
   117427           x = sqlite3ColumnOfIndex(pIdx, x);
   117428           if( x>=0 ){
   117429             pOp->p2 = x;
   117430             pOp->p1 = pLevel->iIdxCur;
   117431           }
   117432           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
   117433         }else if( pOp->opcode==OP_Rowid ){
   117434           pOp->p1 = pLevel->iIdxCur;
   117435           pOp->opcode = OP_IdxRowid;
   117436         }
   117437       }
   117438     }
   117439   }
   117440 
   117441   /* Final cleanup
   117442   */
   117443   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   117444   whereInfoFree(db, pWInfo);
   117445   return;
   117446 }
   117447 
   117448 /************** End of where.c ***********************************************/
   117449 /************** Begin file parse.c *******************************************/
   117450 /* Driver template for the LEMON parser generator.
   117451 ** The author disclaims copyright to this source code.
   117452 **
   117453 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
   117454 ** The only modifications are the addition of a couple of NEVER()
   117455 ** macros to disable tests that are needed in the case of a general
   117456 ** LALR(1) grammar but which are always false in the
   117457 ** specific grammar used by SQLite.
   117458 */
   117459 /* First off, code is included that follows the "include" declaration
   117460 ** in the input grammar file. */
   117461 /* #include <stdio.h> */
   117462 
   117463 
   117464 /*
   117465 ** Disable all error recovery processing in the parser push-down
   117466 ** automaton.
   117467 */
   117468 #define YYNOERRORRECOVERY 1
   117469 
   117470 /*
   117471 ** Make yytestcase() the same as testcase()
   117472 */
   117473 #define yytestcase(X) testcase(X)
   117474 
   117475 /*
   117476 ** An instance of this structure holds information about the
   117477 ** LIMIT clause of a SELECT statement.
   117478 */
   117479 struct LimitVal {
   117480   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
   117481   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
   117482 };
   117483 
   117484 /*
   117485 ** An instance of this structure is used to store the LIKE,
   117486 ** GLOB, NOT LIKE, and NOT GLOB operators.
   117487 */
   117488 struct LikeOp {
   117489   Token eOperator;  /* "like" or "glob" or "regexp" */
   117490   int bNot;         /* True if the NOT keyword is present */
   117491 };
   117492 
   117493 /*
   117494 ** An instance of the following structure describes the event of a
   117495 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
   117496 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
   117497 **
   117498 **      UPDATE ON (a,b,c)
   117499 **
   117500 ** Then the "b" IdList records the list "a,b,c".
   117501 */
   117502 struct TrigEvent { int a; IdList * b; };
   117503 
   117504 /*
   117505 ** An instance of this structure holds the ATTACH key and the key type.
   117506 */
   117507 struct AttachKey { int type;  Token key; };
   117508 
   117509 
   117510   /* This is a utility routine used to set the ExprSpan.zStart and
   117511   ** ExprSpan.zEnd values of pOut so that the span covers the complete
   117512   ** range of text beginning with pStart and going to the end of pEnd.
   117513   */
   117514   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
   117515     pOut->zStart = pStart->z;
   117516     pOut->zEnd = &pEnd->z[pEnd->n];
   117517   }
   117518 
   117519   /* Construct a new Expr object from a single identifier.  Use the
   117520   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
   117521   ** that created the expression.
   117522   */
   117523   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
   117524     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
   117525     pOut->zStart = pValue->z;
   117526     pOut->zEnd = &pValue->z[pValue->n];
   117527   }
   117528 
   117529   /* This routine constructs a binary expression node out of two ExprSpan
   117530   ** objects and uses the result to populate a new ExprSpan object.
   117531   */
   117532   static void spanBinaryExpr(
   117533     ExprSpan *pOut,     /* Write the result here */
   117534     Parse *pParse,      /* The parsing context.  Errors accumulate here */
   117535     int op,             /* The binary operation */
   117536     ExprSpan *pLeft,    /* The left operand */
   117537     ExprSpan *pRight    /* The right operand */
   117538   ){
   117539     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
   117540     pOut->zStart = pLeft->zStart;
   117541     pOut->zEnd = pRight->zEnd;
   117542   }
   117543 
   117544   /* Construct an expression node for a unary postfix operator
   117545   */
   117546   static void spanUnaryPostfix(
   117547     ExprSpan *pOut,        /* Write the new expression node here */
   117548     Parse *pParse,         /* Parsing context to record errors */
   117549     int op,                /* The operator */
   117550     ExprSpan *pOperand,    /* The operand */
   117551     Token *pPostOp         /* The operand token for setting the span */
   117552   ){
   117553     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   117554     pOut->zStart = pOperand->zStart;
   117555     pOut->zEnd = &pPostOp->z[pPostOp->n];
   117556   }
   117557 
   117558   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
   117559   ** unary TK_ISNULL or TK_NOTNULL expression. */
   117560   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
   117561     sqlite3 *db = pParse->db;
   117562     if( db->mallocFailed==0 && pY->op==TK_NULL ){
   117563       pA->op = (u8)op;
   117564       sqlite3ExprDelete(db, pA->pRight);
   117565       pA->pRight = 0;
   117566     }
   117567   }
   117568 
   117569   /* Construct an expression node for a unary prefix operator
   117570   */
   117571   static void spanUnaryPrefix(
   117572     ExprSpan *pOut,        /* Write the new expression node here */
   117573     Parse *pParse,         /* Parsing context to record errors */
   117574     int op,                /* The operator */
   117575     ExprSpan *pOperand,    /* The operand */
   117576     Token *pPreOp         /* The operand token for setting the span */
   117577   ){
   117578     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   117579     pOut->zStart = pPreOp->z;
   117580     pOut->zEnd = pOperand->zEnd;
   117581   }
   117582 /* Next is all token values, in a form suitable for use by makeheaders.
   117583 ** This section will be null unless lemon is run with the -m switch.
   117584 */
   117585 /*
   117586 ** These constants (all generated automatically by the parser generator)
   117587 ** specify the various kinds of tokens (terminals) that the parser
   117588 ** understands.
   117589 **
   117590 ** Each symbol here is a terminal symbol in the grammar.
   117591 */
   117592 /* Make sure the INTERFACE macro is defined.
   117593 */
   117594 #ifndef INTERFACE
   117595 # define INTERFACE 1
   117596 #endif
   117597 /* The next thing included is series of defines which control
   117598 ** various aspects of the generated parser.
   117599 **    YYCODETYPE         is the data type used for storing terminal
   117600 **                       and nonterminal numbers.  "unsigned char" is
   117601 **                       used if there are fewer than 250 terminals
   117602 **                       and nonterminals.  "int" is used otherwise.
   117603 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
   117604 **                       to no legal terminal or nonterminal number.  This
   117605 **                       number is used to fill in empty slots of the hash
   117606 **                       table.
   117607 **    YYFALLBACK         If defined, this indicates that one or more tokens
   117608 **                       have fall-back values which should be used if the
   117609 **                       original value of the token will not parse.
   117610 **    YYACTIONTYPE       is the data type used for storing terminal
   117611 **                       and nonterminal numbers.  "unsigned char" is
   117612 **                       used if there are fewer than 250 rules and
   117613 **                       states combined.  "int" is used otherwise.
   117614 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
   117615 **                       directly to the parser from the tokenizer.
   117616 **    YYMINORTYPE        is the data type used for all minor tokens.
   117617 **                       This is typically a union of many types, one of
   117618 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
   117619 **                       for base tokens is called "yy0".
   117620 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
   117621 **                       zero the stack is dynamically sized using realloc()
   117622 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
   117623 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
   117624 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
   117625 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
   117626 **    YYNSTATE           the combined number of states.
   117627 **    YYNRULE            the number of rules in the grammar
   117628 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
   117629 **                       defined, then do no error processing.
   117630 */
   117631 #define YYCODETYPE unsigned char
   117632 #define YYNOCODE 254
   117633 #define YYACTIONTYPE unsigned short int
   117634 #define YYWILDCARD 70
   117635 #define sqlite3ParserTOKENTYPE Token
   117636 typedef union {
   117637   int yyinit;
   117638   sqlite3ParserTOKENTYPE yy0;
   117639   Select* yy3;
   117640   ExprList* yy14;
   117641   With* yy59;
   117642   SrcList* yy65;
   117643   struct LikeOp yy96;
   117644   Expr* yy132;
   117645   u8 yy186;
   117646   int yy328;
   117647   ExprSpan yy346;
   117648   struct TrigEvent yy378;
   117649   u16 yy381;
   117650   IdList* yy408;
   117651   struct {int value; int mask;} yy429;
   117652   TriggerStep* yy473;
   117653   struct LimitVal yy476;
   117654 } YYMINORTYPE;
   117655 #ifndef YYSTACKDEPTH
   117656 #define YYSTACKDEPTH 100
   117657 #endif
   117658 #define sqlite3ParserARG_SDECL Parse *pParse;
   117659 #define sqlite3ParserARG_PDECL ,Parse *pParse
   117660 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
   117661 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
   117662 #define YYNSTATE 642
   117663 #define YYNRULE 327
   117664 #define YYFALLBACK 1
   117665 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
   117666 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
   117667 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
   117668 
   117669 /* The yyzerominor constant is used to initialize instances of
   117670 ** YYMINORTYPE objects to zero. */
   117671 static const YYMINORTYPE yyzerominor = { 0 };
   117672 
   117673 /* Define the yytestcase() macro to be a no-op if is not already defined
   117674 ** otherwise.
   117675 **
   117676 ** Applications can choose to define yytestcase() in the %include section
   117677 ** to a macro that can assist in verifying code coverage.  For production
   117678 ** code the yytestcase() macro should be turned off.  But it is useful
   117679 ** for testing.
   117680 */
   117681 #ifndef yytestcase
   117682 # define yytestcase(X)
   117683 #endif
   117684 
   117685 
   117686 /* Next are the tables used to determine what action to take based on the
   117687 ** current state and lookahead token.  These tables are used to implement
   117688 ** functions that take a state number and lookahead value and return an
   117689 ** action integer.
   117690 **
   117691 ** Suppose the action integer is N.  Then the action is determined as
   117692 ** follows
   117693 **
   117694 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
   117695 **                                      token onto the stack and goto state N.
   117696 **
   117697 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
   117698 **
   117699 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
   117700 **
   117701 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
   117702 **
   117703 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
   117704 **                                      slots in the yy_action[] table.
   117705 **
   117706 ** The action table is constructed as a single large table named yy_action[].
   117707 ** Given state S and lookahead X, the action is computed as
   117708 **
   117709 **      yy_action[ yy_shift_ofst[S] + X ]
   117710 **
   117711 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
   117712 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
   117713 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
   117714 ** and that yy_default[S] should be used instead.
   117715 **
   117716 ** The formula above is for computing the action when the lookahead is
   117717 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   117718 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
   117719 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
   117720 ** YY_SHIFT_USE_DFLT.
   117721 **
   117722 ** The following are the tables generated in this section:
   117723 **
   117724 **  yy_action[]        A single table containing all actions.
   117725 **  yy_lookahead[]     A table containing the lookahead for each entry in
   117726 **                     yy_action.  Used to detect hash collisions.
   117727 **  yy_shift_ofst[]    For each state, the offset into yy_action for
   117728 **                     shifting terminals.
   117729 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
   117730 **                     shifting non-terminals after a reduce.
   117731 **  yy_default[]       Default action for each state.
   117732 */
   117733 #define YY_ACTTAB_COUNT (1497)
   117734 static const YYACTIONTYPE yy_action[] = {
   117735  /*     0 */   306,  212,  432,  955,  639,  191,  955,  295,  559,   88,
   117736  /*    10 */    88,   88,   88,   81,   86,   86,   86,   86,   85,   85,
   117737  /*    20 */    84,   84,   84,   83,  330,  185,  184,  183,  635,  635,
   117738  /*    30 */   292,  606,  606,   88,   88,   88,   88,  683,   86,   86,
   117739  /*    40 */    86,   86,   85,   85,   84,   84,   84,   83,  330,   16,
   117740  /*    50 */   436,  597,   89,   90,   80,  600,  599,  601,  601,   87,
   117741  /*    60 */    87,   88,   88,   88,   88,  684,   86,   86,   86,   86,
   117742  /*    70 */    85,   85,   84,   84,   84,   83,  330,  306,  559,   84,
   117743  /*    80 */    84,   84,   83,  330,   65,   86,   86,   86,   86,   85,
   117744  /*    90 */    85,   84,   84,   84,   83,  330,  635,  635,  634,  633,
   117745  /*   100 */   182,  682,  550,  379,  376,  375,   17,  322,  606,  606,
   117746  /*   110 */   371,  198,  479,   91,  374,   82,   79,  165,   85,   85,
   117747  /*   120 */    84,   84,   84,   83,  330,  598,  635,  635,  107,   89,
   117748  /*   130 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
   117749  /*   140 */    88,   88,  186,   86,   86,   86,   86,   85,   85,   84,
   117750  /*   150 */    84,   84,   83,  330,  306,  594,  594,  142,  328,  327,
   117751  /*   160 */   484,  249,  344,  238,  635,  635,  634,  633,  585,  448,
   117752  /*   170 */   526,  525,  229,  388,    1,  394,  450,  584,  449,  635,
   117753  /*   180 */   635,  635,  635,  319,  395,  606,  606,  199,  157,  273,
   117754  /*   190 */   382,  268,  381,  187,  635,  635,  634,  633,  311,  555,
   117755  /*   200 */   266,  593,  593,  266,  347,  588,   89,   90,   80,  600,
   117756  /*   210 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  478,
   117757  /*   220 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
   117758  /*   230 */   330,  306,  272,  536,  634,  633,  146,  610,  197,  310,
   117759  /*   240 */   575,  182,  482,  271,  379,  376,  375,  506,   21,  634,
   117760  /*   250 */   633,  634,  633,  635,  635,  374,  611,  574,  548,  440,
   117761  /*   260 */   111,  563,  606,  606,  634,  633,  324,  479,  608,  608,
   117762  /*   270 */   608,  300,  435,  573,  119,  407,  210,  162,  562,  883,
   117763  /*   280 */   592,  592,  306,   89,   90,   80,  600,  599,  601,  601,
   117764  /*   290 */    87,   87,   88,   88,   88,   88,  506,   86,   86,   86,
   117765  /*   300 */    86,   85,   85,   84,   84,   84,   83,  330,  620,  111,
   117766  /*   310 */   635,  635,  361,  606,  606,  358,  249,  349,  248,  433,
   117767  /*   320 */   243,  479,  586,  634,  633,  195,  611,   93,  119,  221,
   117768  /*   330 */   575,  497,  534,  534,   89,   90,   80,  600,  599,  601,
   117769  /*   340 */   601,   87,   87,   88,   88,   88,   88,  574,   86,   86,
   117770  /*   350 */    86,   86,   85,   85,   84,   84,   84,   83,  330,  306,
   117771  /*   360 */    77,  429,  638,  573,  589,  530,  240,  230,  242,  105,
   117772  /*   370 */   249,  349,  248,  515,  588,  208,  460,  529,  564,  173,
   117773  /*   380 */   634,  633,  970,  144,  430,    2,  424,  228,  380,  557,
   117774  /*   390 */   606,  606,  190,  153,  159,  158,  514,   51,  632,  631,
   117775  /*   400 */   630,   71,  536,  432,  954,  196,  610,  954,  614,   45,
   117776  /*   410 */    18,   89,   90,   80,  600,  599,  601,  601,   87,   87,
   117777  /*   420 */    88,   88,   88,   88,  261,   86,   86,   86,   86,   85,
   117778  /*   430 */    85,   84,   84,   84,   83,  330,  306,  608,  608,  608,
   117779  /*   440 */   542,  424,  402,  385,  241,  506,  451,  320,  211,  543,
   117780  /*   450 */   164,  436,  386,  293,  451,  587,  108,  496,  111,  334,
   117781  /*   460 */   391,  591,  424,  614,   27,  452,  453,  606,  606,   72,
   117782  /*   470 */   257,   70,  259,  452,  339,  342,  564,  582,   68,  415,
   117783  /*   480 */   469,  328,  327,   62,  614,   45,  110,  393,   89,   90,
   117784  /*   490 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
   117785  /*   500 */    88,  152,   86,   86,   86,   86,   85,   85,   84,   84,
   117786  /*   510 */    84,   83,  330,  306,  110,  499,  520,  538,  402,  389,
   117787  /*   520 */   424,  110,  566,  500,  593,  593,  454,   82,   79,  165,
   117788  /*   530 */   424,  591,  384,  564,  340,  615,  188,  162,  424,  350,
   117789  /*   540 */   616,  424,  614,   44,  606,  606,  445,  582,  300,  434,
   117790  /*   550 */   151,   19,  614,    9,  568,  580,  348,  615,  469,  567,
   117791  /*   560 */   614,   26,  616,  614,   45,   89,   90,   80,  600,  599,
   117792  /*   570 */   601,  601,   87,   87,   88,   88,   88,   88,  411,   86,
   117793  /*   580 */    86,   86,   86,   85,   85,   84,   84,   84,   83,  330,
   117794  /*   590 */   306,  579,  110,  578,  521,  282,  433,  398,  400,  255,
   117795  /*   600 */   486,   82,   79,  165,  487,  164,   82,   79,  165,  488,
   117796  /*   610 */   488,  364,  387,  424,  544,  544,  509,  350,  362,  155,
   117797  /*   620 */   191,  606,  606,  559,  642,  640,  333,   82,   79,  165,
   117798  /*   630 */   305,  564,  507,  312,  357,  614,   45,  329,  596,  595,
   117799  /*   640 */   194,  337,   89,   90,   80,  600,  599,  601,  601,   87,
   117800  /*   650 */    87,   88,   88,   88,   88,  424,   86,   86,   86,   86,
   117801  /*   660 */    85,   85,   84,   84,   84,   83,  330,  306,   20,  323,
   117802  /*   670 */   150,  263,  211,  543,  421,  596,  595,  614,   22,  424,
   117803  /*   680 */   193,  424,  284,  424,  391,  424,  509,  424,  577,  424,
   117804  /*   690 */   186,  335,  424,  559,  424,  313,  120,  546,  606,  606,
   117805  /*   700 */    67,  614,   47,  614,   50,  614,   48,  614,  100,  614,
   117806  /*   710 */    99,  614,  101,  576,  614,  102,  614,  109,  326,   89,
   117807  /*   720 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
   117808  /*   730 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
   117809  /*   740 */    84,   84,   83,  330,  306,  424,  311,  424,  585,   54,
   117810  /*   750 */   424,  516,  517,  590,  614,  112,  424,  584,  424,  572,
   117811  /*   760 */   424,  195,  424,  571,  424,   67,  424,  614,   94,  614,
   117812  /*   770 */    98,  424,  614,   97,  264,  606,  606,  195,  614,   46,
   117813  /*   780 */   614,   96,  614,   30,  614,   49,  614,  115,  614,  114,
   117814  /*   790 */   418,  229,  388,  614,  113,  306,   89,   90,   80,  600,
   117815  /*   800 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  424,
   117816  /*   810 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
   117817  /*   820 */   330,  119,  424,  590,  110,  372,  606,  606,  195,   53,
   117818  /*   830 */   250,  614,   29,  195,  472,  438,  729,  190,  302,  498,
   117819  /*   840 */    14,  523,  641,    2,  614,   43,  306,   89,   90,   80,
   117820  /*   850 */   600,  599,  601,  601,   87,   87,   88,   88,   88,   88,
   117821  /*   860 */   424,   86,   86,   86,   86,   85,   85,   84,   84,   84,
   117822  /*   870 */    83,  330,  424,  613,  964,  964,  354,  606,  606,  420,
   117823  /*   880 */   312,   64,  614,   42,  391,  355,  283,  437,  301,  255,
   117824  /*   890 */   414,  410,  495,  492,  614,   28,  471,  306,   89,   90,
   117825  /*   900 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
   117826  /*   910 */    88,  424,   86,   86,   86,   86,   85,   85,   84,   84,
   117827  /*   920 */    84,   83,  330,  424,  110,  110,  110,  110,  606,  606,
   117828  /*   930 */   110,  254,   13,  614,   41,  532,  531,  283,  481,  531,
   117829  /*   940 */   457,  284,  119,  561,  356,  614,   40,  284,  306,   89,
   117830  /*   950 */    78,   80,  600,  599,  601,  601,   87,   87,   88,   88,
   117831  /*   960 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
   117832  /*   970 */    84,   84,   83,  330,  110,  424,  341,  220,  555,  606,
   117833  /*   980 */   606,  351,  555,  318,  614,   95,  413,  255,   83,  330,
   117834  /*   990 */   284,  284,  255,  640,  333,  356,  255,  614,   39,  306,
   117835  /*  1000 */   356,   90,   80,  600,  599,  601,  601,   87,   87,   88,
   117836  /*  1010 */    88,   88,   88,  424,   86,   86,   86,   86,   85,   85,
   117837  /*  1020 */    84,   84,   84,   83,  330,  424,  317,  316,  141,  465,
   117838  /*  1030 */   606,  606,  219,  619,  463,  614,   10,  417,  462,  255,
   117839  /*  1040 */   189,  510,  553,  351,  207,  363,  161,  614,   38,  315,
   117840  /*  1050 */   218,  255,  255,   80,  600,  599,  601,  601,   87,   87,
   117841  /*  1060 */    88,   88,   88,   88,  424,   86,   86,   86,   86,   85,
   117842  /*  1070 */    85,   84,   84,   84,   83,  330,   76,  419,  255,    3,
   117843  /*  1080 */   878,  461,  424,  247,  331,  331,  614,   37,  217,   76,
   117844  /*  1090 */   419,  390,    3,  216,  215,  422,    4,  331,  331,  424,
   117845  /*  1100 */   547,   12,  424,  545,  614,   36,  424,  541,  422,  424,
   117846  /*  1110 */   540,  424,  214,  424,  408,  424,  539,  403,  605,  605,
   117847  /*  1120 */   237,  614,   25,  119,  614,   24,  588,  408,  614,   45,
   117848  /*  1130 */   118,  614,   35,  614,   34,  614,   33,  614,   23,  588,
   117849  /*  1140 */    60,  223,  603,  602,  513,  378,   73,   74,  140,  139,
   117850  /*  1150 */   424,  110,  265,   75,  426,  425,   59,  424,  610,   73,
   117851  /*  1160 */    74,  549,  402,  404,  424,  373,   75,  426,  425,  604,
   117852  /*  1170 */   138,  610,  614,   11,  392,   76,  419,  181,    3,  614,
   117853  /*  1180 */    32,  271,  369,  331,  331,  493,  614,   31,  149,  608,
   117854  /*  1190 */   608,  608,  607,   15,  422,  365,  614,    8,  137,  489,
   117855  /*  1200 */   136,  190,  608,  608,  608,  607,   15,  485,  176,  135,
   117856  /*  1210 */     7,  252,  477,  408,  174,  133,  175,  474,   57,   56,
   117857  /*  1220 */   132,  130,  119,   76,  419,  588,    3,  468,  245,  464,
   117858  /*  1230 */   171,  331,  331,  125,  123,  456,  447,  122,  446,  104,
   117859  /*  1240 */   336,  231,  422,  166,  154,   73,   74,  332,  116,  431,
   117860  /*  1250 */   121,  309,   75,  426,  425,  222,  106,  610,  308,  637,
   117861  /*  1260 */   204,  408,  629,  627,  628,    6,  200,  428,  427,  290,
   117862  /*  1270 */   203,  622,  201,  588,   62,   63,  289,   66,  419,  399,
   117863  /*  1280 */     3,  401,  288,   92,  143,  331,  331,  287,  608,  608,
   117864  /*  1290 */   608,  607,   15,   73,   74,  227,  422,  325,   69,  416,
   117865  /*  1300 */    75,  426,  425,  612,  412,  610,  192,   61,  569,  209,
   117866  /*  1310 */   396,  226,  278,  225,  383,  408,  527,  558,  276,  533,
   117867  /*  1320 */   552,  528,  321,  523,  370,  508,  180,  588,  494,  179,
   117868  /*  1330 */   366,  117,  253,  269,  522,  503,  608,  608,  608,  607,
   117869  /*  1340 */    15,  551,  502,   58,  274,  524,  178,   73,   74,  304,
   117870  /*  1350 */   501,  368,  303,  206,   75,  426,  425,  491,  360,  610,
   117871  /*  1360 */   213,  177,  483,  131,  345,  298,  297,  296,  202,  294,
   117872  /*  1370 */   480,  490,  466,  134,  172,  129,  444,  346,  470,  128,
   117873  /*  1380 */   314,  459,  103,  127,  126,  148,  124,  167,  443,  235,
   117874  /*  1390 */   608,  608,  608,  607,   15,  442,  439,  623,  234,  299,
   117875  /*  1400 */   145,  583,  291,  377,  581,  160,  119,  156,  270,  636,
   117876  /*  1410 */   971,  169,  279,  626,  520,  625,  473,  624,  170,  621,
   117877  /*  1420 */   618,  119,  168,   55,  409,  423,  537,  609,  286,  285,
   117878  /*  1430 */   405,  570,  560,  556,    5,   52,  458,  554,  147,  267,
   117879  /*  1440 */   519,  504,  518,  406,  262,  239,  260,  512,  343,  511,
   117880  /*  1450 */   258,  353,  565,  256,  224,  251,  359,  277,  275,  476,
   117881  /*  1460 */   475,  246,  352,  244,  467,  455,  236,  233,  232,  307,
   117882  /*  1470 */   441,  281,  205,  163,  397,  280,  535,  505,  330,  617,
   117883  /*  1480 */   971,  971,  971,  971,  367,  971,  971,  971,  971,  971,
   117884  /*  1490 */   971,  971,  971,  971,  971,  971,  338,
   117885 };
   117886 static const YYCODETYPE yy_lookahead[] = {
   117887  /*     0 */    19,   22,   22,   23,    1,   24,   26,   15,   27,   80,
   117888  /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   117889  /*    20 */    91,   92,   93,   94,   95,  108,  109,  110,   27,   28,
   117890  /*    30 */    23,   50,   51,   80,   81,   82,   83,  122,   85,   86,
   117891  /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   22,
   117892  /*    50 */    70,   23,   71,   72,   73,   74,   75,   76,   77,   78,
   117893  /*    60 */    79,   80,   81,   82,   83,  122,   85,   86,   87,   88,
   117894  /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   91,
   117895  /*    80 */    92,   93,   94,   95,   26,   85,   86,   87,   88,   89,
   117896  /*    90 */    90,   91,   92,   93,   94,   95,   27,   28,   97,   98,
   117897  /*   100 */    99,  122,  211,  102,  103,  104,   79,   19,   50,   51,
   117898  /*   110 */    19,  122,   59,   55,  113,  224,  225,  226,   89,   90,
   117899  /*   120 */    91,   92,   93,   94,   95,   23,   27,   28,   26,   71,
   117900  /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
   117901  /*   140 */    82,   83,   51,   85,   86,   87,   88,   89,   90,   91,
   117902  /*   150 */    92,   93,   94,   95,   19,  132,  133,   58,   89,   90,
   117903  /*   160 */    21,  108,  109,  110,   27,   28,   97,   98,   33,  100,
   117904  /*   170 */     7,    8,  119,  120,   22,   19,  107,   42,  109,   27,
   117905  /*   180 */    28,   27,   28,   95,   28,   50,   51,   99,  100,  101,
   117906  /*   190 */   102,  103,  104,  105,   27,   28,   97,   98,  107,  152,
   117907  /*   200 */   112,  132,  133,  112,   65,   69,   71,   72,   73,   74,
   117908  /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   11,
   117909  /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
   117910  /*   230 */    95,   19,  101,   97,   97,   98,   24,  101,  122,  157,
   117911  /*   240 */    12,   99,  103,  112,  102,  103,  104,  152,   22,   97,
   117912  /*   250 */    98,   97,   98,   27,   28,  113,   27,   29,   91,  164,
   117913  /*   260 */   165,  124,   50,   51,   97,   98,  219,   59,  132,  133,
   117914  /*   270 */   134,   22,   23,   45,   66,   47,  212,  213,  124,  140,
   117915  /*   280 */   132,  133,   19,   71,   72,   73,   74,   75,   76,   77,
   117916  /*   290 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
   117917  /*   300 */    88,   89,   90,   91,   92,   93,   94,   95,  164,  165,
   117918  /*   310 */    27,   28,  230,   50,   51,  233,  108,  109,  110,   70,
   117919  /*   320 */    16,   59,   23,   97,   98,   26,   97,   22,   66,  185,
   117920  /*   330 */    12,  187,   27,   28,   71,   72,   73,   74,   75,   76,
   117921  /*   340 */    77,   78,   79,   80,   81,   82,   83,   29,   85,   86,
   117922  /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
   117923  /*   360 */    22,  148,  149,   45,   23,   47,   62,  154,   64,  156,
   117924  /*   370 */   108,  109,  110,   37,   69,   23,  163,   59,   26,   26,
   117925  /*   380 */    97,   98,  144,  145,  146,  147,  152,  200,   52,   23,
   117926  /*   390 */    50,   51,   26,   22,   89,   90,   60,  210,    7,    8,
   117927  /*   400 */     9,  138,   97,   22,   23,   26,  101,   26,  174,  175,
   117928  /*   410 */   197,   71,   72,   73,   74,   75,   76,   77,   78,   79,
   117929  /*   420 */    80,   81,   82,   83,   16,   85,   86,   87,   88,   89,
   117930  /*   430 */    90,   91,   92,   93,   94,   95,   19,  132,  133,  134,
   117931  /*   440 */    23,  152,  208,  209,  140,  152,  152,  111,  195,  196,
   117932  /*   450 */    98,   70,  163,  160,  152,   23,   22,  164,  165,  246,
   117933  /*   460 */   207,   27,  152,  174,  175,  171,  172,   50,   51,  137,
   117934  /*   470 */    62,  139,   64,  171,  172,  222,  124,   27,  138,   24,
   117935  /*   480 */   163,   89,   90,  130,  174,  175,  197,  163,   71,   72,
   117936  /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
   117937  /*   500 */    83,   22,   85,   86,   87,   88,   89,   90,   91,   92,
   117938  /*   510 */    93,   94,   95,   19,  197,  181,  182,   23,  208,  209,
   117939  /*   520 */   152,  197,   26,  189,  132,  133,  232,  224,  225,  226,
   117940  /*   530 */   152,   97,   91,   26,  232,  116,  212,  213,  152,  222,
   117941  /*   540 */   121,  152,  174,  175,   50,   51,  243,   97,   22,   23,
   117942  /*   550 */    22,  234,  174,  175,  177,   23,  239,  116,  163,  177,
   117943  /*   560 */   174,  175,  121,  174,  175,   71,   72,   73,   74,   75,
   117944  /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,   24,   85,
   117945  /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
   117946  /*   590 */    19,   23,  197,   11,   23,  227,   70,  208,  220,  152,
   117947  /*   600 */    31,  224,  225,  226,   35,   98,  224,  225,  226,  108,
   117948  /*   610 */   109,  110,  115,  152,  117,  118,   27,  222,   49,  123,
   117949  /*   620 */    24,   50,   51,   27,    0,    1,    2,  224,  225,  226,
   117950  /*   630 */   166,  124,  168,  169,  239,  174,  175,  170,  171,  172,
   117951  /*   640 */    22,  194,   71,   72,   73,   74,   75,   76,   77,   78,
   117952  /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
   117953  /*   660 */    89,   90,   91,   92,   93,   94,   95,   19,   22,  208,
   117954  /*   670 */    24,   23,  195,  196,  170,  171,  172,  174,  175,  152,
   117955  /*   680 */    26,  152,  152,  152,  207,  152,   97,  152,   23,  152,
   117956  /*   690 */    51,  244,  152,   97,  152,  247,  248,   23,   50,   51,
   117957  /*   700 */    26,  174,  175,  174,  175,  174,  175,  174,  175,  174,
   117958  /*   710 */   175,  174,  175,   23,  174,  175,  174,  175,  188,   71,
   117959  /*   720 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
   117960  /*   730 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
   117961  /*   740 */    92,   93,   94,   95,   19,  152,  107,  152,   33,   24,
   117962  /*   750 */   152,  100,  101,   27,  174,  175,  152,   42,  152,   23,
   117963  /*   760 */   152,   26,  152,   23,  152,   26,  152,  174,  175,  174,
   117964  /*   770 */   175,  152,  174,  175,   23,   50,   51,   26,  174,  175,
   117965  /*   780 */   174,  175,  174,  175,  174,  175,  174,  175,  174,  175,
   117966  /*   790 */   163,  119,  120,  174,  175,   19,   71,   72,   73,   74,
   117967  /*   800 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  152,
   117968  /*   810 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
   117969  /*   820 */    95,   66,  152,   97,  197,   23,   50,   51,   26,   53,
   117970  /*   830 */    23,  174,  175,   26,   23,   23,   23,   26,   26,   26,
   117971  /*   840 */    36,  106,  146,  147,  174,  175,   19,   71,   72,   73,
   117972  /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
   117973  /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
   117974  /*   870 */    94,   95,  152,  196,  119,  120,   19,   50,   51,  168,
   117975  /*   880 */   169,   26,  174,  175,  207,   28,  152,  249,  250,  152,
   117976  /*   890 */   163,  163,  163,  163,  174,  175,  163,   19,   71,   72,
   117977  /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
   117978  /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
   117979  /*   920 */    93,   94,   95,  152,  197,  197,  197,  197,   50,   51,
   117980  /*   930 */   197,  194,   36,  174,  175,  191,  192,  152,  191,  192,
   117981  /*   940 */   163,  152,   66,  124,  152,  174,  175,  152,   19,   71,
   117982  /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
   117983  /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
   117984  /*   970 */    92,   93,   94,   95,  197,  152,  100,  188,  152,   50,
   117985  /*   980 */    51,  152,  152,  188,  174,  175,  252,  152,   94,   95,
   117986  /*   990 */   152,  152,  152,    1,    2,  152,  152,  174,  175,   19,
   117987  /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   117988  /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
   117989  /*  1020 */    91,   92,   93,   94,   95,  152,  188,  188,   22,  194,
   117990  /*  1030 */    50,   51,  240,  173,  194,  174,  175,  252,  194,  152,
   117991  /*  1040 */    36,  181,   28,  152,   23,  219,  122,  174,  175,  219,
   117992  /*  1050 */   221,  152,  152,   73,   74,   75,   76,   77,   78,   79,
   117993  /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
   117994  /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,  152,   22,
   117995  /*  1080 */    23,  194,  152,  240,   27,   28,  174,  175,  240,   19,
   117996  /*  1090 */    20,   26,   22,  194,  194,   38,   22,   27,   28,  152,
   117997  /*  1100 */    23,   22,  152,  116,  174,  175,  152,   23,   38,  152,
   117998  /*  1110 */    23,  152,  221,  152,   57,  152,   23,  163,   50,   51,
   117999  /*  1120 */   194,  174,  175,   66,  174,  175,   69,   57,  174,  175,
   118000  /*  1130 */    40,  174,  175,  174,  175,  174,  175,  174,  175,   69,
   118001  /*  1140 */    22,   53,   74,   75,   30,   53,   89,   90,   22,   22,
   118002  /*  1150 */   152,  197,   23,   96,   97,   98,   22,  152,  101,   89,
   118003  /*  1160 */    90,   91,  208,  209,  152,   53,   96,   97,   98,  101,
   118004  /*  1170 */    22,  101,  174,  175,  152,   19,   20,  105,   22,  174,
   118005  /*  1180 */   175,  112,   19,   27,   28,   20,  174,  175,   24,  132,
   118006  /*  1190 */   133,  134,  135,  136,   38,   44,  174,  175,  107,   61,
   118007  /*  1200 */    54,   26,  132,  133,  134,  135,  136,   54,  107,   22,
   118008  /*  1210 */     5,  140,    1,   57,   36,  111,  122,   28,   79,   79,
   118009  /*  1220 */   131,  123,   66,   19,   20,   69,   22,    1,   16,   20,
   118010  /*  1230 */   125,   27,   28,  123,  111,  120,   23,  131,   23,   16,
   118011  /*  1240 */    68,  142,   38,   15,   22,   89,   90,    3,  167,    4,
   118012  /*  1250 */   248,  251,   96,   97,   98,  180,  180,  101,  251,  151,
   118013  /*  1260 */     6,   57,  151,   13,  151,   26,   25,  151,  161,  202,
   118014  /*  1270 */   153,  162,  153,   69,  130,  128,  203,   19,   20,  127,
   118015  /*  1280 */    22,  126,  204,  129,   22,   27,   28,  205,  132,  133,
   118016  /*  1290 */   134,  135,  136,   89,   90,  231,   38,   95,  137,  179,
   118017  /*  1300 */    96,   97,   98,  206,  179,  101,  122,  107,  159,  159,
   118018  /*  1310 */   125,  231,  216,  228,  107,   57,  184,  217,  216,  176,
   118019  /*  1320 */   217,  176,   48,  106,   18,  184,  158,   69,  159,  158,
   118020  /*  1330 */    46,   71,  237,  176,  176,  176,  132,  133,  134,  135,
   118021  /*  1340 */   136,  217,  176,  137,  216,  178,  158,   89,   90,  179,
   118022  /*  1350 */   176,  159,  179,  159,   96,   97,   98,  159,  159,  101,
   118023  /*  1360 */     5,  158,  202,   22,   18,   10,   11,   12,   13,   14,
   118024  /*  1370 */   190,  238,   17,  190,  158,  193,   41,  159,  202,  193,
   118025  /*  1380 */   159,  202,  245,  193,  193,  223,  190,   32,  159,   34,
   118026  /*  1390 */   132,  133,  134,  135,  136,  159,   39,  155,   43,  150,
   118027  /*  1400 */   223,  177,  201,  178,  177,  186,   66,  199,  177,  152,
   118028  /*  1410 */   253,   56,  215,  152,  182,  152,  202,  152,   63,  152,
   118029  /*  1420 */   152,   66,   67,  242,  229,  152,  174,  152,  152,  152,
   118030  /*  1430 */   152,  152,  152,  152,  199,  242,  202,  152,  198,  152,
   118031  /*  1440 */   152,  152,  183,  192,  152,  215,  152,  183,  215,  183,
   118032  /*  1450 */   152,  241,  214,  152,  211,  152,  152,  211,  211,  152,
   118033  /*  1460 */   152,  241,  152,  152,  152,  152,  152,  152,  152,  114,
   118034  /*  1470 */   152,  152,  235,  152,  152,  152,  174,  187,   95,  174,
   118035  /*  1480 */   253,  253,  253,  253,  236,  253,  253,  253,  253,  253,
   118036  /*  1490 */   253,  253,  253,  253,  253,  253,  141,
   118037 };
   118038 #define YY_SHIFT_USE_DFLT (-86)
   118039 #define YY_SHIFT_COUNT (429)
   118040 #define YY_SHIFT_MIN   (-85)
   118041 #define YY_SHIFT_MAX   (1383)
   118042 static const short yy_shift_ofst[] = {
   118043  /*     0 */   992, 1057, 1355, 1156, 1204, 1204,    1,  262,  -19,  135,
   118044  /*    10 */   135,  776, 1204, 1204, 1204, 1204,   69,   69,   53,  208,
   118045  /*    20 */   283,  755,   58,  725,  648,  571,  494,  417,  340,  263,
   118046  /*    30 */   212,  827,  827,  827,  827,  827,  827,  827,  827,  827,
   118047  /*    40 */   827,  827,  827,  827,  827,  827,  878,  827,  929,  980,
   118048  /*    50 */   980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
   118049  /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
   118050  /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
   118051  /*    80 */  1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
   118052  /*    90 */  1204, 1204, 1204, 1204,  -71,  -47,  -47,  -47,  -47,  -47,
   118053  /*   100 */     0,   29,  -12,  283,  283,  139,   91,  392,  392,  894,
   118054  /*   110 */   672,  726, 1383,  -86,  -86,  -86,   88,  318,  318,   99,
   118055  /*   120 */   381,  -20,  283,  283,  283,  283,  283,  283,  283,  283,
   118056  /*   130 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
   118057  /*   140 */   283,  283,  283,  283,  624,  876,  726,  672, 1340, 1340,
   118058  /*   150 */  1340, 1340, 1340, 1340,  -86,  -86,  -86,  305,  136,  136,
   118059  /*   160 */   142,  167,  226,  154,  137,  152,  283,  283,  283,  283,
   118060  /*   170 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
   118061  /*   180 */   283,  283,  283,  336,  336,  336,  283,  283,  352,  283,
   118062  /*   190 */   283,  283,  283,  283,  228,  283,  283,  283,  283,  283,
   118063  /*   200 */   283,  283,  283,  283,  283,  501,  569,  596,  596,  596,
   118064  /*   210 */   507,  497,  441,  391,  353,  156,  156,  857,  353,  857,
   118065  /*   220 */   735,  813,  639,  715,  156,  332,  715,  715,  496,  419,
   118066  /*   230 */   646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
   118067  /*   240 */  1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
   118068  /*   250 */  1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
   118069  /*   260 */  1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
   118070  /*   270 */  1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
   118071  /*   280 */  1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
   118072  /*   290 */  1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
   118073  /*   300 */   -86,  -86,  -86,  -86,  -86,  -86, 1068,  304,  526,  249,
   118074  /*   310 */   408,  -83,  434,  812,   27,  811,  807,  802,  751,  589,
   118075  /*   320 */   651,  163,  131,  674,  366,  450,  299,  148,   23,  102,
   118076  /*   330 */   229,  -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
   118077  /*   340 */  1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
   118078  /*   350 */  1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
   118079  /*   360 */  1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
   118080  /*   370 */  1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
   118081  /*   380 */  1114, 1118, 1088, 1090, 1093, 1087, 1084,  987, 1079, 1077,
   118082  /*   390 */  1074, 1065,  924, 1021, 1014, 1004, 1006,  819,  739,  896,
   118083  /*   400 */   855,  804,  739,  740,  736,  690,  654,  665,  618,  582,
   118084  /*   410 */   568,  528,  554,  379,  532,  479,  455,  379,  432,  371,
   118085  /*   420 */   341,   28,  338,  116,  -11,  -57,  -85,    7,   -8,    3,
   118086 };
   118087 #define YY_REDUCE_USE_DFLT (-110)
   118088 #define YY_REDUCE_COUNT (305)
   118089 #define YY_REDUCE_MIN   (-109)
   118090 #define YY_REDUCE_MAX   (1323)
   118091 static const short yy_reduce_ofst[] = {
   118092  /*     0 */   238,  954,  213,  289,  310,  234,  144,  317, -109,  382,
   118093  /*    10 */   377,  303,  461,  389,  378,  368,  302,  294,  253,  395,
   118094  /*    20 */   293,  324,  403,  403,  403,  403,  403,  403,  403,  403,
   118095  /*    30 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
   118096  /*    40 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
   118097  /*    50 */   403, 1022, 1012, 1005,  998,  963,  961,  959,  957,  950,
   118098  /*    60 */   947,  930,  912,  873,  861,  823,  810,  771,  759,  720,
   118099  /*    70 */   708,  670,  657,  619,  614,  612,  610,  608,  606,  604,
   118100  /*    80 */   598,  595,  593,  580,  542,  540,  537,  535,  533,  531,
   118101  /*    90 */   529,  527,  503,  386,  403,  403,  403,  403,  403,  403,
   118102  /*   100 */   403,  403,  403,   95,  447,   82,  334,  504,  467,  403,
   118103  /*   110 */   477,  464,  403,  403,  403,  403,  860,  747,  744,  785,
   118104  /*   120 */   638,  638,  926,  891,  900,  899,  887,  844,  840,  835,
   118105  /*   130 */   848,  830,  843,  829,  792,  839,  826,  737,  838,  795,
   118106  /*   140 */   789,   47,  734,  530,  696,  777,  711,  677,  733,  730,
   118107  /*   150 */   729,  728,  727,  627,  448,   64,  187, 1305, 1302, 1252,
   118108  /*   160 */  1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
   118109  /*   170 */  1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
   118110  /*   180 */  1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
   118111  /*   190 */  1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
   118112  /*   200 */  1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
   118113  /*   210 */  1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
   118114  /*   220 */  1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
   118115  /*   230 */  1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
   118116  /*   240 */  1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
   118117  /*   250 */  1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
   118118  /*   260 */  1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
   118119  /*   270 */  1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
   118120  /*   280 */  1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
   118121  /*   290 */  1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
   118122  /*   300 */  1007, 1000, 1002, 1076, 1075, 1081,
   118123 };
   118124 static const YYACTIONTYPE yy_default[] = {
   118125  /*     0 */   647,  964,  964,  964,  878,  878,  969,  964,  774,  802,
   118126  /*    10 */   802,  938,  969,  969,  969,  876,  969,  969,  969,  964,
   118127  /*    20 */   969,  778,  808,  969,  969,  969,  969,  969,  969,  969,
   118128  /*    30 */   969,  937,  939,  816,  815,  918,  789,  813,  806,  810,
   118129  /*    40 */   879,  872,  873,  871,  875,  880,  969,  809,  841,  856,
   118130  /*    50 */   840,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118131  /*    60 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118132  /*    70 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118133  /*    80 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118134  /*    90 */   969,  969,  969,  969,  850,  855,  862,  854,  851,  843,
   118135  /*   100 */   842,  844,  845,  969,  969,  673,  739,  969,  969,  846,
   118136  /*   110 */   969,  685,  847,  859,  858,  857,  680,  969,  969,  969,
   118137  /*   120 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118138  /*   130 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118139  /*   140 */   969,  969,  969,  969,  647,  964,  969,  969,  964,  964,
   118140  /*   150 */   964,  964,  964,  964,  956,  778,  768,  969,  969,  969,
   118141  /*   160 */   969,  969,  969,  969,  969,  969,  969,  944,  942,  969,
   118142  /*   170 */   891,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118143  /*   180 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118144  /*   190 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118145  /*   200 */   969,  969,  969,  969,  653,  969,  911,  774,  774,  774,
   118146  /*   210 */   776,  754,  766,  655,  812,  791,  791,  923,  812,  923,
   118147  /*   220 */   710,  733,  707,  802,  791,  874,  802,  802,  775,  766,
   118148  /*   230 */   969,  949,  782,  782,  941,  941,  782,  821,  743,  812,
   118149  /*   240 */   750,  750,  750,  750,  782,  670,  812,  821,  743,  743,
   118150  /*   250 */   812,  782,  670,  917,  915,  782,  782,  670,  782,  670,
   118151  /*   260 */   782,  670,  884,  741,  741,  741,  725,  884,  741,  710,
   118152  /*   270 */   741,  725,  741,  741,  795,  790,  795,  790,  795,  790,
   118153  /*   280 */   782,  782,  969,  884,  888,  888,  884,  807,  796,  805,
   118154  /*   290 */   803,  812,  676,  728,  663,  663,  652,  652,  652,  652,
   118155  /*   300 */   961,  961,  956,  712,  712,  695,  969,  969,  969,  969,
   118156  /*   310 */   969,  969,  687,  969,  893,  969,  969,  969,  969,  969,
   118157  /*   320 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118158  /*   330 */   969,  828,  969,  648,  951,  969,  969,  948,  969,  969,
   118159  /*   340 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118160  /*   350 */   969,  969,  969,  969,  969,  969,  921,  969,  969,  969,
   118161  /*   360 */   969,  969,  969,  914,  913,  969,  969,  969,  969,  969,
   118162  /*   370 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
   118163  /*   380 */   969,  969,  969,  969,  969,  969,  969,  757,  969,  969,
   118164  /*   390 */   969,  761,  969,  969,  969,  969,  969,  969,  804,  969,
   118165  /*   400 */   797,  969,  877,  969,  969,  969,  969,  969,  969,  969,
   118166  /*   410 */   969,  969,  969,  966,  969,  969,  969,  965,  969,  969,
   118167  /*   420 */   969,  969,  969,  830,  969,  829,  833,  969,  661,  969,
   118168  /*   430 */   644,  649,  960,  963,  962,  959,  958,  957,  952,  950,
   118169  /*   440 */   947,  946,  945,  943,  940,  936,  897,  895,  902,  901,
   118170  /*   450 */   900,  899,  898,  896,  894,  892,  818,  817,  814,  811,
   118171  /*   460 */   753,  935,  890,  752,  749,  748,  669,  953,  920,  929,
   118172  /*   470 */   928,  927,  822,  926,  925,  924,  922,  919,  906,  820,
   118173  /*   480 */   819,  744,  882,  881,  672,  910,  909,  908,  912,  916,
   118174  /*   490 */   907,  784,  751,  671,  668,  675,  679,  731,  732,  740,
   118175  /*   500 */   738,  737,  736,  735,  734,  730,  681,  686,  724,  709,
   118176  /*   510 */   708,  717,  716,  722,  721,  720,  719,  718,  715,  714,
   118177  /*   520 */   713,  706,  705,  711,  704,  727,  726,  723,  703,  747,
   118178  /*   530 */   746,  745,  742,  702,  701,  700,  833,  699,  698,  838,
   118179  /*   540 */   837,  866,  826,  755,  759,  758,  762,  763,  771,  770,
   118180  /*   550 */   769,  780,  781,  793,  792,  824,  823,  794,  779,  773,
   118181  /*   560 */   772,  788,  787,  786,  785,  777,  767,  799,  798,  868,
   118182  /*   570 */   783,  867,  865,  934,  933,  932,  931,  930,  870,  967,
   118183  /*   580 */   968,  887,  889,  886,  801,  800,  885,  869,  839,  836,
   118184  /*   590 */   690,  691,  905,  904,  903,  693,  692,  689,  688,  863,
   118185  /*   600 */   860,  852,  864,  861,  853,  849,  848,  834,  832,  831,
   118186  /*   610 */   827,  835,  760,  756,  825,  765,  764,  697,  696,  694,
   118187  /*   620 */   678,  677,  674,  667,  665,  664,  666,  662,  660,  659,
   118188  /*   630 */   658,  657,  656,  684,  683,  682,  654,  651,  650,  646,
   118189  /*   640 */   645,  643,
   118190 };
   118191 
   118192 /* The next table maps tokens into fallback tokens.  If a construct
   118193 ** like the following:
   118194 **
   118195 **      %fallback ID X Y Z.
   118196 **
   118197 ** appears in the grammar, then ID becomes a fallback token for X, Y,
   118198 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
   118199 ** but it does not parse, the type of the token is changed to ID and
   118200 ** the parse is retried before an error is thrown.
   118201 */
   118202 #ifdef YYFALLBACK
   118203 static const YYCODETYPE yyFallback[] = {
   118204     0,  /*          $ => nothing */
   118205     0,  /*       SEMI => nothing */
   118206    27,  /*    EXPLAIN => ID */
   118207    27,  /*      QUERY => ID */
   118208    27,  /*       PLAN => ID */
   118209    27,  /*      BEGIN => ID */
   118210     0,  /* TRANSACTION => nothing */
   118211    27,  /*   DEFERRED => ID */
   118212    27,  /*  IMMEDIATE => ID */
   118213    27,  /*  EXCLUSIVE => ID */
   118214     0,  /*     COMMIT => nothing */
   118215    27,  /*        END => ID */
   118216    27,  /*   ROLLBACK => ID */
   118217    27,  /*  SAVEPOINT => ID */
   118218    27,  /*    RELEASE => ID */
   118219     0,  /*         TO => nothing */
   118220     0,  /*      TABLE => nothing */
   118221     0,  /*     CREATE => nothing */
   118222    27,  /*         IF => ID */
   118223     0,  /*        NOT => nothing */
   118224     0,  /*     EXISTS => nothing */
   118225    27,  /*       TEMP => ID */
   118226     0,  /*         LP => nothing */
   118227     0,  /*         RP => nothing */
   118228     0,  /*         AS => nothing */
   118229    27,  /*    WITHOUT => ID */
   118230     0,  /*      COMMA => nothing */
   118231     0,  /*         ID => nothing */
   118232     0,  /*    INDEXED => nothing */
   118233    27,  /*      ABORT => ID */
   118234    27,  /*     ACTION => ID */
   118235    27,  /*      AFTER => ID */
   118236    27,  /*    ANALYZE => ID */
   118237    27,  /*        ASC => ID */
   118238    27,  /*     ATTACH => ID */
   118239    27,  /*     BEFORE => ID */
   118240    27,  /*         BY => ID */
   118241    27,  /*    CASCADE => ID */
   118242    27,  /*       CAST => ID */
   118243    27,  /*   COLUMNKW => ID */
   118244    27,  /*   CONFLICT => ID */
   118245    27,  /*   DATABASE => ID */
   118246    27,  /*       DESC => ID */
   118247    27,  /*     DETACH => ID */
   118248    27,  /*       EACH => ID */
   118249    27,  /*       FAIL => ID */
   118250    27,  /*        FOR => ID */
   118251    27,  /*     IGNORE => ID */
   118252    27,  /*  INITIALLY => ID */
   118253    27,  /*    INSTEAD => ID */
   118254    27,  /*    LIKE_KW => ID */
   118255    27,  /*      MATCH => ID */
   118256    27,  /*         NO => ID */
   118257    27,  /*        KEY => ID */
   118258    27,  /*         OF => ID */
   118259    27,  /*     OFFSET => ID */
   118260    27,  /*     PRAGMA => ID */
   118261    27,  /*      RAISE => ID */
   118262    27,  /*  RECURSIVE => ID */
   118263    27,  /*    REPLACE => ID */
   118264    27,  /*   RESTRICT => ID */
   118265    27,  /*        ROW => ID */
   118266    27,  /*    TRIGGER => ID */
   118267    27,  /*     VACUUM => ID */
   118268    27,  /*       VIEW => ID */
   118269    27,  /*    VIRTUAL => ID */
   118270    27,  /*       WITH => ID */
   118271    27,  /*    REINDEX => ID */
   118272    27,  /*     RENAME => ID */
   118273    27,  /*   CTIME_KW => ID */
   118274 };
   118275 #endif /* YYFALLBACK */
   118276 
   118277 /* The following structure represents a single element of the
   118278 ** parser's stack.  Information stored includes:
   118279 **
   118280 **   +  The state number for the parser at this level of the stack.
   118281 **
   118282 **   +  The value of the token stored at this level of the stack.
   118283 **      (In other words, the "major" token.)
   118284 **
   118285 **   +  The semantic value stored at this level of the stack.  This is
   118286 **      the information used by the action routines in the grammar.
   118287 **      It is sometimes called the "minor" token.
   118288 */
   118289 struct yyStackEntry {
   118290   YYACTIONTYPE stateno;  /* The state-number */
   118291   YYCODETYPE major;      /* The major token value.  This is the code
   118292                          ** number for the token at this stack level */
   118293   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
   118294                          ** is the value of the token  */
   118295 };
   118296 typedef struct yyStackEntry yyStackEntry;
   118297 
   118298 /* The state of the parser is completely contained in an instance of
   118299 ** the following structure */
   118300 struct yyParser {
   118301   int yyidx;                    /* Index of top element in stack */
   118302 #ifdef YYTRACKMAXSTACKDEPTH
   118303   int yyidxMax;                 /* Maximum value of yyidx */
   118304 #endif
   118305   int yyerrcnt;                 /* Shifts left before out of the error */
   118306   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
   118307 #if YYSTACKDEPTH<=0
   118308   int yystksz;                  /* Current side of the stack */
   118309   yyStackEntry *yystack;        /* The parser's stack */
   118310 #else
   118311   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
   118312 #endif
   118313 };
   118314 typedef struct yyParser yyParser;
   118315 
   118316 #ifndef NDEBUG
   118317 /* #include <stdio.h> */
   118318 static FILE *yyTraceFILE = 0;
   118319 static char *yyTracePrompt = 0;
   118320 #endif /* NDEBUG */
   118321 
   118322 #ifndef NDEBUG
   118323 /*
   118324 ** Turn parser tracing on by giving a stream to which to write the trace
   118325 ** and a prompt to preface each trace message.  Tracing is turned off
   118326 ** by making either argument NULL
   118327 **
   118328 ** Inputs:
   118329 ** <ul>
   118330 ** <li> A FILE* to which trace output should be written.
   118331 **      If NULL, then tracing is turned off.
   118332 ** <li> A prefix string written at the beginning of every
   118333 **      line of trace output.  If NULL, then tracing is
   118334 **      turned off.
   118335 ** </ul>
   118336 **
   118337 ** Outputs:
   118338 ** None.
   118339 */
   118340 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
   118341   yyTraceFILE = TraceFILE;
   118342   yyTracePrompt = zTracePrompt;
   118343   if( yyTraceFILE==0 ) yyTracePrompt = 0;
   118344   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
   118345 }
   118346 #endif /* NDEBUG */
   118347 
   118348 #ifndef NDEBUG
   118349 /* For tracing shifts, the names of all terminals and nonterminals
   118350 ** are required.  The following table supplies these names */
   118351 static const char *const yyTokenName[] = {
   118352   "$",             "SEMI",          "EXPLAIN",       "QUERY",
   118353   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
   118354   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
   118355   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
   118356   "TABLE",         "CREATE",        "IF",            "NOT",
   118357   "EXISTS",        "TEMP",          "LP",            "RP",
   118358   "AS",            "WITHOUT",       "COMMA",         "ID",
   118359   "INDEXED",       "ABORT",         "ACTION",        "AFTER",
   118360   "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
   118361   "BY",            "CASCADE",       "CAST",          "COLUMNKW",
   118362   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
   118363   "EACH",          "FAIL",          "FOR",           "IGNORE",
   118364   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",
   118365   "NO",            "KEY",           "OF",            "OFFSET",
   118366   "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",
   118367   "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",
   118368   "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",
   118369   "RENAME",        "CTIME_KW",      "ANY",           "OR",
   118370   "AND",           "IS",            "BETWEEN",       "IN",
   118371   "ISNULL",        "NOTNULL",       "NE",            "EQ",
   118372   "GT",            "LE",            "LT",            "GE",
   118373   "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",
   118374   "RSHIFT",        "PLUS",          "MINUS",         "STAR",
   118375   "SLASH",         "REM",           "CONCAT",        "COLLATE",
   118376   "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",
   118377   "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
   118378   "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
   118379   "INSERT",        "DELETE",        "UPDATE",        "SET",
   118380   "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
   118381   "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
   118382   "VALUES",        "DISTINCT",      "DOT",           "FROM",
   118383   "JOIN",          "USING",         "ORDER",         "GROUP",
   118384   "HAVING",        "LIMIT",         "WHERE",         "INTO",
   118385   "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
   118386   "CASE",          "WHEN",          "THEN",          "ELSE",
   118387   "INDEX",         "ALTER",         "ADD",           "error",
   118388   "input",         "cmdlist",       "ecmd",          "explain",
   118389   "cmdx",          "cmd",           "transtype",     "trans_opt",
   118390   "nm",            "savepoint_opt",  "create_table",  "create_table_args",
   118391   "createkw",      "temp",          "ifnotexists",   "dbnm",
   118392   "columnlist",    "conslist_opt",  "table_options",  "select",
   118393   "column",        "columnid",      "type",          "carglist",
   118394   "typetoken",     "typename",      "signed",        "plus_num",
   118395   "minus_num",     "ccons",         "term",          "expr",
   118396   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
   118397   "refargs",       "defer_subclause",  "refarg",        "refact",
   118398   "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",
   118399   "idxlist",       "defer_subclause_opt",  "orconf",        "resolvetype",
   118400   "raisetype",     "ifexists",      "fullname",      "selectnowith",
   118401   "oneselect",     "with",          "multiselect_op",  "distinct",
   118402   "selcollist",    "from",          "where_opt",     "groupby_opt",
   118403   "having_opt",    "orderby_opt",   "limit_opt",     "values",
   118404   "nexprlist",     "exprlist",      "sclp",          "as",
   118405   "seltablist",    "stl_prefix",    "joinop",        "indexed_opt",
   118406   "on_opt",        "using_opt",     "joinop2",       "idlist",
   118407   "sortlist",      "setlist",       "insert_cmd",    "inscollist_opt",
   118408   "likeop",        "between_op",    "in_op",         "case_operand",
   118409   "case_exprlist",  "case_else",     "uniqueflag",    "collate",
   118410   "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
   118411   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
   118412   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
   118413   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
   118414   "vtabarg",       "vtabargtoken",  "lp",            "anylist",
   118415   "wqlist",
   118416 };
   118417 #endif /* NDEBUG */
   118418 
   118419 #ifndef NDEBUG
   118420 /* For tracing reduce actions, the names of all rules are required.
   118421 */
   118422 static const char *const yyRuleName[] = {
   118423  /*   0 */ "input ::= cmdlist",
   118424  /*   1 */ "cmdlist ::= cmdlist ecmd",
   118425  /*   2 */ "cmdlist ::= ecmd",
   118426  /*   3 */ "ecmd ::= SEMI",
   118427  /*   4 */ "ecmd ::= explain cmdx SEMI",
   118428  /*   5 */ "explain ::=",
   118429  /*   6 */ "explain ::= EXPLAIN",
   118430  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
   118431  /*   8 */ "cmdx ::= cmd",
   118432  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
   118433  /*  10 */ "trans_opt ::=",
   118434  /*  11 */ "trans_opt ::= TRANSACTION",
   118435  /*  12 */ "trans_opt ::= TRANSACTION nm",
   118436  /*  13 */ "transtype ::=",
   118437  /*  14 */ "transtype ::= DEFERRED",
   118438  /*  15 */ "transtype ::= IMMEDIATE",
   118439  /*  16 */ "transtype ::= EXCLUSIVE",
   118440  /*  17 */ "cmd ::= COMMIT trans_opt",
   118441  /*  18 */ "cmd ::= END trans_opt",
   118442  /*  19 */ "cmd ::= ROLLBACK trans_opt",
   118443  /*  20 */ "savepoint_opt ::= SAVEPOINT",
   118444  /*  21 */ "savepoint_opt ::=",
   118445  /*  22 */ "cmd ::= SAVEPOINT nm",
   118446  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
   118447  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
   118448  /*  25 */ "cmd ::= create_table create_table_args",
   118449  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
   118450  /*  27 */ "createkw ::= CREATE",
   118451  /*  28 */ "ifnotexists ::=",
   118452  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
   118453  /*  30 */ "temp ::= TEMP",
   118454  /*  31 */ "temp ::=",
   118455  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
   118456  /*  33 */ "create_table_args ::= AS select",
   118457  /*  34 */ "table_options ::=",
   118458  /*  35 */ "table_options ::= WITHOUT nm",
   118459  /*  36 */ "columnlist ::= columnlist COMMA column",
   118460  /*  37 */ "columnlist ::= column",
   118461  /*  38 */ "column ::= columnid type carglist",
   118462  /*  39 */ "columnid ::= nm",
   118463  /*  40 */ "nm ::= ID|INDEXED",
   118464  /*  41 */ "nm ::= STRING",
   118465  /*  42 */ "nm ::= JOIN_KW",
   118466  /*  43 */ "type ::=",
   118467  /*  44 */ "type ::= typetoken",
   118468  /*  45 */ "typetoken ::= typename",
   118469  /*  46 */ "typetoken ::= typename LP signed RP",
   118470  /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
   118471  /*  48 */ "typename ::= ID|STRING",
   118472  /*  49 */ "typename ::= typename ID|STRING",
   118473  /*  50 */ "signed ::= plus_num",
   118474  /*  51 */ "signed ::= minus_num",
   118475  /*  52 */ "carglist ::= carglist ccons",
   118476  /*  53 */ "carglist ::=",
   118477  /*  54 */ "ccons ::= CONSTRAINT nm",
   118478  /*  55 */ "ccons ::= DEFAULT term",
   118479  /*  56 */ "ccons ::= DEFAULT LP expr RP",
   118480  /*  57 */ "ccons ::= DEFAULT PLUS term",
   118481  /*  58 */ "ccons ::= DEFAULT MINUS term",
   118482  /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
   118483  /*  60 */ "ccons ::= NULL onconf",
   118484  /*  61 */ "ccons ::= NOT NULL onconf",
   118485  /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
   118486  /*  63 */ "ccons ::= UNIQUE onconf",
   118487  /*  64 */ "ccons ::= CHECK LP expr RP",
   118488  /*  65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
   118489  /*  66 */ "ccons ::= defer_subclause",
   118490  /*  67 */ "ccons ::= COLLATE ID|STRING",
   118491  /*  68 */ "autoinc ::=",
   118492  /*  69 */ "autoinc ::= AUTOINCR",
   118493  /*  70 */ "refargs ::=",
   118494  /*  71 */ "refargs ::= refargs refarg",
   118495  /*  72 */ "refarg ::= MATCH nm",
   118496  /*  73 */ "refarg ::= ON INSERT refact",
   118497  /*  74 */ "refarg ::= ON DELETE refact",
   118498  /*  75 */ "refarg ::= ON UPDATE refact",
   118499  /*  76 */ "refact ::= SET NULL",
   118500  /*  77 */ "refact ::= SET DEFAULT",
   118501  /*  78 */ "refact ::= CASCADE",
   118502  /*  79 */ "refact ::= RESTRICT",
   118503  /*  80 */ "refact ::= NO ACTION",
   118504  /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
   118505  /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
   118506  /*  83 */ "init_deferred_pred_opt ::=",
   118507  /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
   118508  /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
   118509  /*  86 */ "conslist_opt ::=",
   118510  /*  87 */ "conslist_opt ::= COMMA conslist",
   118511  /*  88 */ "conslist ::= conslist tconscomma tcons",
   118512  /*  89 */ "conslist ::= tcons",
   118513  /*  90 */ "tconscomma ::= COMMA",
   118514  /*  91 */ "tconscomma ::=",
   118515  /*  92 */ "tcons ::= CONSTRAINT nm",
   118516  /*  93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
   118517  /*  94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
   118518  /*  95 */ "tcons ::= CHECK LP expr RP onconf",
   118519  /*  96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
   118520  /*  97 */ "defer_subclause_opt ::=",
   118521  /*  98 */ "defer_subclause_opt ::= defer_subclause",
   118522  /*  99 */ "onconf ::=",
   118523  /* 100 */ "onconf ::= ON CONFLICT resolvetype",
   118524  /* 101 */ "orconf ::=",
   118525  /* 102 */ "orconf ::= OR resolvetype",
   118526  /* 103 */ "resolvetype ::= raisetype",
   118527  /* 104 */ "resolvetype ::= IGNORE",
   118528  /* 105 */ "resolvetype ::= REPLACE",
   118529  /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
   118530  /* 107 */ "ifexists ::= IF EXISTS",
   118531  /* 108 */ "ifexists ::=",
   118532  /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
   118533  /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
   118534  /* 111 */ "cmd ::= select",
   118535  /* 112 */ "select ::= with selectnowith",
   118536  /* 113 */ "selectnowith ::= oneselect",
   118537  /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
   118538  /* 115 */ "multiselect_op ::= UNION",
   118539  /* 116 */ "multiselect_op ::= UNION ALL",
   118540  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
   118541  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
   118542  /* 119 */ "oneselect ::= values",
   118543  /* 120 */ "values ::= VALUES LP nexprlist RP",
   118544  /* 121 */ "values ::= values COMMA LP exprlist RP",
   118545  /* 122 */ "distinct ::= DISTINCT",
   118546  /* 123 */ "distinct ::= ALL",
   118547  /* 124 */ "distinct ::=",
   118548  /* 125 */ "sclp ::= selcollist COMMA",
   118549  /* 126 */ "sclp ::=",
   118550  /* 127 */ "selcollist ::= sclp expr as",
   118551  /* 128 */ "selcollist ::= sclp STAR",
   118552  /* 129 */ "selcollist ::= sclp nm DOT STAR",
   118553  /* 130 */ "as ::= AS nm",
   118554  /* 131 */ "as ::= ID|STRING",
   118555  /* 132 */ "as ::=",
   118556  /* 133 */ "from ::=",
   118557  /* 134 */ "from ::= FROM seltablist",
   118558  /* 135 */ "stl_prefix ::= seltablist joinop",
   118559  /* 136 */ "stl_prefix ::=",
   118560  /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
   118561  /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
   118562  /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
   118563  /* 140 */ "dbnm ::=",
   118564  /* 141 */ "dbnm ::= DOT nm",
   118565  /* 142 */ "fullname ::= nm dbnm",
   118566  /* 143 */ "joinop ::= COMMA|JOIN",
   118567  /* 144 */ "joinop ::= JOIN_KW JOIN",
   118568  /* 145 */ "joinop ::= JOIN_KW nm JOIN",
   118569  /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
   118570  /* 147 */ "on_opt ::= ON expr",
   118571  /* 148 */ "on_opt ::=",
   118572  /* 149 */ "indexed_opt ::=",
   118573  /* 150 */ "indexed_opt ::= INDEXED BY nm",
   118574  /* 151 */ "indexed_opt ::= NOT INDEXED",
   118575  /* 152 */ "using_opt ::= USING LP idlist RP",
   118576  /* 153 */ "using_opt ::=",
   118577  /* 154 */ "orderby_opt ::=",
   118578  /* 155 */ "orderby_opt ::= ORDER BY sortlist",
   118579  /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
   118580  /* 157 */ "sortlist ::= expr sortorder",
   118581  /* 158 */ "sortorder ::= ASC",
   118582  /* 159 */ "sortorder ::= DESC",
   118583  /* 160 */ "sortorder ::=",
   118584  /* 161 */ "groupby_opt ::=",
   118585  /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
   118586  /* 163 */ "having_opt ::=",
   118587  /* 164 */ "having_opt ::= HAVING expr",
   118588  /* 165 */ "limit_opt ::=",
   118589  /* 166 */ "limit_opt ::= LIMIT expr",
   118590  /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
   118591  /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
   118592  /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
   118593  /* 170 */ "where_opt ::=",
   118594  /* 171 */ "where_opt ::= WHERE expr",
   118595  /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
   118596  /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
   118597  /* 174 */ "setlist ::= nm EQ expr",
   118598  /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
   118599  /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
   118600  /* 177 */ "insert_cmd ::= INSERT orconf",
   118601  /* 178 */ "insert_cmd ::= REPLACE",
   118602  /* 179 */ "inscollist_opt ::=",
   118603  /* 180 */ "inscollist_opt ::= LP idlist RP",
   118604  /* 181 */ "idlist ::= idlist COMMA nm",
   118605  /* 182 */ "idlist ::= nm",
   118606  /* 183 */ "expr ::= term",
   118607  /* 184 */ "expr ::= LP expr RP",
   118608  /* 185 */ "term ::= NULL",
   118609  /* 186 */ "expr ::= ID|INDEXED",
   118610  /* 187 */ "expr ::= JOIN_KW",
   118611  /* 188 */ "expr ::= nm DOT nm",
   118612  /* 189 */ "expr ::= nm DOT nm DOT nm",
   118613  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
   118614  /* 191 */ "term ::= STRING",
   118615  /* 192 */ "expr ::= VARIABLE",
   118616  /* 193 */ "expr ::= expr COLLATE ID|STRING",
   118617  /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
   118618  /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
   118619  /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
   118620  /* 197 */ "term ::= CTIME_KW",
   118621  /* 198 */ "expr ::= expr AND expr",
   118622  /* 199 */ "expr ::= expr OR expr",
   118623  /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
   118624  /* 201 */ "expr ::= expr EQ|NE expr",
   118625  /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
   118626  /* 203 */ "expr ::= expr PLUS|MINUS expr",
   118627  /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
   118628  /* 205 */ "expr ::= expr CONCAT expr",
   118629  /* 206 */ "likeop ::= LIKE_KW|MATCH",
   118630  /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
   118631  /* 208 */ "expr ::= expr likeop expr",
   118632  /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
   118633  /* 210 */ "expr ::= expr ISNULL|NOTNULL",
   118634  /* 211 */ "expr ::= expr NOT NULL",
   118635  /* 212 */ "expr ::= expr IS expr",
   118636  /* 213 */ "expr ::= expr IS NOT expr",
   118637  /* 214 */ "expr ::= NOT expr",
   118638  /* 215 */ "expr ::= BITNOT expr",
   118639  /* 216 */ "expr ::= MINUS expr",
   118640  /* 217 */ "expr ::= PLUS expr",
   118641  /* 218 */ "between_op ::= BETWEEN",
   118642  /* 219 */ "between_op ::= NOT BETWEEN",
   118643  /* 220 */ "expr ::= expr between_op expr AND expr",
   118644  /* 221 */ "in_op ::= IN",
   118645  /* 222 */ "in_op ::= NOT IN",
   118646  /* 223 */ "expr ::= expr in_op LP exprlist RP",
   118647  /* 224 */ "expr ::= LP select RP",
   118648  /* 225 */ "expr ::= expr in_op LP select RP",
   118649  /* 226 */ "expr ::= expr in_op nm dbnm",
   118650  /* 227 */ "expr ::= EXISTS LP select RP",
   118651  /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
   118652  /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
   118653  /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
   118654  /* 231 */ "case_else ::= ELSE expr",
   118655  /* 232 */ "case_else ::=",
   118656  /* 233 */ "case_operand ::= expr",
   118657  /* 234 */ "case_operand ::=",
   118658  /* 235 */ "exprlist ::= nexprlist",
   118659  /* 236 */ "exprlist ::=",
   118660  /* 237 */ "nexprlist ::= nexprlist COMMA expr",
   118661  /* 238 */ "nexprlist ::= expr",
   118662  /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
   118663  /* 240 */ "uniqueflag ::= UNIQUE",
   118664  /* 241 */ "uniqueflag ::=",
   118665  /* 242 */ "idxlist_opt ::=",
   118666  /* 243 */ "idxlist_opt ::= LP idxlist RP",
   118667  /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
   118668  /* 245 */ "idxlist ::= nm collate sortorder",
   118669  /* 246 */ "collate ::=",
   118670  /* 247 */ "collate ::= COLLATE ID|STRING",
   118671  /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
   118672  /* 249 */ "cmd ::= VACUUM",
   118673  /* 250 */ "cmd ::= VACUUM nm",
   118674  /* 251 */ "cmd ::= PRAGMA nm dbnm",
   118675  /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
   118676  /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
   118677  /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
   118678  /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
   118679  /* 256 */ "nmnum ::= plus_num",
   118680  /* 257 */ "nmnum ::= nm",
   118681  /* 258 */ "nmnum ::= ON",
   118682  /* 259 */ "nmnum ::= DELETE",
   118683  /* 260 */ "nmnum ::= DEFAULT",
   118684  /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
   118685  /* 262 */ "plus_num ::= INTEGER|FLOAT",
   118686  /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
   118687  /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
   118688  /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
   118689  /* 266 */ "trigger_time ::= BEFORE",
   118690  /* 267 */ "trigger_time ::= AFTER",
   118691  /* 268 */ "trigger_time ::= INSTEAD OF",
   118692  /* 269 */ "trigger_time ::=",
   118693  /* 270 */ "trigger_event ::= DELETE|INSERT",
   118694  /* 271 */ "trigger_event ::= UPDATE",
   118695  /* 272 */ "trigger_event ::= UPDATE OF idlist",
   118696  /* 273 */ "foreach_clause ::=",
   118697  /* 274 */ "foreach_clause ::= FOR EACH ROW",
   118698  /* 275 */ "when_clause ::=",
   118699  /* 276 */ "when_clause ::= WHEN expr",
   118700  /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
   118701  /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
   118702  /* 279 */ "trnm ::= nm",
   118703  /* 280 */ "trnm ::= nm DOT nm",
   118704  /* 281 */ "tridxby ::=",
   118705  /* 282 */ "tridxby ::= INDEXED BY nm",
   118706  /* 283 */ "tridxby ::= NOT INDEXED",
   118707  /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
   118708  /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
   118709  /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
   118710  /* 287 */ "trigger_cmd ::= select",
   118711  /* 288 */ "expr ::= RAISE LP IGNORE RP",
   118712  /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
   118713  /* 290 */ "raisetype ::= ROLLBACK",
   118714  /* 291 */ "raisetype ::= ABORT",
   118715  /* 292 */ "raisetype ::= FAIL",
   118716  /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
   118717  /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
   118718  /* 295 */ "cmd ::= DETACH database_kw_opt expr",
   118719  /* 296 */ "key_opt ::=",
   118720  /* 297 */ "key_opt ::= KEY expr",
   118721  /* 298 */ "database_kw_opt ::= DATABASE",
   118722  /* 299 */ "database_kw_opt ::=",
   118723  /* 300 */ "cmd ::= REINDEX",
   118724  /* 301 */ "cmd ::= REINDEX nm dbnm",
   118725  /* 302 */ "cmd ::= ANALYZE",
   118726  /* 303 */ "cmd ::= ANALYZE nm dbnm",
   118727  /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
   118728  /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
   118729  /* 306 */ "add_column_fullname ::= fullname",
   118730  /* 307 */ "kwcolumn_opt ::=",
   118731  /* 308 */ "kwcolumn_opt ::= COLUMNKW",
   118732  /* 309 */ "cmd ::= create_vtab",
   118733  /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
   118734  /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
   118735  /* 312 */ "vtabarglist ::= vtabarg",
   118736  /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
   118737  /* 314 */ "vtabarg ::=",
   118738  /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
   118739  /* 316 */ "vtabargtoken ::= ANY",
   118740  /* 317 */ "vtabargtoken ::= lp anylist RP",
   118741  /* 318 */ "lp ::= LP",
   118742  /* 319 */ "anylist ::=",
   118743  /* 320 */ "anylist ::= anylist LP anylist RP",
   118744  /* 321 */ "anylist ::= anylist ANY",
   118745  /* 322 */ "with ::=",
   118746  /* 323 */ "with ::= WITH wqlist",
   118747  /* 324 */ "with ::= WITH RECURSIVE wqlist",
   118748  /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
   118749  /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
   118750 };
   118751 #endif /* NDEBUG */
   118752 
   118753 
   118754 #if YYSTACKDEPTH<=0
   118755 /*
   118756 ** Try to increase the size of the parser stack.
   118757 */
   118758 static void yyGrowStack(yyParser *p){
   118759   int newSize;
   118760   yyStackEntry *pNew;
   118761 
   118762   newSize = p->yystksz*2 + 100;
   118763   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
   118764   if( pNew ){
   118765     p->yystack = pNew;
   118766     p->yystksz = newSize;
   118767 #ifndef NDEBUG
   118768     if( yyTraceFILE ){
   118769       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
   118770               yyTracePrompt, p->yystksz);
   118771     }
   118772 #endif
   118773   }
   118774 }
   118775 #endif
   118776 
   118777 /*
   118778 ** This function allocates a new parser.
   118779 ** The only argument is a pointer to a function which works like
   118780 ** malloc.
   118781 **
   118782 ** Inputs:
   118783 ** A pointer to the function used to allocate memory.
   118784 **
   118785 ** Outputs:
   118786 ** A pointer to a parser.  This pointer is used in subsequent calls
   118787 ** to sqlite3Parser and sqlite3ParserFree.
   118788 */
   118789 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
   118790   yyParser *pParser;
   118791   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
   118792   if( pParser ){
   118793     pParser->yyidx = -1;
   118794 #ifdef YYTRACKMAXSTACKDEPTH
   118795     pParser->yyidxMax = 0;
   118796 #endif
   118797 #if YYSTACKDEPTH<=0
   118798     pParser->yystack = NULL;
   118799     pParser->yystksz = 0;
   118800     yyGrowStack(pParser);
   118801 #endif
   118802   }
   118803   return pParser;
   118804 }
   118805 
   118806 /* The following function deletes the value associated with a
   118807 ** symbol.  The symbol can be either a terminal or nonterminal.
   118808 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
   118809 ** the value.
   118810 */
   118811 static void yy_destructor(
   118812   yyParser *yypParser,    /* The parser */
   118813   YYCODETYPE yymajor,     /* Type code for object to destroy */
   118814   YYMINORTYPE *yypminor   /* The object to be destroyed */
   118815 ){
   118816   sqlite3ParserARG_FETCH;
   118817   switch( yymajor ){
   118818     /* Here is inserted the actions which take place when a
   118819     ** terminal or non-terminal is destroyed.  This can happen
   118820     ** when the symbol is popped from the stack during a
   118821     ** reduce or during error processing or when a parser is
   118822     ** being destroyed before it is finished parsing.
   118823     **
   118824     ** Note: during a reduce, the only symbols destroyed are those
   118825     ** which appear on the RHS of the rule, but which are not used
   118826     ** inside the C code.
   118827     */
   118828     case 163: /* select */
   118829     case 195: /* selectnowith */
   118830     case 196: /* oneselect */
   118831     case 207: /* values */
   118832 {
   118833 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
   118834 }
   118835       break;
   118836     case 174: /* term */
   118837     case 175: /* expr */
   118838 {
   118839 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
   118840 }
   118841       break;
   118842     case 179: /* idxlist_opt */
   118843     case 188: /* idxlist */
   118844     case 200: /* selcollist */
   118845     case 203: /* groupby_opt */
   118846     case 205: /* orderby_opt */
   118847     case 208: /* nexprlist */
   118848     case 209: /* exprlist */
   118849     case 210: /* sclp */
   118850     case 220: /* sortlist */
   118851     case 221: /* setlist */
   118852     case 228: /* case_exprlist */
   118853 {
   118854 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
   118855 }
   118856       break;
   118857     case 194: /* fullname */
   118858     case 201: /* from */
   118859     case 212: /* seltablist */
   118860     case 213: /* stl_prefix */
   118861 {
   118862 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
   118863 }
   118864       break;
   118865     case 197: /* with */
   118866     case 252: /* wqlist */
   118867 {
   118868 sqlite3WithDelete(pParse->db, (yypminor->yy59));
   118869 }
   118870       break;
   118871     case 202: /* where_opt */
   118872     case 204: /* having_opt */
   118873     case 216: /* on_opt */
   118874     case 227: /* case_operand */
   118875     case 229: /* case_else */
   118876     case 238: /* when_clause */
   118877     case 243: /* key_opt */
   118878 {
   118879 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
   118880 }
   118881       break;
   118882     case 217: /* using_opt */
   118883     case 219: /* idlist */
   118884     case 223: /* inscollist_opt */
   118885 {
   118886 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
   118887 }
   118888       break;
   118889     case 234: /* trigger_cmd_list */
   118890     case 239: /* trigger_cmd */
   118891 {
   118892 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
   118893 }
   118894       break;
   118895     case 236: /* trigger_event */
   118896 {
   118897 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
   118898 }
   118899       break;
   118900     default:  break;   /* If no destructor action specified: do nothing */
   118901   }
   118902 }
   118903 
   118904 /*
   118905 ** Pop the parser's stack once.
   118906 **
   118907 ** If there is a destructor routine associated with the token which
   118908 ** is popped from the stack, then call it.
   118909 **
   118910 ** Return the major token number for the symbol popped.
   118911 */
   118912 static int yy_pop_parser_stack(yyParser *pParser){
   118913   YYCODETYPE yymajor;
   118914   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
   118915 
   118916   /* There is no mechanism by which the parser stack can be popped below
   118917   ** empty in SQLite.  */
   118918   if( NEVER(pParser->yyidx<0) ) return 0;
   118919 #ifndef NDEBUG
   118920   if( yyTraceFILE && pParser->yyidx>=0 ){
   118921     fprintf(yyTraceFILE,"%sPopping %s\n",
   118922       yyTracePrompt,
   118923       yyTokenName[yytos->major]);
   118924   }
   118925 #endif
   118926   yymajor = yytos->major;
   118927   yy_destructor(pParser, yymajor, &yytos->minor);
   118928   pParser->yyidx--;
   118929   return yymajor;
   118930 }
   118931 
   118932 /*
   118933 ** Deallocate and destroy a parser.  Destructors are all called for
   118934 ** all stack elements before shutting the parser down.
   118935 **
   118936 ** Inputs:
   118937 ** <ul>
   118938 ** <li>  A pointer to the parser.  This should be a pointer
   118939 **       obtained from sqlite3ParserAlloc.
   118940 ** <li>  A pointer to a function used to reclaim memory obtained
   118941 **       from malloc.
   118942 ** </ul>
   118943 */
   118944 SQLITE_PRIVATE void sqlite3ParserFree(
   118945   void *p,                    /* The parser to be deleted */
   118946   void (*freeProc)(void*)     /* Function used to reclaim memory */
   118947 ){
   118948   yyParser *pParser = (yyParser*)p;
   118949   /* In SQLite, we never try to destroy a parser that was not successfully
   118950   ** created in the first place. */
   118951   if( NEVER(pParser==0) ) return;
   118952   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
   118953 #if YYSTACKDEPTH<=0
   118954   free(pParser->yystack);
   118955 #endif
   118956   (*freeProc)((void*)pParser);
   118957 }
   118958 
   118959 /*
   118960 ** Return the peak depth of the stack for a parser.
   118961 */
   118962 #ifdef YYTRACKMAXSTACKDEPTH
   118963 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
   118964   yyParser *pParser = (yyParser*)p;
   118965   return pParser->yyidxMax;
   118966 }
   118967 #endif
   118968 
   118969 /*
   118970 ** Find the appropriate action for a parser given the terminal
   118971 ** look-ahead token iLookAhead.
   118972 **
   118973 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   118974 ** independent of the look-ahead.  If it is, return the action, otherwise
   118975 ** return YY_NO_ACTION.
   118976 */
   118977 static int yy_find_shift_action(
   118978   yyParser *pParser,        /* The parser */
   118979   YYCODETYPE iLookAhead     /* The look-ahead token */
   118980 ){
   118981   int i;
   118982   int stateno = pParser->yystack[pParser->yyidx].stateno;
   118983 
   118984   if( stateno>YY_SHIFT_COUNT
   118985    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
   118986     return yy_default[stateno];
   118987   }
   118988   assert( iLookAhead!=YYNOCODE );
   118989   i += iLookAhead;
   118990   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   118991     if( iLookAhead>0 ){
   118992 #ifdef YYFALLBACK
   118993       YYCODETYPE iFallback;            /* Fallback token */
   118994       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
   118995              && (iFallback = yyFallback[iLookAhead])!=0 ){
   118996 #ifndef NDEBUG
   118997         if( yyTraceFILE ){
   118998           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
   118999              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
   119000         }
   119001 #endif
   119002         return yy_find_shift_action(pParser, iFallback);
   119003       }
   119004 #endif
   119005 #ifdef YYWILDCARD
   119006       {
   119007         int j = i - iLookAhead + YYWILDCARD;
   119008         if(
   119009 #if YY_SHIFT_MIN+YYWILDCARD<0
   119010           j>=0 &&
   119011 #endif
   119012 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
   119013           j<YY_ACTTAB_COUNT &&
   119014 #endif
   119015           yy_lookahead[j]==YYWILDCARD
   119016         ){
   119017 #ifndef NDEBUG
   119018           if( yyTraceFILE ){
   119019             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
   119020                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
   119021           }
   119022 #endif /* NDEBUG */
   119023           return yy_action[j];
   119024         }
   119025       }
   119026 #endif /* YYWILDCARD */
   119027     }
   119028     return yy_default[stateno];
   119029   }else{
   119030     return yy_action[i];
   119031   }
   119032 }
   119033 
   119034 /*
   119035 ** Find the appropriate action for a parser given the non-terminal
   119036 ** look-ahead token iLookAhead.
   119037 **
   119038 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   119039 ** independent of the look-ahead.  If it is, return the action, otherwise
   119040 ** return YY_NO_ACTION.
   119041 */
   119042 static int yy_find_reduce_action(
   119043   int stateno,              /* Current state number */
   119044   YYCODETYPE iLookAhead     /* The look-ahead token */
   119045 ){
   119046   int i;
   119047 #ifdef YYERRORSYMBOL
   119048   if( stateno>YY_REDUCE_COUNT ){
   119049     return yy_default[stateno];
   119050   }
   119051 #else
   119052   assert( stateno<=YY_REDUCE_COUNT );
   119053 #endif
   119054   i = yy_reduce_ofst[stateno];
   119055   assert( i!=YY_REDUCE_USE_DFLT );
   119056   assert( iLookAhead!=YYNOCODE );
   119057   i += iLookAhead;
   119058 #ifdef YYERRORSYMBOL
   119059   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   119060     return yy_default[stateno];
   119061   }
   119062 #else
   119063   assert( i>=0 && i<YY_ACTTAB_COUNT );
   119064   assert( yy_lookahead[i]==iLookAhead );
   119065 #endif
   119066   return yy_action[i];
   119067 }
   119068 
   119069 /*
   119070 ** The following routine is called if the stack overflows.
   119071 */
   119072 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
   119073    sqlite3ParserARG_FETCH;
   119074    yypParser->yyidx--;
   119075 #ifndef NDEBUG
   119076    if( yyTraceFILE ){
   119077      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   119078    }
   119079 #endif
   119080    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   119081    /* Here code is inserted which will execute if the parser
   119082    ** stack every overflows */
   119083 
   119084   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
   119085   sqlite3ErrorMsg(pParse, "parser stack overflow");
   119086    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
   119087 }
   119088 
   119089 /*
   119090 ** Perform a shift action.
   119091 */
   119092 static void yy_shift(
   119093   yyParser *yypParser,          /* The parser to be shifted */
   119094   int yyNewState,               /* The new state to shift in */
   119095   int yyMajor,                  /* The major token to shift in */
   119096   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
   119097 ){
   119098   yyStackEntry *yytos;
   119099   yypParser->yyidx++;
   119100 #ifdef YYTRACKMAXSTACKDEPTH
   119101   if( yypParser->yyidx>yypParser->yyidxMax ){
   119102     yypParser->yyidxMax = yypParser->yyidx;
   119103   }
   119104 #endif
   119105 #if YYSTACKDEPTH>0
   119106   if( yypParser->yyidx>=YYSTACKDEPTH ){
   119107     yyStackOverflow(yypParser, yypMinor);
   119108     return;
   119109   }
   119110 #else
   119111   if( yypParser->yyidx>=yypParser->yystksz ){
   119112     yyGrowStack(yypParser);
   119113     if( yypParser->yyidx>=yypParser->yystksz ){
   119114       yyStackOverflow(yypParser, yypMinor);
   119115       return;
   119116     }
   119117   }
   119118 #endif
   119119   yytos = &yypParser->yystack[yypParser->yyidx];
   119120   yytos->stateno = (YYACTIONTYPE)yyNewState;
   119121   yytos->major = (YYCODETYPE)yyMajor;
   119122   yytos->minor = *yypMinor;
   119123 #ifndef NDEBUG
   119124   if( yyTraceFILE && yypParser->yyidx>0 ){
   119125     int i;
   119126     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
   119127     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
   119128     for(i=1; i<=yypParser->yyidx; i++)
   119129       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
   119130     fprintf(yyTraceFILE,"\n");
   119131   }
   119132 #endif
   119133 }
   119134 
   119135 /* The following table contains information about every rule that
   119136 ** is used during the reduce.
   119137 */
   119138 static const struct {
   119139   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
   119140   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
   119141 } yyRuleInfo[] = {
   119142   { 144, 1 },
   119143   { 145, 2 },
   119144   { 145, 1 },
   119145   { 146, 1 },
   119146   { 146, 3 },
   119147   { 147, 0 },
   119148   { 147, 1 },
   119149   { 147, 3 },
   119150   { 148, 1 },
   119151   { 149, 3 },
   119152   { 151, 0 },
   119153   { 151, 1 },
   119154   { 151, 2 },
   119155   { 150, 0 },
   119156   { 150, 1 },
   119157   { 150, 1 },
   119158   { 150, 1 },
   119159   { 149, 2 },
   119160   { 149, 2 },
   119161   { 149, 2 },
   119162   { 153, 1 },
   119163   { 153, 0 },
   119164   { 149, 2 },
   119165   { 149, 3 },
   119166   { 149, 5 },
   119167   { 149, 2 },
   119168   { 154, 6 },
   119169   { 156, 1 },
   119170   { 158, 0 },
   119171   { 158, 3 },
   119172   { 157, 1 },
   119173   { 157, 0 },
   119174   { 155, 5 },
   119175   { 155, 2 },
   119176   { 162, 0 },
   119177   { 162, 2 },
   119178   { 160, 3 },
   119179   { 160, 1 },
   119180   { 164, 3 },
   119181   { 165, 1 },
   119182   { 152, 1 },
   119183   { 152, 1 },
   119184   { 152, 1 },
   119185   { 166, 0 },
   119186   { 166, 1 },
   119187   { 168, 1 },
   119188   { 168, 4 },
   119189   { 168, 6 },
   119190   { 169, 1 },
   119191   { 169, 2 },
   119192   { 170, 1 },
   119193   { 170, 1 },
   119194   { 167, 2 },
   119195   { 167, 0 },
   119196   { 173, 2 },
   119197   { 173, 2 },
   119198   { 173, 4 },
   119199   { 173, 3 },
   119200   { 173, 3 },
   119201   { 173, 2 },
   119202   { 173, 2 },
   119203   { 173, 3 },
   119204   { 173, 5 },
   119205   { 173, 2 },
   119206   { 173, 4 },
   119207   { 173, 4 },
   119208   { 173, 1 },
   119209   { 173, 2 },
   119210   { 178, 0 },
   119211   { 178, 1 },
   119212   { 180, 0 },
   119213   { 180, 2 },
   119214   { 182, 2 },
   119215   { 182, 3 },
   119216   { 182, 3 },
   119217   { 182, 3 },
   119218   { 183, 2 },
   119219   { 183, 2 },
   119220   { 183, 1 },
   119221   { 183, 1 },
   119222   { 183, 2 },
   119223   { 181, 3 },
   119224   { 181, 2 },
   119225   { 184, 0 },
   119226   { 184, 2 },
   119227   { 184, 2 },
   119228   { 161, 0 },
   119229   { 161, 2 },
   119230   { 185, 3 },
   119231   { 185, 1 },
   119232   { 186, 1 },
   119233   { 186, 0 },
   119234   { 187, 2 },
   119235   { 187, 7 },
   119236   { 187, 5 },
   119237   { 187, 5 },
   119238   { 187, 10 },
   119239   { 189, 0 },
   119240   { 189, 1 },
   119241   { 176, 0 },
   119242   { 176, 3 },
   119243   { 190, 0 },
   119244   { 190, 2 },
   119245   { 191, 1 },
   119246   { 191, 1 },
   119247   { 191, 1 },
   119248   { 149, 4 },
   119249   { 193, 2 },
   119250   { 193, 0 },
   119251   { 149, 8 },
   119252   { 149, 4 },
   119253   { 149, 1 },
   119254   { 163, 2 },
   119255   { 195, 1 },
   119256   { 195, 3 },
   119257   { 198, 1 },
   119258   { 198, 2 },
   119259   { 198, 1 },
   119260   { 196, 9 },
   119261   { 196, 1 },
   119262   { 207, 4 },
   119263   { 207, 5 },
   119264   { 199, 1 },
   119265   { 199, 1 },
   119266   { 199, 0 },
   119267   { 210, 2 },
   119268   { 210, 0 },
   119269   { 200, 3 },
   119270   { 200, 2 },
   119271   { 200, 4 },
   119272   { 211, 2 },
   119273   { 211, 1 },
   119274   { 211, 0 },
   119275   { 201, 0 },
   119276   { 201, 2 },
   119277   { 213, 2 },
   119278   { 213, 0 },
   119279   { 212, 7 },
   119280   { 212, 7 },
   119281   { 212, 7 },
   119282   { 159, 0 },
   119283   { 159, 2 },
   119284   { 194, 2 },
   119285   { 214, 1 },
   119286   { 214, 2 },
   119287   { 214, 3 },
   119288   { 214, 4 },
   119289   { 216, 2 },
   119290   { 216, 0 },
   119291   { 215, 0 },
   119292   { 215, 3 },
   119293   { 215, 2 },
   119294   { 217, 4 },
   119295   { 217, 0 },
   119296   { 205, 0 },
   119297   { 205, 3 },
   119298   { 220, 4 },
   119299   { 220, 2 },
   119300   { 177, 1 },
   119301   { 177, 1 },
   119302   { 177, 0 },
   119303   { 203, 0 },
   119304   { 203, 3 },
   119305   { 204, 0 },
   119306   { 204, 2 },
   119307   { 206, 0 },
   119308   { 206, 2 },
   119309   { 206, 4 },
   119310   { 206, 4 },
   119311   { 149, 6 },
   119312   { 202, 0 },
   119313   { 202, 2 },
   119314   { 149, 8 },
   119315   { 221, 5 },
   119316   { 221, 3 },
   119317   { 149, 6 },
   119318   { 149, 7 },
   119319   { 222, 2 },
   119320   { 222, 1 },
   119321   { 223, 0 },
   119322   { 223, 3 },
   119323   { 219, 3 },
   119324   { 219, 1 },
   119325   { 175, 1 },
   119326   { 175, 3 },
   119327   { 174, 1 },
   119328   { 175, 1 },
   119329   { 175, 1 },
   119330   { 175, 3 },
   119331   { 175, 5 },
   119332   { 174, 1 },
   119333   { 174, 1 },
   119334   { 175, 1 },
   119335   { 175, 3 },
   119336   { 175, 6 },
   119337   { 175, 5 },
   119338   { 175, 4 },
   119339   { 174, 1 },
   119340   { 175, 3 },
   119341   { 175, 3 },
   119342   { 175, 3 },
   119343   { 175, 3 },
   119344   { 175, 3 },
   119345   { 175, 3 },
   119346   { 175, 3 },
   119347   { 175, 3 },
   119348   { 224, 1 },
   119349   { 224, 2 },
   119350   { 175, 3 },
   119351   { 175, 5 },
   119352   { 175, 2 },
   119353   { 175, 3 },
   119354   { 175, 3 },
   119355   { 175, 4 },
   119356   { 175, 2 },
   119357   { 175, 2 },
   119358   { 175, 2 },
   119359   { 175, 2 },
   119360   { 225, 1 },
   119361   { 225, 2 },
   119362   { 175, 5 },
   119363   { 226, 1 },
   119364   { 226, 2 },
   119365   { 175, 5 },
   119366   { 175, 3 },
   119367   { 175, 5 },
   119368   { 175, 4 },
   119369   { 175, 4 },
   119370   { 175, 5 },
   119371   { 228, 5 },
   119372   { 228, 4 },
   119373   { 229, 2 },
   119374   { 229, 0 },
   119375   { 227, 1 },
   119376   { 227, 0 },
   119377   { 209, 1 },
   119378   { 209, 0 },
   119379   { 208, 3 },
   119380   { 208, 1 },
   119381   { 149, 12 },
   119382   { 230, 1 },
   119383   { 230, 0 },
   119384   { 179, 0 },
   119385   { 179, 3 },
   119386   { 188, 5 },
   119387   { 188, 3 },
   119388   { 231, 0 },
   119389   { 231, 2 },
   119390   { 149, 4 },
   119391   { 149, 1 },
   119392   { 149, 2 },
   119393   { 149, 3 },
   119394   { 149, 5 },
   119395   { 149, 6 },
   119396   { 149, 5 },
   119397   { 149, 6 },
   119398   { 232, 1 },
   119399   { 232, 1 },
   119400   { 232, 1 },
   119401   { 232, 1 },
   119402   { 232, 1 },
   119403   { 171, 2 },
   119404   { 171, 1 },
   119405   { 172, 2 },
   119406   { 149, 5 },
   119407   { 233, 11 },
   119408   { 235, 1 },
   119409   { 235, 1 },
   119410   { 235, 2 },
   119411   { 235, 0 },
   119412   { 236, 1 },
   119413   { 236, 1 },
   119414   { 236, 3 },
   119415   { 237, 0 },
   119416   { 237, 3 },
   119417   { 238, 0 },
   119418   { 238, 2 },
   119419   { 234, 3 },
   119420   { 234, 2 },
   119421   { 240, 1 },
   119422   { 240, 3 },
   119423   { 241, 0 },
   119424   { 241, 3 },
   119425   { 241, 2 },
   119426   { 239, 7 },
   119427   { 239, 5 },
   119428   { 239, 5 },
   119429   { 239, 1 },
   119430   { 175, 4 },
   119431   { 175, 6 },
   119432   { 192, 1 },
   119433   { 192, 1 },
   119434   { 192, 1 },
   119435   { 149, 4 },
   119436   { 149, 6 },
   119437   { 149, 3 },
   119438   { 243, 0 },
   119439   { 243, 2 },
   119440   { 242, 1 },
   119441   { 242, 0 },
   119442   { 149, 1 },
   119443   { 149, 3 },
   119444   { 149, 1 },
   119445   { 149, 3 },
   119446   { 149, 6 },
   119447   { 149, 6 },
   119448   { 244, 1 },
   119449   { 245, 0 },
   119450   { 245, 1 },
   119451   { 149, 1 },
   119452   { 149, 4 },
   119453   { 246, 8 },
   119454   { 247, 1 },
   119455   { 247, 3 },
   119456   { 248, 0 },
   119457   { 248, 2 },
   119458   { 249, 1 },
   119459   { 249, 3 },
   119460   { 250, 1 },
   119461   { 251, 0 },
   119462   { 251, 4 },
   119463   { 251, 2 },
   119464   { 197, 0 },
   119465   { 197, 2 },
   119466   { 197, 3 },
   119467   { 252, 6 },
   119468   { 252, 8 },
   119469 };
   119470 
   119471 static void yy_accept(yyParser*);  /* Forward Declaration */
   119472 
   119473 /*
   119474 ** Perform a reduce action and the shift that must immediately
   119475 ** follow the reduce.
   119476 */
   119477 static void yy_reduce(
   119478   yyParser *yypParser,         /* The parser */
   119479   int yyruleno                 /* Number of the rule by which to reduce */
   119480 ){
   119481   int yygoto;                     /* The next state */
   119482   int yyact;                      /* The next action */
   119483   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
   119484   yyStackEntry *yymsp;            /* The top of the parser's stack */
   119485   int yysize;                     /* Amount to pop the stack */
   119486   sqlite3ParserARG_FETCH;
   119487   yymsp = &yypParser->yystack[yypParser->yyidx];
   119488 #ifndef NDEBUG
   119489   if( yyTraceFILE && yyruleno>=0
   119490         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
   119491     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
   119492       yyRuleName[yyruleno]);
   119493   }
   119494 #endif /* NDEBUG */
   119495 
   119496   /* Silence complaints from purify about yygotominor being uninitialized
   119497   ** in some cases when it is copied into the stack after the following
   119498   ** switch.  yygotominor is uninitialized when a rule reduces that does
   119499   ** not set the value of its left-hand side nonterminal.  Leaving the
   119500   ** value of the nonterminal uninitialized is utterly harmless as long
   119501   ** as the value is never used.  So really the only thing this code
   119502   ** accomplishes is to quieten purify.
   119503   **
   119504   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
   119505   ** without this code, their parser segfaults.  I'm not sure what there
   119506   ** parser is doing to make this happen.  This is the second bug report
   119507   ** from wireshark this week.  Clearly they are stressing Lemon in ways
   119508   ** that it has not been previously stressed...  (SQLite ticket #2172)
   119509   */
   119510   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
   119511   yygotominor = yyzerominor;
   119512 
   119513 
   119514   switch( yyruleno ){
   119515   /* Beginning here are the reduction cases.  A typical example
   119516   ** follows:
   119517   **   case 0:
   119518   **  #line <lineno> <grammarfile>
   119519   **     { ... }           // User supplied code
   119520   **  #line <lineno> <thisfile>
   119521   **     break;
   119522   */
   119523       case 5: /* explain ::= */
   119524 { sqlite3BeginParse(pParse, 0); }
   119525         break;
   119526       case 6: /* explain ::= EXPLAIN */
   119527 { sqlite3BeginParse(pParse, 1); }
   119528         break;
   119529       case 7: /* explain ::= EXPLAIN QUERY PLAN */
   119530 { sqlite3BeginParse(pParse, 2); }
   119531         break;
   119532       case 8: /* cmdx ::= cmd */
   119533 { sqlite3FinishCoding(pParse); }
   119534         break;
   119535       case 9: /* cmd ::= BEGIN transtype trans_opt */
   119536 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
   119537         break;
   119538       case 13: /* transtype ::= */
   119539 {yygotominor.yy328 = TK_DEFERRED;}
   119540         break;
   119541       case 14: /* transtype ::= DEFERRED */
   119542       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
   119543       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
   119544       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
   119545       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
   119546 {yygotominor.yy328 = yymsp[0].major;}
   119547         break;
   119548       case 17: /* cmd ::= COMMIT trans_opt */
   119549       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
   119550 {sqlite3CommitTransaction(pParse);}
   119551         break;
   119552       case 19: /* cmd ::= ROLLBACK trans_opt */
   119553 {sqlite3RollbackTransaction(pParse);}
   119554         break;
   119555       case 22: /* cmd ::= SAVEPOINT nm */
   119556 {
   119557   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
   119558 }
   119559         break;
   119560       case 23: /* cmd ::= RELEASE savepoint_opt nm */
   119561 {
   119562   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
   119563 }
   119564         break;
   119565       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
   119566 {
   119567   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
   119568 }
   119569         break;
   119570       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
   119571 {
   119572    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
   119573 }
   119574         break;
   119575       case 27: /* createkw ::= CREATE */
   119576 {
   119577   pParse->db->lookaside.bEnabled = 0;
   119578   yygotominor.yy0 = yymsp[0].minor.yy0;
   119579 }
   119580         break;
   119581       case 28: /* ifnotexists ::= */
   119582       case 31: /* temp ::= */ yytestcase(yyruleno==31);
   119583       case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
   119584       case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
   119585       case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
   119586       case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
   119587       case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
   119588       case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
   119589       case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
   119590       case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
   119591 {yygotominor.yy328 = 0;}
   119592         break;
   119593       case 29: /* ifnotexists ::= IF NOT EXISTS */
   119594       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
   119595       case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
   119596       case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
   119597       case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
   119598       case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
   119599       case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
   119600 {yygotominor.yy328 = 1;}
   119601         break;
   119602       case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
   119603 {
   119604   sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
   119605 }
   119606         break;
   119607       case 33: /* create_table_args ::= AS select */
   119608 {
   119609   sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
   119610   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
   119611 }
   119612         break;
   119613       case 34: /* table_options ::= */
   119614 {yygotominor.yy186 = 0;}
   119615         break;
   119616       case 35: /* table_options ::= WITHOUT nm */
   119617 {
   119618   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
   119619     yygotominor.yy186 = TF_WithoutRowid;
   119620   }else{
   119621     yygotominor.yy186 = 0;
   119622     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
   119623   }
   119624 }
   119625         break;
   119626       case 38: /* column ::= columnid type carglist */
   119627 {
   119628   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
   119629   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
   119630 }
   119631         break;
   119632       case 39: /* columnid ::= nm */
   119633 {
   119634   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
   119635   yygotominor.yy0 = yymsp[0].minor.yy0;
   119636   pParse->constraintName.n = 0;
   119637 }
   119638         break;
   119639       case 40: /* nm ::= ID|INDEXED */
   119640       case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
   119641       case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
   119642       case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
   119643       case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
   119644       case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
   119645       case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
   119646       case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
   119647       case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
   119648       case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
   119649       case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
   119650       case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
   119651       case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
   119652       case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
   119653       case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
   119654       case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
   119655       case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
   119656       case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
   119657       case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
   119658 {yygotominor.yy0 = yymsp[0].minor.yy0;}
   119659         break;
   119660       case 44: /* type ::= typetoken */
   119661 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
   119662         break;
   119663       case 46: /* typetoken ::= typename LP signed RP */
   119664 {
   119665   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
   119666   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
   119667 }
   119668         break;
   119669       case 47: /* typetoken ::= typename LP signed COMMA signed RP */
   119670 {
   119671   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
   119672   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
   119673 }
   119674         break;
   119675       case 49: /* typename ::= typename ID|STRING */
   119676 {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);}
   119677         break;
   119678       case 54: /* ccons ::= CONSTRAINT nm */
   119679       case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
   119680 {pParse->constraintName = yymsp[0].minor.yy0;}
   119681         break;
   119682       case 55: /* ccons ::= DEFAULT term */
   119683       case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
   119684 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
   119685         break;
   119686       case 56: /* ccons ::= DEFAULT LP expr RP */
   119687 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
   119688         break;
   119689       case 58: /* ccons ::= DEFAULT MINUS term */
   119690 {
   119691   ExprSpan v;
   119692   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
   119693   v.zStart = yymsp[-1].minor.yy0.z;
   119694   v.zEnd = yymsp[0].minor.yy346.zEnd;
   119695   sqlite3AddDefaultValue(pParse,&v);
   119696 }
   119697         break;
   119698       case 59: /* ccons ::= DEFAULT ID|INDEXED */
   119699 {
   119700   ExprSpan v;
   119701   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
   119702   sqlite3AddDefaultValue(pParse,&v);
   119703 }
   119704         break;
   119705       case 61: /* ccons ::= NOT NULL onconf */
   119706 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
   119707         break;
   119708       case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
   119709 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
   119710         break;
   119711       case 63: /* ccons ::= UNIQUE onconf */
   119712 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
   119713         break;
   119714       case 64: /* ccons ::= CHECK LP expr RP */
   119715 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
   119716         break;
   119717       case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
   119718 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
   119719         break;
   119720       case 66: /* ccons ::= defer_subclause */
   119721 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
   119722         break;
   119723       case 67: /* ccons ::= COLLATE ID|STRING */
   119724 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
   119725         break;
   119726       case 70: /* refargs ::= */
   119727 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
   119728         break;
   119729       case 71: /* refargs ::= refargs refarg */
   119730 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
   119731         break;
   119732       case 72: /* refarg ::= MATCH nm */
   119733       case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
   119734 { yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
   119735         break;
   119736       case 74: /* refarg ::= ON DELETE refact */
   119737 { yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
   119738         break;
   119739       case 75: /* refarg ::= ON UPDATE refact */
   119740 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
   119741         break;
   119742       case 76: /* refact ::= SET NULL */
   119743 { yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
   119744         break;
   119745       case 77: /* refact ::= SET DEFAULT */
   119746 { yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
   119747         break;
   119748       case 78: /* refact ::= CASCADE */
   119749 { yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
   119750         break;
   119751       case 79: /* refact ::= RESTRICT */
   119752 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
   119753         break;
   119754       case 80: /* refact ::= NO ACTION */
   119755 { yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
   119756         break;
   119757       case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
   119758       case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
   119759       case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
   119760       case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
   119761 {yygotominor.yy328 = yymsp[0].minor.yy328;}
   119762         break;
   119763       case 86: /* conslist_opt ::= */
   119764 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
   119765         break;
   119766       case 87: /* conslist_opt ::= COMMA conslist */
   119767 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
   119768         break;
   119769       case 90: /* tconscomma ::= COMMA */
   119770 {pParse->constraintName.n = 0;}
   119771         break;
   119772       case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
   119773 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
   119774         break;
   119775       case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
   119776 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
   119777         break;
   119778       case 95: /* tcons ::= CHECK LP expr RP onconf */
   119779 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
   119780         break;
   119781       case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
   119782 {
   119783     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
   119784     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
   119785 }
   119786         break;
   119787       case 99: /* onconf ::= */
   119788 {yygotominor.yy328 = OE_Default;}
   119789         break;
   119790       case 101: /* orconf ::= */
   119791 {yygotominor.yy186 = OE_Default;}
   119792         break;
   119793       case 102: /* orconf ::= OR resolvetype */
   119794 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
   119795         break;
   119796       case 104: /* resolvetype ::= IGNORE */
   119797 {yygotominor.yy328 = OE_Ignore;}
   119798         break;
   119799       case 105: /* resolvetype ::= REPLACE */
   119800 {yygotominor.yy328 = OE_Replace;}
   119801         break;
   119802       case 106: /* cmd ::= DROP TABLE ifexists fullname */
   119803 {
   119804   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
   119805 }
   119806         break;
   119807       case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
   119808 {
   119809   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);
   119810 }
   119811         break;
   119812       case 110: /* cmd ::= DROP VIEW ifexists fullname */
   119813 {
   119814   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
   119815 }
   119816         break;
   119817       case 111: /* cmd ::= select */
   119818 {
   119819   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
   119820   sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
   119821   sqlite3ExplainBegin(pParse->pVdbe);
   119822   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy3);
   119823   sqlite3ExplainFinish(pParse->pVdbe);
   119824   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
   119825 }
   119826         break;
   119827       case 112: /* select ::= with selectnowith */
   119828 {
   119829   Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
   119830   if( p ){
   119831     int cnt = 0, mxSelect;
   119832     p->pWith = yymsp[-1].minor.yy59;
   119833     if( p->pPrior ){
   119834       pNext = 0;
   119835       for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
   119836         pLoop->pNext = pNext;
   119837         pLoop->selFlags |= SF_Compound;
   119838       }
   119839       mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
   119840       if( mxSelect && cnt>mxSelect ){
   119841         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
   119842       }
   119843     }
   119844   }else{
   119845     sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
   119846   }
   119847   yygotominor.yy3 = p;
   119848 }
   119849         break;
   119850       case 113: /* selectnowith ::= oneselect */
   119851       case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
   119852 {yygotominor.yy3 = yymsp[0].minor.yy3;}
   119853         break;
   119854       case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
   119855 {
   119856   Select *pRhs = yymsp[0].minor.yy3;
   119857   if( pRhs && pRhs->pPrior ){
   119858     SrcList *pFrom;
   119859     Token x;
   119860     x.n = 0;
   119861     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
   119862     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
   119863   }
   119864   if( pRhs ){
   119865     pRhs->op = (u8)yymsp[-1].minor.yy328;
   119866     pRhs->pPrior = yymsp[-2].minor.yy3;
   119867     if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
   119868   }else{
   119869     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
   119870   }
   119871   yygotominor.yy3 = pRhs;
   119872 }
   119873         break;
   119874       case 116: /* multiselect_op ::= UNION ALL */
   119875 {yygotominor.yy328 = TK_ALL;}
   119876         break;
   119877       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
   119878 {
   119879   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);
   119880 }
   119881         break;
   119882       case 120: /* values ::= VALUES LP nexprlist RP */
   119883 {
   119884   yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
   119885 }
   119886         break;
   119887       case 121: /* values ::= values COMMA LP exprlist RP */
   119888 {
   119889   Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
   119890   if( pRight ){
   119891     pRight->op = TK_ALL;
   119892     pRight->pPrior = yymsp[-4].minor.yy3;
   119893     yygotominor.yy3 = pRight;
   119894   }else{
   119895     yygotominor.yy3 = yymsp[-4].minor.yy3;
   119896   }
   119897 }
   119898         break;
   119899       case 122: /* distinct ::= DISTINCT */
   119900 {yygotominor.yy381 = SF_Distinct;}
   119901         break;
   119902       case 123: /* distinct ::= ALL */
   119903       case 124: /* distinct ::= */ yytestcase(yyruleno==124);
   119904 {yygotominor.yy381 = 0;}
   119905         break;
   119906       case 125: /* sclp ::= selcollist COMMA */
   119907       case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
   119908 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
   119909         break;
   119910       case 126: /* sclp ::= */
   119911       case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
   119912       case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
   119913       case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
   119914       case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
   119915 {yygotominor.yy14 = 0;}
   119916         break;
   119917       case 127: /* selcollist ::= sclp expr as */
   119918 {
   119919    yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
   119920    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
   119921    sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
   119922 }
   119923         break;
   119924       case 128: /* selcollist ::= sclp STAR */
   119925 {
   119926   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
   119927   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
   119928 }
   119929         break;
   119930       case 129: /* selcollist ::= sclp nm DOT STAR */
   119931 {
   119932   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
   119933   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   119934   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   119935   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
   119936 }
   119937         break;
   119938       case 132: /* as ::= */
   119939 {yygotominor.yy0.n = 0;}
   119940         break;
   119941       case 133: /* from ::= */
   119942 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
   119943         break;
   119944       case 134: /* from ::= FROM seltablist */
   119945 {
   119946   yygotominor.yy65 = yymsp[0].minor.yy65;
   119947   sqlite3SrcListShiftJoinType(yygotominor.yy65);
   119948 }
   119949         break;
   119950       case 135: /* stl_prefix ::= seltablist joinop */
   119951 {
   119952    yygotominor.yy65 = yymsp[-1].minor.yy65;
   119953    if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
   119954 }
   119955         break;
   119956       case 136: /* stl_prefix ::= */
   119957 {yygotominor.yy65 = 0;}
   119958         break;
   119959       case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
   119960 {
   119961   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);
   119962   sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
   119963 }
   119964         break;
   119965       case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
   119966 {
   119967     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);
   119968   }
   119969         break;
   119970       case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
   119971 {
   119972     if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
   119973       yygotominor.yy65 = yymsp[-4].minor.yy65;
   119974     }else if( yymsp[-4].minor.yy65->nSrc==1 ){
   119975       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
   119976       if( yygotominor.yy65 ){
   119977         struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
   119978         struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
   119979         pNew->zName = pOld->zName;
   119980         pNew->zDatabase = pOld->zDatabase;
   119981         pNew->pSelect = pOld->pSelect;
   119982         pOld->zName = pOld->zDatabase = 0;
   119983         pOld->pSelect = 0;
   119984       }
   119985       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
   119986     }else{
   119987       Select *pSubquery;
   119988       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
   119989       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
   119990       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
   119991     }
   119992   }
   119993         break;
   119994       case 140: /* dbnm ::= */
   119995       case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
   119996 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
   119997         break;
   119998       case 142: /* fullname ::= nm dbnm */
   119999 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
   120000         break;
   120001       case 143: /* joinop ::= COMMA|JOIN */
   120002 { yygotominor.yy328 = JT_INNER; }
   120003         break;
   120004       case 144: /* joinop ::= JOIN_KW JOIN */
   120005 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
   120006         break;
   120007       case 145: /* joinop ::= JOIN_KW nm JOIN */
   120008 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
   120009         break;
   120010       case 146: /* joinop ::= JOIN_KW nm nm JOIN */
   120011 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
   120012         break;
   120013       case 147: /* on_opt ::= ON expr */
   120014       case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
   120015       case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
   120016       case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
   120017       case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
   120018 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
   120019         break;
   120020       case 148: /* on_opt ::= */
   120021       case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
   120022       case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
   120023       case 232: /* case_else ::= */ yytestcase(yyruleno==232);
   120024       case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
   120025 {yygotominor.yy132 = 0;}
   120026         break;
   120027       case 151: /* indexed_opt ::= NOT INDEXED */
   120028 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
   120029         break;
   120030       case 152: /* using_opt ::= USING LP idlist RP */
   120031       case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
   120032 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
   120033         break;
   120034       case 153: /* using_opt ::= */
   120035       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
   120036 {yygotominor.yy408 = 0;}
   120037         break;
   120038       case 155: /* orderby_opt ::= ORDER BY sortlist */
   120039       case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
   120040       case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
   120041 {yygotominor.yy14 = yymsp[0].minor.yy14;}
   120042         break;
   120043       case 156: /* sortlist ::= sortlist COMMA expr sortorder */
   120044 {
   120045   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
   120046   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   120047 }
   120048         break;
   120049       case 157: /* sortlist ::= expr sortorder */
   120050 {
   120051   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
   120052   if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
   120053 }
   120054         break;
   120055       case 158: /* sortorder ::= ASC */
   120056       case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
   120057 {yygotominor.yy328 = SQLITE_SO_ASC;}
   120058         break;
   120059       case 159: /* sortorder ::= DESC */
   120060 {yygotominor.yy328 = SQLITE_SO_DESC;}
   120061         break;
   120062       case 165: /* limit_opt ::= */
   120063 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
   120064         break;
   120065       case 166: /* limit_opt ::= LIMIT expr */
   120066 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
   120067         break;
   120068       case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
   120069 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
   120070         break;
   120071       case 168: /* limit_opt ::= LIMIT expr COMMA expr */
   120072 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
   120073         break;
   120074       case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
   120075 {
   120076   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
   120077   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
   120078   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
   120079 }
   120080         break;
   120081       case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
   120082 {
   120083   sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
   120084   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
   120085   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
   120086   sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
   120087 }
   120088         break;
   120089       case 173: /* setlist ::= setlist COMMA nm EQ expr */
   120090 {
   120091   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
   120092   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   120093 }
   120094         break;
   120095       case 174: /* setlist ::= nm EQ expr */
   120096 {
   120097   yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
   120098   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   120099 }
   120100         break;
   120101       case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
   120102 {
   120103   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
   120104   sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
   120105 }
   120106         break;
   120107       case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
   120108 {
   120109   sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
   120110   sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
   120111 }
   120112         break;
   120113       case 177: /* insert_cmd ::= INSERT orconf */
   120114 {yygotominor.yy186 = yymsp[0].minor.yy186;}
   120115         break;
   120116       case 178: /* insert_cmd ::= REPLACE */
   120117 {yygotominor.yy186 = OE_Replace;}
   120118         break;
   120119       case 181: /* idlist ::= idlist COMMA nm */
   120120 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
   120121         break;
   120122       case 182: /* idlist ::= nm */
   120123 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
   120124         break;
   120125       case 183: /* expr ::= term */
   120126 {yygotominor.yy346 = yymsp[0].minor.yy346;}
   120127         break;
   120128       case 184: /* expr ::= LP expr RP */
   120129 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
   120130         break;
   120131       case 185: /* term ::= NULL */
   120132       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
   120133       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
   120134 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
   120135         break;
   120136       case 186: /* expr ::= ID|INDEXED */
   120137       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
   120138 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
   120139         break;
   120140       case 188: /* expr ::= nm DOT nm */
   120141 {
   120142   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   120143   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   120144   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
   120145   spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
   120146 }
   120147         break;
   120148       case 189: /* expr ::= nm DOT nm DOT nm */
   120149 {
   120150   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
   120151   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   120152   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   120153   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
   120154   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
   120155   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   120156 }
   120157         break;
   120158       case 192: /* expr ::= VARIABLE */
   120159 {
   120160   if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
   120161     /* When doing a nested parse, one can include terms in an expression
   120162     ** that look like this:   #1 #2 ...  These terms refer to registers
   120163     ** in the virtual machine.  #N is the N-th register. */
   120164     if( pParse->nested==0 ){
   120165       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
   120166       yygotominor.yy346.pExpr = 0;
   120167     }else{
   120168       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
   120169       if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
   120170     }
   120171   }else{
   120172     spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
   120173     sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
   120174   }
   120175   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   120176 }
   120177         break;
   120178       case 193: /* expr ::= expr COLLATE ID|STRING */
   120179 {
   120180   yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
   120181   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
   120182   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120183 }
   120184         break;
   120185       case 194: /* expr ::= CAST LP expr AS typetoken RP */
   120186 {
   120187   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
   120188   spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
   120189 }
   120190         break;
   120191       case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
   120192 {
   120193   if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
   120194     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
   120195   }
   120196   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
   120197   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   120198   if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
   120199     yygotominor.yy346.pExpr->flags |= EP_Distinct;
   120200   }
   120201 }
   120202         break;
   120203       case 196: /* expr ::= ID|INDEXED LP STAR RP */
   120204 {
   120205   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
   120206   spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
   120207 }
   120208         break;
   120209       case 197: /* term ::= CTIME_KW */
   120210 {
   120211   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
   120212   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   120213 }
   120214         break;
   120215       case 198: /* expr ::= expr AND expr */
   120216       case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
   120217       case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
   120218       case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
   120219       case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
   120220       case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
   120221       case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
   120222       case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
   120223 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
   120224         break;
   120225       case 206: /* likeop ::= LIKE_KW|MATCH */
   120226 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
   120227         break;
   120228       case 207: /* likeop ::= NOT LIKE_KW|MATCH */
   120229 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
   120230         break;
   120231       case 208: /* expr ::= expr likeop expr */
   120232 {
   120233   ExprList *pList;
   120234   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
   120235   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
   120236   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
   120237   if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120238   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
   120239   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
   120240   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
   120241 }
   120242         break;
   120243       case 209: /* expr ::= expr likeop expr ESCAPE expr */
   120244 {
   120245   ExprList *pList;
   120246   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
   120247   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
   120248   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
   120249   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
   120250   if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120251   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   120252   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
   120253   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
   120254 }
   120255         break;
   120256       case 210: /* expr ::= expr ISNULL|NOTNULL */
   120257 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
   120258         break;
   120259       case 211: /* expr ::= expr NOT NULL */
   120260 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
   120261         break;
   120262       case 212: /* expr ::= expr IS expr */
   120263 {
   120264   spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
   120265   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
   120266 }
   120267         break;
   120268       case 213: /* expr ::= expr IS NOT expr */
   120269 {
   120270   spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
   120271   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
   120272 }
   120273         break;
   120274       case 214: /* expr ::= NOT expr */
   120275       case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
   120276 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   120277         break;
   120278       case 216: /* expr ::= MINUS expr */
   120279 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   120280         break;
   120281       case 217: /* expr ::= PLUS expr */
   120282 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   120283         break;
   120284       case 220: /* expr ::= expr between_op expr AND expr */
   120285 {
   120286   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
   120287   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
   120288   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   120289   if( yygotominor.yy346.pExpr ){
   120290     yygotominor.yy346.pExpr->x.pList = pList;
   120291   }else{
   120292     sqlite3ExprListDelete(pParse->db, pList);
   120293   }
   120294   if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120295   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   120296   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
   120297 }
   120298         break;
   120299       case 223: /* expr ::= expr in_op LP exprlist RP */
   120300 {
   120301     if( yymsp[-1].minor.yy14==0 ){
   120302       /* Expressions of the form
   120303       **
   120304       **      expr1 IN ()
   120305       **      expr1 NOT IN ()
   120306       **
   120307       ** simplify to constants 0 (false) and 1 (true), respectively,
   120308       ** regardless of the value of expr1.
   120309       */
   120310       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
   120311       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
   120312     }else if( yymsp[-1].minor.yy14->nExpr==1 ){
   120313       /* Expressions of the form:
   120314       **
   120315       **      expr1 IN (?1)
   120316       **      expr1 NOT IN (?2)
   120317       **
   120318       ** with exactly one value on the RHS can be simplified to something
   120319       ** like this:
   120320       **
   120321       **      expr1 == ?1
   120322       **      expr1 <> ?2
   120323       **
   120324       ** But, the RHS of the == or <> is marked with the EP_Generic flag
   120325       ** so that it may not contribute to the computation of comparison
   120326       ** affinity or the collating sequence to use for comparison.  Otherwise,
   120327       ** the semantics would be subtly different from IN or NOT IN.
   120328       */
   120329       Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
   120330       yymsp[-1].minor.yy14->a[0].pExpr = 0;
   120331       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
   120332       /* pRHS cannot be NULL because a malloc error would have been detected
   120333       ** before now and control would have never reached this point */
   120334       if( ALWAYS(pRHS) ){
   120335         pRHS->flags &= ~EP_Collate;
   120336         pRHS->flags |= EP_Generic;
   120337       }
   120338       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
   120339     }else{
   120340       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   120341       if( yygotominor.yy346.pExpr ){
   120342         yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
   120343         sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120344       }else{
   120345         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
   120346       }
   120347       if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120348     }
   120349     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   120350     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120351   }
   120352         break;
   120353       case 224: /* expr ::= LP select RP */
   120354 {
   120355     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
   120356     if( yygotominor.yy346.pExpr ){
   120357       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
   120358       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   120359       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120360     }else{
   120361       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   120362     }
   120363     yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
   120364     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120365   }
   120366         break;
   120367       case 225: /* expr ::= expr in_op LP select RP */
   120368 {
   120369     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   120370     if( yygotominor.yy346.pExpr ){
   120371       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
   120372       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   120373       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120374     }else{
   120375       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   120376     }
   120377     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120378     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   120379     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120380   }
   120381         break;
   120382       case 226: /* expr ::= expr in_op nm dbnm */
   120383 {
   120384     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
   120385     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
   120386     if( yygotominor.yy346.pExpr ){
   120387       yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
   120388       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   120389       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120390     }else{
   120391       sqlite3SrcListDelete(pParse->db, pSrc);
   120392     }
   120393     if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   120394     yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
   120395     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];
   120396   }
   120397         break;
   120398       case 227: /* expr ::= EXISTS LP select RP */
   120399 {
   120400     Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
   120401     if( p ){
   120402       p->x.pSelect = yymsp[-1].minor.yy3;
   120403       ExprSetProperty(p, EP_xIsSelect);
   120404       sqlite3ExprSetHeight(pParse, p);
   120405     }else{
   120406       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   120407     }
   120408     yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
   120409     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120410   }
   120411         break;
   120412       case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
   120413 {
   120414   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
   120415   if( yygotominor.yy346.pExpr ){
   120416     yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
   120417     sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   120418   }else{
   120419     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
   120420     sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
   120421   }
   120422   yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
   120423   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120424 }
   120425         break;
   120426       case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
   120427 {
   120428   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
   120429   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
   120430 }
   120431         break;
   120432       case 230: /* case_exprlist ::= WHEN expr THEN expr */
   120433 {
   120434   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
   120435   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
   120436 }
   120437         break;
   120438       case 237: /* nexprlist ::= nexprlist COMMA expr */
   120439 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
   120440         break;
   120441       case 238: /* nexprlist ::= expr */
   120442 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
   120443         break;
   120444       case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
   120445 {
   120446   sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
   120447                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
   120448                       &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
   120449 }
   120450         break;
   120451       case 240: /* uniqueflag ::= UNIQUE */
   120452       case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
   120453 {yygotominor.yy328 = OE_Abort;}
   120454         break;
   120455       case 241: /* uniqueflag ::= */
   120456 {yygotominor.yy328 = OE_None;}
   120457         break;
   120458       case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
   120459 {
   120460   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
   120461   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
   120462   sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
   120463   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
   120464   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   120465 }
   120466         break;
   120467       case 245: /* idxlist ::= nm collate sortorder */
   120468 {
   120469   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
   120470   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
   120471   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   120472   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
   120473   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   120474 }
   120475         break;
   120476       case 246: /* collate ::= */
   120477 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
   120478         break;
   120479       case 248: /* cmd ::= DROP INDEX ifexists fullname */
   120480 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
   120481         break;
   120482       case 249: /* cmd ::= VACUUM */
   120483       case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
   120484 {sqlite3Vacuum(pParse);}
   120485         break;
   120486       case 251: /* cmd ::= PRAGMA nm dbnm */
   120487 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
   120488         break;
   120489       case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
   120490 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
   120491         break;
   120492       case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
   120493 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
   120494         break;
   120495       case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
   120496 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
   120497         break;
   120498       case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
   120499 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
   120500         break;
   120501       case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   120502 {
   120503   Token all;
   120504   all.z = yymsp[-3].minor.yy0.z;
   120505   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
   120506   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
   120507 }
   120508         break;
   120509       case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   120510 {
   120511   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);
   120512   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
   120513 }
   120514         break;
   120515       case 266: /* trigger_time ::= BEFORE */
   120516       case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
   120517 { yygotominor.yy328 = TK_BEFORE; }
   120518         break;
   120519       case 267: /* trigger_time ::= AFTER */
   120520 { yygotominor.yy328 = TK_AFTER;  }
   120521         break;
   120522       case 268: /* trigger_time ::= INSTEAD OF */
   120523 { yygotominor.yy328 = TK_INSTEAD;}
   120524         break;
   120525       case 270: /* trigger_event ::= DELETE|INSERT */
   120526       case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
   120527 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
   120528         break;
   120529       case 272: /* trigger_event ::= UPDATE OF idlist */
   120530 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
   120531         break;
   120532       case 275: /* when_clause ::= */
   120533       case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
   120534 { yygotominor.yy132 = 0; }
   120535         break;
   120536       case 276: /* when_clause ::= WHEN expr */
   120537       case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
   120538 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
   120539         break;
   120540       case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   120541 {
   120542   assert( yymsp[-2].minor.yy473!=0 );
   120543   yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
   120544   yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
   120545   yygotominor.yy473 = yymsp[-2].minor.yy473;
   120546 }
   120547         break;
   120548       case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
   120549 {
   120550   assert( yymsp[-1].minor.yy473!=0 );
   120551   yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
   120552   yygotominor.yy473 = yymsp[-1].minor.yy473;
   120553 }
   120554         break;
   120555       case 280: /* trnm ::= nm DOT nm */
   120556 {
   120557   yygotominor.yy0 = yymsp[0].minor.yy0;
   120558   sqlite3ErrorMsg(pParse,
   120559         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
   120560         "statements within triggers");
   120561 }
   120562         break;
   120563       case 282: /* tridxby ::= INDEXED BY nm */
   120564 {
   120565   sqlite3ErrorMsg(pParse,
   120566         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
   120567         "within triggers");
   120568 }
   120569         break;
   120570       case 283: /* tridxby ::= NOT INDEXED */
   120571 {
   120572   sqlite3ErrorMsg(pParse,
   120573         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
   120574         "within triggers");
   120575 }
   120576         break;
   120577       case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
   120578 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
   120579         break;
   120580       case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
   120581 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
   120582         break;
   120583       case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
   120584 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
   120585         break;
   120586       case 287: /* trigger_cmd ::= select */
   120587 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
   120588         break;
   120589       case 288: /* expr ::= RAISE LP IGNORE RP */
   120590 {
   120591   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
   120592   if( yygotominor.yy346.pExpr ){
   120593     yygotominor.yy346.pExpr->affinity = OE_Ignore;
   120594   }
   120595   yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
   120596   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120597 }
   120598         break;
   120599       case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
   120600 {
   120601   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
   120602   if( yygotominor.yy346.pExpr ) {
   120603     yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
   120604   }
   120605   yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
   120606   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   120607 }
   120608         break;
   120609       case 290: /* raisetype ::= ROLLBACK */
   120610 {yygotominor.yy328 = OE_Rollback;}
   120611         break;
   120612       case 292: /* raisetype ::= FAIL */
   120613 {yygotominor.yy328 = OE_Fail;}
   120614         break;
   120615       case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
   120616 {
   120617   sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
   120618 }
   120619         break;
   120620       case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   120621 {
   120622   sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
   120623 }
   120624         break;
   120625       case 295: /* cmd ::= DETACH database_kw_opt expr */
   120626 {
   120627   sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
   120628 }
   120629         break;
   120630       case 300: /* cmd ::= REINDEX */
   120631 {sqlite3Reindex(pParse, 0, 0);}
   120632         break;
   120633       case 301: /* cmd ::= REINDEX nm dbnm */
   120634 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   120635         break;
   120636       case 302: /* cmd ::= ANALYZE */
   120637 {sqlite3Analyze(pParse, 0, 0);}
   120638         break;
   120639       case 303: /* cmd ::= ANALYZE nm dbnm */
   120640 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   120641         break;
   120642       case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
   120643 {
   120644   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
   120645 }
   120646         break;
   120647       case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
   120648 {
   120649   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
   120650 }
   120651         break;
   120652       case 306: /* add_column_fullname ::= fullname */
   120653 {
   120654   pParse->db->lookaside.bEnabled = 0;
   120655   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
   120656 }
   120657         break;
   120658       case 309: /* cmd ::= create_vtab */
   120659 {sqlite3VtabFinishParse(pParse,0);}
   120660         break;
   120661       case 310: /* cmd ::= create_vtab LP vtabarglist RP */
   120662 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
   120663         break;
   120664       case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
   120665 {
   120666     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
   120667 }
   120668         break;
   120669       case 314: /* vtabarg ::= */
   120670 {sqlite3VtabArgInit(pParse);}
   120671         break;
   120672       case 316: /* vtabargtoken ::= ANY */
   120673       case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
   120674       case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
   120675 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
   120676         break;
   120677       case 322: /* with ::= */
   120678 {yygotominor.yy59 = 0;}
   120679         break;
   120680       case 323: /* with ::= WITH wqlist */
   120681       case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
   120682 { yygotominor.yy59 = yymsp[0].minor.yy59; }
   120683         break;
   120684       case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
   120685 {
   120686   yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
   120687 }
   120688         break;
   120689       case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
   120690 {
   120691   yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
   120692 }
   120693         break;
   120694       default:
   120695       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
   120696       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
   120697       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
   120698       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
   120699       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
   120700       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
   120701       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
   120702       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
   120703       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
   120704       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
   120705       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
   120706       /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
   120707       /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
   120708       /* (43) type ::= */ yytestcase(yyruleno==43);
   120709       /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
   120710       /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
   120711       /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
   120712       /* (53) carglist ::= */ yytestcase(yyruleno==53);
   120713       /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
   120714       /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
   120715       /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
   120716       /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
   120717       /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
   120718       /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
   120719       /* (281) tridxby ::= */ yytestcase(yyruleno==281);
   120720       /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
   120721       /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
   120722       /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
   120723       /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
   120724       /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
   120725       /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
   120726       /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
   120727       /* (319) anylist ::= */ yytestcase(yyruleno==319);
   120728       /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
   120729       /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
   120730         break;
   120731   };
   120732   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
   120733   yygoto = yyRuleInfo[yyruleno].lhs;
   120734   yysize = yyRuleInfo[yyruleno].nrhs;
   120735   yypParser->yyidx -= yysize;
   120736   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
   120737   if( yyact < YYNSTATE ){
   120738 #ifdef NDEBUG
   120739     /* If we are not debugging and the reduce action popped at least
   120740     ** one element off the stack, then we can push the new element back
   120741     ** onto the stack here, and skip the stack overflow test in yy_shift().
   120742     ** That gives a significant speed improvement. */
   120743     if( yysize ){
   120744       yypParser->yyidx++;
   120745       yymsp -= yysize-1;
   120746       yymsp->stateno = (YYACTIONTYPE)yyact;
   120747       yymsp->major = (YYCODETYPE)yygoto;
   120748       yymsp->minor = yygotominor;
   120749     }else
   120750 #endif
   120751     {
   120752       yy_shift(yypParser,yyact,yygoto,&yygotominor);
   120753     }
   120754   }else{
   120755     assert( yyact == YYNSTATE + YYNRULE + 1 );
   120756     yy_accept(yypParser);
   120757   }
   120758 }
   120759 
   120760 /*
   120761 ** The following code executes when the parse fails
   120762 */
   120763 #ifndef YYNOERRORRECOVERY
   120764 static void yy_parse_failed(
   120765   yyParser *yypParser           /* The parser */
   120766 ){
   120767   sqlite3ParserARG_FETCH;
   120768 #ifndef NDEBUG
   120769   if( yyTraceFILE ){
   120770     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
   120771   }
   120772 #endif
   120773   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   120774   /* Here code is inserted which will be executed whenever the
   120775   ** parser fails */
   120776   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   120777 }
   120778 #endif /* YYNOERRORRECOVERY */
   120779 
   120780 /*
   120781 ** The following code executes when a syntax error first occurs.
   120782 */
   120783 static void yy_syntax_error(
   120784   yyParser *yypParser,           /* The parser */
   120785   int yymajor,                   /* The major type of the error token */
   120786   YYMINORTYPE yyminor            /* The minor type of the error token */
   120787 ){
   120788   sqlite3ParserARG_FETCH;
   120789 #define TOKEN (yyminor.yy0)
   120790 
   120791   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
   120792   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
   120793   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
   120794   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   120795 }
   120796 
   120797 /*
   120798 ** The following is executed when the parser accepts
   120799 */
   120800 static void yy_accept(
   120801   yyParser *yypParser           /* The parser */
   120802 ){
   120803   sqlite3ParserARG_FETCH;
   120804 #ifndef NDEBUG
   120805   if( yyTraceFILE ){
   120806     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
   120807   }
   120808 #endif
   120809   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   120810   /* Here code is inserted which will be executed whenever the
   120811   ** parser accepts */
   120812   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   120813 }
   120814 
   120815 /* The main parser program.
   120816 ** The first argument is a pointer to a structure obtained from
   120817 ** "sqlite3ParserAlloc" which describes the current state of the parser.
   120818 ** The second argument is the major token number.  The third is
   120819 ** the minor token.  The fourth optional argument is whatever the
   120820 ** user wants (and specified in the grammar) and is available for
   120821 ** use by the action routines.
   120822 **
   120823 ** Inputs:
   120824 ** <ul>
   120825 ** <li> A pointer to the parser (an opaque structure.)
   120826 ** <li> The major token number.
   120827 ** <li> The minor token number.
   120828 ** <li> An option argument of a grammar-specified type.
   120829 ** </ul>
   120830 **
   120831 ** Outputs:
   120832 ** None.
   120833 */
   120834 SQLITE_PRIVATE void sqlite3Parser(
   120835   void *yyp,                   /* The parser */
   120836   int yymajor,                 /* The major token code number */
   120837   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
   120838   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
   120839 ){
   120840   YYMINORTYPE yyminorunion;
   120841   int yyact;            /* The parser action. */
   120842 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   120843   int yyendofinput;     /* True if we are at the end of input */
   120844 #endif
   120845 #ifdef YYERRORSYMBOL
   120846   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
   120847 #endif
   120848   yyParser *yypParser;  /* The parser */
   120849 
   120850   /* (re)initialize the parser, if necessary */
   120851   yypParser = (yyParser*)yyp;
   120852   if( yypParser->yyidx<0 ){
   120853 #if YYSTACKDEPTH<=0
   120854     if( yypParser->yystksz <=0 ){
   120855       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
   120856       yyminorunion = yyzerominor;
   120857       yyStackOverflow(yypParser, &yyminorunion);
   120858       return;
   120859     }
   120860 #endif
   120861     yypParser->yyidx = 0;
   120862     yypParser->yyerrcnt = -1;
   120863     yypParser->yystack[0].stateno = 0;
   120864     yypParser->yystack[0].major = 0;
   120865   }
   120866   yyminorunion.yy0 = yyminor;
   120867 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   120868   yyendofinput = (yymajor==0);
   120869 #endif
   120870   sqlite3ParserARG_STORE;
   120871 
   120872 #ifndef NDEBUG
   120873   if( yyTraceFILE ){
   120874     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
   120875   }
   120876 #endif
   120877 
   120878   do{
   120879     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
   120880     if( yyact<YYNSTATE ){
   120881       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
   120882       yypParser->yyerrcnt--;
   120883       yymajor = YYNOCODE;
   120884     }else if( yyact < YYNSTATE + YYNRULE ){
   120885       yy_reduce(yypParser,yyact-YYNSTATE);
   120886     }else{
   120887       assert( yyact == YY_ERROR_ACTION );
   120888 #ifdef YYERRORSYMBOL
   120889       int yymx;
   120890 #endif
   120891 #ifndef NDEBUG
   120892       if( yyTraceFILE ){
   120893         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
   120894       }
   120895 #endif
   120896 #ifdef YYERRORSYMBOL
   120897       /* A syntax error has occurred.
   120898       ** The response to an error depends upon whether or not the
   120899       ** grammar defines an error token "ERROR".
   120900       **
   120901       ** This is what we do if the grammar does define ERROR:
   120902       **
   120903       **  * Call the %syntax_error function.
   120904       **
   120905       **  * Begin popping the stack until we enter a state where
   120906       **    it is legal to shift the error symbol, then shift
   120907       **    the error symbol.
   120908       **
   120909       **  * Set the error count to three.
   120910       **
   120911       **  * Begin accepting and shifting new tokens.  No new error
   120912       **    processing will occur until three tokens have been
   120913       **    shifted successfully.
   120914       **
   120915       */
   120916       if( yypParser->yyerrcnt<0 ){
   120917         yy_syntax_error(yypParser,yymajor,yyminorunion);
   120918       }
   120919       yymx = yypParser->yystack[yypParser->yyidx].major;
   120920       if( yymx==YYERRORSYMBOL || yyerrorhit ){
   120921 #ifndef NDEBUG
   120922         if( yyTraceFILE ){
   120923           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
   120924              yyTracePrompt,yyTokenName[yymajor]);
   120925         }
   120926 #endif
   120927         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
   120928         yymajor = YYNOCODE;
   120929       }else{
   120930          while(
   120931           yypParser->yyidx >= 0 &&
   120932           yymx != YYERRORSYMBOL &&
   120933           (yyact = yy_find_reduce_action(
   120934                         yypParser->yystack[yypParser->yyidx].stateno,
   120935                         YYERRORSYMBOL)) >= YYNSTATE
   120936         ){
   120937           yy_pop_parser_stack(yypParser);
   120938         }
   120939         if( yypParser->yyidx < 0 || yymajor==0 ){
   120940           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   120941           yy_parse_failed(yypParser);
   120942           yymajor = YYNOCODE;
   120943         }else if( yymx!=YYERRORSYMBOL ){
   120944           YYMINORTYPE u2;
   120945           u2.YYERRSYMDT = 0;
   120946           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
   120947         }
   120948       }
   120949       yypParser->yyerrcnt = 3;
   120950       yyerrorhit = 1;
   120951 #elif defined(YYNOERRORRECOVERY)
   120952       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
   120953       ** do any kind of error recovery.  Instead, simply invoke the syntax
   120954       ** error routine and continue going as if nothing had happened.
   120955       **
   120956       ** Applications can set this macro (for example inside %include) if
   120957       ** they intend to abandon the parse upon the first syntax error seen.
   120958       */
   120959       yy_syntax_error(yypParser,yymajor,yyminorunion);
   120960       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   120961       yymajor = YYNOCODE;
   120962 
   120963 #else  /* YYERRORSYMBOL is not defined */
   120964       /* This is what we do if the grammar does not define ERROR:
   120965       **
   120966       **  * Report an error message, and throw away the input token.
   120967       **
   120968       **  * If the input token is $, then fail the parse.
   120969       **
   120970       ** As before, subsequent error messages are suppressed until
   120971       ** three input tokens have been successfully shifted.
   120972       */
   120973       if( yypParser->yyerrcnt<=0 ){
   120974         yy_syntax_error(yypParser,yymajor,yyminorunion);
   120975       }
   120976       yypParser->yyerrcnt = 3;
   120977       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   120978       if( yyendofinput ){
   120979         yy_parse_failed(yypParser);
   120980       }
   120981       yymajor = YYNOCODE;
   120982 #endif
   120983     }
   120984   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
   120985   return;
   120986 }
   120987 
   120988 /************** End of parse.c ***********************************************/
   120989 /************** Begin file tokenize.c ****************************************/
   120990 /*
   120991 ** 2001 September 15
   120992 **
   120993 ** The author disclaims copyright to this source code.  In place of
   120994 ** a legal notice, here is a blessing:
   120995 **
   120996 **    May you do good and not evil.
   120997 **    May you find forgiveness for yourself and forgive others.
   120998 **    May you share freely, never taking more than you give.
   120999 **
   121000 *************************************************************************
   121001 ** An tokenizer for SQL
   121002 **
   121003 ** This file contains C code that splits an SQL input string up into
   121004 ** individual tokens and sends those tokens one-by-one over to the
   121005 ** parser for analysis.
   121006 */
   121007 /* #include <stdlib.h> */
   121008 
   121009 /*
   121010 ** The charMap() macro maps alphabetic characters into their
   121011 ** lower-case ASCII equivalent.  On ASCII machines, this is just
   121012 ** an upper-to-lower case map.  On EBCDIC machines we also need
   121013 ** to adjust the encoding.  Only alphabetic characters and underscores
   121014 ** need to be translated.
   121015 */
   121016 #ifdef SQLITE_ASCII
   121017 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
   121018 #endif
   121019 #ifdef SQLITE_EBCDIC
   121020 # define charMap(X) ebcdicToAscii[(unsigned char)X]
   121021 const unsigned char ebcdicToAscii[] = {
   121022 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
   121023    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
   121024    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
   121025    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
   121026    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
   121027    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
   121028    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
   121029    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
   121030    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
   121031    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
   121032    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
   121033    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
   121034    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
   121035    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
   121036    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
   121037    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
   121038    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
   121039 };
   121040 #endif
   121041 
   121042 /*
   121043 ** The sqlite3KeywordCode function looks up an identifier to determine if
   121044 ** it is a keyword.  If it is a keyword, the token code of that keyword is
   121045 ** returned.  If the input is not a keyword, TK_ID is returned.
   121046 **
   121047 ** The implementation of this routine was generated by a program,
   121048 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
   121049 ** The output of the mkkeywordhash.c program is written into a file
   121050 ** named keywordhash.h and then included into this source file by
   121051 ** the #include below.
   121052 */
   121053 /************** Include keywordhash.h in the middle of tokenize.c ************/
   121054 /************** Begin file keywordhash.h *************************************/
   121055 /***** This file contains automatically generated code ******
   121056 **
   121057 ** The code in this file has been automatically generated by
   121058 **
   121059 **   sqlite/tool/mkkeywordhash.c
   121060 **
   121061 ** The code in this file implements a function that determines whether
   121062 ** or not a given identifier is really an SQL keyword.  The same thing
   121063 ** might be implemented more directly using a hand-written hash table.
   121064 ** But by using this automatically generated code, the size of the code
   121065 ** is substantially reduced.  This is important for embedded applications
   121066 ** on platforms with limited memory.
   121067 */
   121068 /* Hash score: 182 */
   121069 static int keywordCode(const char *z, int n){
   121070   /* zText[] encodes 834 bytes of keywords in 554 bytes */
   121071   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
   121072   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
   121073   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
   121074   /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
   121075   /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
   121076   /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
   121077   /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
   121078   /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
   121079   /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
   121080   /*   VACUUMVIEWINITIALLY                                                */
   121081   static const char zText[553] = {
   121082     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
   121083     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
   121084     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
   121085     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
   121086     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
   121087     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
   121088     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
   121089     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
   121090     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
   121091     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
   121092     'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
   121093     'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
   121094     'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
   121095     'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
   121096     'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
   121097     'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
   121098     'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
   121099     'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
   121100     'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
   121101     'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
   121102     'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
   121103     'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
   121104     'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
   121105     'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
   121106     'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
   121107     'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
   121108     'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
   121109     'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
   121110     'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
   121111     'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
   121112     'V','I','E','W','I','N','I','T','I','A','L','L','Y',
   121113   };
   121114   static const unsigned char aHash[127] = {
   121115       76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
   121116       42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
   121117      121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
   121118        0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
   121119        0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
   121120       96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
   121121      100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
   121122       39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
   121123       62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
   121124       29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
   121125   };
   121126   static const unsigned char aNext[124] = {
   121127        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
   121128        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
   121129        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
   121130        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
   121131        0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
   121132        0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
   121133        0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
   121134       10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
   121135        0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
   121136       73,  83,   0,  35,  68,   0,   0,
   121137   };
   121138   static const unsigned char aLen[124] = {
   121139        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
   121140        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
   121141       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
   121142        4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
   121143        6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
   121144        7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
   121145        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
   121146       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
   121147        2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
   121148        3,   5,   5,   6,   4,   9,   3,
   121149   };
   121150   static const unsigned short int aOffset[124] = {
   121151        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
   121152       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
   121153       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
   121154      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
   121155      199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
   121156      250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
   121157      320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
   121158      387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
   121159      460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
   121160      521, 524, 529, 534, 540, 544, 549,
   121161   };
   121162   static const unsigned char aCode[124] = {
   121163     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
   121164     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
   121165     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
   121166     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
   121167     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
   121168     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
   121169     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
   121170     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
   121171     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
   121172     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
   121173     TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
   121174     TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
   121175     TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
   121176     TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
   121177     TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
   121178     TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
   121179     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
   121180     TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
   121181     TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
   121182     TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
   121183     TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
   121184     TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
   121185     TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
   121186     TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
   121187     TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
   121188   };
   121189   int h, i;
   121190   if( n<2 ) return TK_ID;
   121191   h = ((charMap(z[0])*4) ^
   121192       (charMap(z[n-1])*3) ^
   121193       n) % 127;
   121194   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
   121195     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
   121196       testcase( i==0 ); /* REINDEX */
   121197       testcase( i==1 ); /* INDEXED */
   121198       testcase( i==2 ); /* INDEX */
   121199       testcase( i==3 ); /* DESC */
   121200       testcase( i==4 ); /* ESCAPE */
   121201       testcase( i==5 ); /* EACH */
   121202       testcase( i==6 ); /* CHECK */
   121203       testcase( i==7 ); /* KEY */
   121204       testcase( i==8 ); /* BEFORE */
   121205       testcase( i==9 ); /* FOREIGN */
   121206       testcase( i==10 ); /* FOR */
   121207       testcase( i==11 ); /* IGNORE */
   121208       testcase( i==12 ); /* REGEXP */
   121209       testcase( i==13 ); /* EXPLAIN */
   121210       testcase( i==14 ); /* INSTEAD */
   121211       testcase( i==15 ); /* ADD */
   121212       testcase( i==16 ); /* DATABASE */
   121213       testcase( i==17 ); /* AS */
   121214       testcase( i==18 ); /* SELECT */
   121215       testcase( i==19 ); /* TABLE */
   121216       testcase( i==20 ); /* LEFT */
   121217       testcase( i==21 ); /* THEN */
   121218       testcase( i==22 ); /* END */
   121219       testcase( i==23 ); /* DEFERRABLE */
   121220       testcase( i==24 ); /* ELSE */
   121221       testcase( i==25 ); /* EXCEPT */
   121222       testcase( i==26 ); /* TRANSACTION */
   121223       testcase( i==27 ); /* ACTION */
   121224       testcase( i==28 ); /* ON */
   121225       testcase( i==29 ); /* NATURAL */
   121226       testcase( i==30 ); /* ALTER */
   121227       testcase( i==31 ); /* RAISE */
   121228       testcase( i==32 ); /* EXCLUSIVE */
   121229       testcase( i==33 ); /* EXISTS */
   121230       testcase( i==34 ); /* SAVEPOINT */
   121231       testcase( i==35 ); /* INTERSECT */
   121232       testcase( i==36 ); /* TRIGGER */
   121233       testcase( i==37 ); /* REFERENCES */
   121234       testcase( i==38 ); /* CONSTRAINT */
   121235       testcase( i==39 ); /* INTO */
   121236       testcase( i==40 ); /* OFFSET */
   121237       testcase( i==41 ); /* OF */
   121238       testcase( i==42 ); /* SET */
   121239       testcase( i==43 ); /* TEMPORARY */
   121240       testcase( i==44 ); /* TEMP */
   121241       testcase( i==45 ); /* OR */
   121242       testcase( i==46 ); /* UNIQUE */
   121243       testcase( i==47 ); /* QUERY */
   121244       testcase( i==48 ); /* WITHOUT */
   121245       testcase( i==49 ); /* WITH */
   121246       testcase( i==50 ); /* OUTER */
   121247       testcase( i==51 ); /* RELEASE */
   121248       testcase( i==52 ); /* ATTACH */
   121249       testcase( i==53 ); /* HAVING */
   121250       testcase( i==54 ); /* GROUP */
   121251       testcase( i==55 ); /* UPDATE */
   121252       testcase( i==56 ); /* BEGIN */
   121253       testcase( i==57 ); /* INNER */
   121254       testcase( i==58 ); /* RECURSIVE */
   121255       testcase( i==59 ); /* BETWEEN */
   121256       testcase( i==60 ); /* NOTNULL */
   121257       testcase( i==61 ); /* NOT */
   121258       testcase( i==62 ); /* NO */
   121259       testcase( i==63 ); /* NULL */
   121260       testcase( i==64 ); /* LIKE */
   121261       testcase( i==65 ); /* CASCADE */
   121262       testcase( i==66 ); /* ASC */
   121263       testcase( i==67 ); /* DELETE */
   121264       testcase( i==68 ); /* CASE */
   121265       testcase( i==69 ); /* COLLATE */
   121266       testcase( i==70 ); /* CREATE */
   121267       testcase( i==71 ); /* CURRENT_DATE */
   121268       testcase( i==72 ); /* DETACH */
   121269       testcase( i==73 ); /* IMMEDIATE */
   121270       testcase( i==74 ); /* JOIN */
   121271       testcase( i==75 ); /* INSERT */
   121272       testcase( i==76 ); /* MATCH */
   121273       testcase( i==77 ); /* PLAN */
   121274       testcase( i==78 ); /* ANALYZE */
   121275       testcase( i==79 ); /* PRAGMA */
   121276       testcase( i==80 ); /* ABORT */
   121277       testcase( i==81 ); /* VALUES */
   121278       testcase( i==82 ); /* VIRTUAL */
   121279       testcase( i==83 ); /* LIMIT */
   121280       testcase( i==84 ); /* WHEN */
   121281       testcase( i==85 ); /* WHERE */
   121282       testcase( i==86 ); /* RENAME */
   121283       testcase( i==87 ); /* AFTER */
   121284       testcase( i==88 ); /* REPLACE */
   121285       testcase( i==89 ); /* AND */
   121286       testcase( i==90 ); /* DEFAULT */
   121287       testcase( i==91 ); /* AUTOINCREMENT */
   121288       testcase( i==92 ); /* TO */
   121289       testcase( i==93 ); /* IN */
   121290       testcase( i==94 ); /* CAST */
   121291       testcase( i==95 ); /* COLUMN */
   121292       testcase( i==96 ); /* COMMIT */
   121293       testcase( i==97 ); /* CONFLICT */
   121294       testcase( i==98 ); /* CROSS */
   121295       testcase( i==99 ); /* CURRENT_TIMESTAMP */
   121296       testcase( i==100 ); /* CURRENT_TIME */
   121297       testcase( i==101 ); /* PRIMARY */
   121298       testcase( i==102 ); /* DEFERRED */
   121299       testcase( i==103 ); /* DISTINCT */
   121300       testcase( i==104 ); /* IS */
   121301       testcase( i==105 ); /* DROP */
   121302       testcase( i==106 ); /* FAIL */
   121303       testcase( i==107 ); /* FROM */
   121304       testcase( i==108 ); /* FULL */
   121305       testcase( i==109 ); /* GLOB */
   121306       testcase( i==110 ); /* BY */
   121307       testcase( i==111 ); /* IF */
   121308       testcase( i==112 ); /* ISNULL */
   121309       testcase( i==113 ); /* ORDER */
   121310       testcase( i==114 ); /* RESTRICT */
   121311       testcase( i==115 ); /* RIGHT */
   121312       testcase( i==116 ); /* ROLLBACK */
   121313       testcase( i==117 ); /* ROW */
   121314       testcase( i==118 ); /* UNION */
   121315       testcase( i==119 ); /* USING */
   121316       testcase( i==120 ); /* VACUUM */
   121317       testcase( i==121 ); /* VIEW */
   121318       testcase( i==122 ); /* INITIALLY */
   121319       testcase( i==123 ); /* ALL */
   121320       return aCode[i];
   121321     }
   121322   }
   121323   return TK_ID;
   121324 }
   121325 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
   121326   return keywordCode((char*)z, n);
   121327 }
   121328 #define SQLITE_N_KEYWORD 124
   121329 
   121330 /************** End of keywordhash.h *****************************************/
   121331 /************** Continuing where we left off in tokenize.c *******************/
   121332 
   121333 
   121334 /*
   121335 ** If X is a character that can be used in an identifier then
   121336 ** IdChar(X) will be true.  Otherwise it is false.
   121337 **
   121338 ** For ASCII, any character with the high-order bit set is
   121339 ** allowed in an identifier.  For 7-bit characters,
   121340 ** sqlite3IsIdChar[X] must be 1.
   121341 **
   121342 ** For EBCDIC, the rules are more complex but have the same
   121343 ** end result.
   121344 **
   121345 ** Ticket #1066.  the SQL standard does not allow '$' in the
   121346 ** middle of identfiers.  But many SQL implementations do.
   121347 ** SQLite will allow '$' in identifiers for compatibility.
   121348 ** But the feature is undocumented.
   121349 */
   121350 #ifdef SQLITE_ASCII
   121351 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   121352 #endif
   121353 #ifdef SQLITE_EBCDIC
   121354 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
   121355 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   121356     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
   121357     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
   121358     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
   121359     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
   121360     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
   121361     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
   121362     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
   121363     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
   121364     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
   121365     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
   121366     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
   121367     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
   121368 };
   121369 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   121370 #endif
   121371 
   121372 
   121373 /*
   121374 ** Return the length of the token that begins at z[0].
   121375 ** Store the token type in *tokenType before returning.
   121376 */
   121377 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
   121378   int i, c;
   121379   switch( *z ){
   121380     case ' ': case '\t': case '\n': case '\f': case '\r': {
   121381       testcase( z[0]==' ' );
   121382       testcase( z[0]=='\t' );
   121383       testcase( z[0]=='\n' );
   121384       testcase( z[0]=='\f' );
   121385       testcase( z[0]=='\r' );
   121386       for(i=1; sqlite3Isspace(z[i]); i++){}
   121387       *tokenType = TK_SPACE;
   121388       return i;
   121389     }
   121390     case '-': {
   121391       if( z[1]=='-' ){
   121392         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
   121393         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   121394         return i;
   121395       }
   121396       *tokenType = TK_MINUS;
   121397       return 1;
   121398     }
   121399     case '(': {
   121400       *tokenType = TK_LP;
   121401       return 1;
   121402     }
   121403     case ')': {
   121404       *tokenType = TK_RP;
   121405       return 1;
   121406     }
   121407     case ';': {
   121408       *tokenType = TK_SEMI;
   121409       return 1;
   121410     }
   121411     case '+': {
   121412       *tokenType = TK_PLUS;
   121413       return 1;
   121414     }
   121415     case '*': {
   121416       *tokenType = TK_STAR;
   121417       return 1;
   121418     }
   121419     case '/': {
   121420       if( z[1]!='*' || z[2]==0 ){
   121421         *tokenType = TK_SLASH;
   121422         return 1;
   121423       }
   121424       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
   121425       if( c ) i++;
   121426       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   121427       return i;
   121428     }
   121429     case '%': {
   121430       *tokenType = TK_REM;
   121431       return 1;
   121432     }
   121433     case '=': {
   121434       *tokenType = TK_EQ;
   121435       return 1 + (z[1]=='=');
   121436     }
   121437     case '<': {
   121438       if( (c=z[1])=='=' ){
   121439         *tokenType = TK_LE;
   121440         return 2;
   121441       }else if( c=='>' ){
   121442         *tokenType = TK_NE;
   121443         return 2;
   121444       }else if( c=='<' ){
   121445         *tokenType = TK_LSHIFT;
   121446         return 2;
   121447       }else{
   121448         *tokenType = TK_LT;
   121449         return 1;
   121450       }
   121451     }
   121452     case '>': {
   121453       if( (c=z[1])=='=' ){
   121454         *tokenType = TK_GE;
   121455         return 2;
   121456       }else if( c=='>' ){
   121457         *tokenType = TK_RSHIFT;
   121458         return 2;
   121459       }else{
   121460         *tokenType = TK_GT;
   121461         return 1;
   121462       }
   121463     }
   121464     case '!': {
   121465       if( z[1]!='=' ){
   121466         *tokenType = TK_ILLEGAL;
   121467         return 2;
   121468       }else{
   121469         *tokenType = TK_NE;
   121470         return 2;
   121471       }
   121472     }
   121473     case '|': {
   121474       if( z[1]!='|' ){
   121475         *tokenType = TK_BITOR;
   121476         return 1;
   121477       }else{
   121478         *tokenType = TK_CONCAT;
   121479         return 2;
   121480       }
   121481     }
   121482     case ',': {
   121483       *tokenType = TK_COMMA;
   121484       return 1;
   121485     }
   121486     case '&': {
   121487       *tokenType = TK_BITAND;
   121488       return 1;
   121489     }
   121490     case '~': {
   121491       *tokenType = TK_BITNOT;
   121492       return 1;
   121493     }
   121494     case '`':
   121495     case '\'':
   121496     case '"': {
   121497       int delim = z[0];
   121498       testcase( delim=='`' );
   121499       testcase( delim=='\'' );
   121500       testcase( delim=='"' );
   121501       for(i=1; (c=z[i])!=0; i++){
   121502         if( c==delim ){
   121503           if( z[i+1]==delim ){
   121504             i++;
   121505           }else{
   121506             break;
   121507           }
   121508         }
   121509       }
   121510       if( c=='\'' ){
   121511         *tokenType = TK_STRING;
   121512         return i+1;
   121513       }else if( c!=0 ){
   121514         *tokenType = TK_ID;
   121515         return i+1;
   121516       }else{
   121517         *tokenType = TK_ILLEGAL;
   121518         return i;
   121519       }
   121520     }
   121521     case '.': {
   121522 #ifndef SQLITE_OMIT_FLOATING_POINT
   121523       if( !sqlite3Isdigit(z[1]) )
   121524 #endif
   121525       {
   121526         *tokenType = TK_DOT;
   121527         return 1;
   121528       }
   121529       /* If the next character is a digit, this is a floating point
   121530       ** number that begins with ".".  Fall thru into the next case */
   121531     }
   121532     case '0': case '1': case '2': case '3': case '4':
   121533     case '5': case '6': case '7': case '8': case '9': {
   121534       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
   121535       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
   121536       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
   121537       testcase( z[0]=='9' );
   121538       *tokenType = TK_INTEGER;
   121539 #ifndef SQLITE_OMIT_HEX_INTEGER
   121540       if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
   121541         for(i=3; sqlite3Isxdigit(z[i]); i++){}
   121542         return i;
   121543       }
   121544 #endif
   121545       for(i=0; sqlite3Isdigit(z[i]); i++){}
   121546 #ifndef SQLITE_OMIT_FLOATING_POINT
   121547       if( z[i]=='.' ){
   121548         i++;
   121549         while( sqlite3Isdigit(z[i]) ){ i++; }
   121550         *tokenType = TK_FLOAT;
   121551       }
   121552       if( (z[i]=='e' || z[i]=='E') &&
   121553            ( sqlite3Isdigit(z[i+1])
   121554             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
   121555            )
   121556       ){
   121557         i += 2;
   121558         while( sqlite3Isdigit(z[i]) ){ i++; }
   121559         *tokenType = TK_FLOAT;
   121560       }
   121561 #endif
   121562       while( IdChar(z[i]) ){
   121563         *tokenType = TK_ILLEGAL;
   121564         i++;
   121565       }
   121566       return i;
   121567     }
   121568     case '[': {
   121569       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
   121570       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
   121571       return i;
   121572     }
   121573     case '?': {
   121574       *tokenType = TK_VARIABLE;
   121575       for(i=1; sqlite3Isdigit(z[i]); i++){}
   121576       return i;
   121577     }
   121578 #ifndef SQLITE_OMIT_TCL_VARIABLE
   121579     case '$':
   121580 #endif
   121581     case '@':  /* For compatibility with MS SQL Server */
   121582     case '#':
   121583     case ':': {
   121584       int n = 0;
   121585       testcase( z[0]=='$' );  testcase( z[0]=='@' );
   121586       testcase( z[0]==':' );  testcase( z[0]=='#' );
   121587       *tokenType = TK_VARIABLE;
   121588       for(i=1; (c=z[i])!=0; i++){
   121589         if( IdChar(c) ){
   121590           n++;
   121591 #ifndef SQLITE_OMIT_TCL_VARIABLE
   121592         }else if( c=='(' && n>0 ){
   121593           do{
   121594             i++;
   121595           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
   121596           if( c==')' ){
   121597             i++;
   121598           }else{
   121599             *tokenType = TK_ILLEGAL;
   121600           }
   121601           break;
   121602         }else if( c==':' && z[i+1]==':' ){
   121603           i++;
   121604 #endif
   121605         }else{
   121606           break;
   121607         }
   121608       }
   121609       if( n==0 ) *tokenType = TK_ILLEGAL;
   121610       return i;
   121611     }
   121612 #ifndef SQLITE_OMIT_BLOB_LITERAL
   121613     case 'x': case 'X': {
   121614       testcase( z[0]=='x' ); testcase( z[0]=='X' );
   121615       if( z[1]=='\'' ){
   121616         *tokenType = TK_BLOB;
   121617         for(i=2; sqlite3Isxdigit(z[i]); i++){}
   121618         if( z[i]!='\'' || i%2 ){
   121619           *tokenType = TK_ILLEGAL;
   121620           while( z[i] && z[i]!='\'' ){ i++; }
   121621         }
   121622         if( z[i] ) i++;
   121623         return i;
   121624       }
   121625       /* Otherwise fall through to the next case */
   121626     }
   121627 #endif
   121628     default: {
   121629       if( !IdChar(*z) ){
   121630         break;
   121631       }
   121632       for(i=1; IdChar(z[i]); i++){}
   121633       *tokenType = keywordCode((char*)z, i);
   121634       return i;
   121635     }
   121636   }
   121637   *tokenType = TK_ILLEGAL;
   121638   return 1;
   121639 }
   121640 
   121641 /*
   121642 ** Run the parser on the given SQL string.  The parser structure is
   121643 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
   121644 ** then an and attempt is made to write an error message into
   121645 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
   121646 ** error message.
   121647 */
   121648 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
   121649   int nErr = 0;                   /* Number of errors encountered */
   121650   int i;                          /* Loop counter */
   121651   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   121652   int tokenType;                  /* type of the next token */
   121653   int lastTokenParsed = -1;       /* type of the previous token */
   121654   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
   121655   sqlite3 *db = pParse->db;       /* The database connection */
   121656   int mxSqlLen;                   /* Max length of an SQL string */
   121657 
   121658 
   121659   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   121660   if( db->nVdbeActive==0 ){
   121661     db->u1.isInterrupted = 0;
   121662   }
   121663   pParse->rc = SQLITE_OK;
   121664   pParse->zTail = zSql;
   121665   i = 0;
   121666   assert( pzErrMsg!=0 );
   121667   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
   121668   if( pEngine==0 ){
   121669     db->mallocFailed = 1;
   121670     return SQLITE_NOMEM;
   121671   }
   121672   assert( pParse->pNewTable==0 );
   121673   assert( pParse->pNewTrigger==0 );
   121674   assert( pParse->nVar==0 );
   121675   assert( pParse->nzVar==0 );
   121676   assert( pParse->azVar==0 );
   121677   enableLookaside = db->lookaside.bEnabled;
   121678   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
   121679   while( !db->mallocFailed && zSql[i]!=0 ){
   121680     assert( i>=0 );
   121681     pParse->sLastToken.z = &zSql[i];
   121682     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
   121683     i += pParse->sLastToken.n;
   121684     if( i>mxSqlLen ){
   121685       pParse->rc = SQLITE_TOOBIG;
   121686       break;
   121687     }
   121688     switch( tokenType ){
   121689       case TK_SPACE: {
   121690         if( db->u1.isInterrupted ){
   121691           sqlite3ErrorMsg(pParse, "interrupt");
   121692           pParse->rc = SQLITE_INTERRUPT;
   121693           goto abort_parse;
   121694         }
   121695         break;
   121696       }
   121697       case TK_ILLEGAL: {
   121698         sqlite3DbFree(db, *pzErrMsg);
   121699         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
   121700                         &pParse->sLastToken);
   121701         nErr++;
   121702         goto abort_parse;
   121703       }
   121704       case TK_SEMI: {
   121705         pParse->zTail = &zSql[i];
   121706         /* Fall thru into the default case */
   121707       }
   121708       default: {
   121709         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
   121710         lastTokenParsed = tokenType;
   121711         if( pParse->rc!=SQLITE_OK ){
   121712           goto abort_parse;
   121713         }
   121714         break;
   121715       }
   121716     }
   121717   }
   121718 abort_parse:
   121719   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
   121720     if( lastTokenParsed!=TK_SEMI ){
   121721       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
   121722       pParse->zTail = &zSql[i];
   121723     }
   121724     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
   121725   }
   121726 #ifdef YYTRACKMAXSTACKDEPTH
   121727   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
   121728       sqlite3ParserStackPeak(pEngine)
   121729   );
   121730 #endif /* YYDEBUG */
   121731   sqlite3ParserFree(pEngine, sqlite3_free);
   121732   db->lookaside.bEnabled = enableLookaside;
   121733   if( db->mallocFailed ){
   121734     pParse->rc = SQLITE_NOMEM;
   121735   }
   121736   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   121737     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
   121738   }
   121739   assert( pzErrMsg!=0 );
   121740   if( pParse->zErrMsg ){
   121741     *pzErrMsg = pParse->zErrMsg;
   121742     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
   121743     pParse->zErrMsg = 0;
   121744     nErr++;
   121745   }
   121746   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
   121747     sqlite3VdbeDelete(pParse->pVdbe);
   121748     pParse->pVdbe = 0;
   121749   }
   121750 #ifndef SQLITE_OMIT_SHARED_CACHE
   121751   if( pParse->nested==0 ){
   121752     sqlite3DbFree(db, pParse->aTableLock);
   121753     pParse->aTableLock = 0;
   121754     pParse->nTableLock = 0;
   121755   }
   121756 #endif
   121757 #ifndef SQLITE_OMIT_VIRTUALTABLE
   121758   sqlite3_free(pParse->apVtabLock);
   121759 #endif
   121760 
   121761   if( !IN_DECLARE_VTAB ){
   121762     /* If the pParse->declareVtab flag is set, do not delete any table
   121763     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
   121764     ** will take responsibility for freeing the Table structure.
   121765     */
   121766     sqlite3DeleteTable(db, pParse->pNewTable);
   121767   }
   121768 
   121769   if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
   121770   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   121771   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
   121772   sqlite3DbFree(db, pParse->azVar);
   121773   while( pParse->pAinc ){
   121774     AutoincInfo *p = pParse->pAinc;
   121775     pParse->pAinc = p->pNext;
   121776     sqlite3DbFree(db, p);
   121777   }
   121778   while( pParse->pZombieTab ){
   121779     Table *p = pParse->pZombieTab;
   121780     pParse->pZombieTab = p->pNextZombie;
   121781     sqlite3DeleteTable(db, p);
   121782   }
   121783   if( nErr>0 && pParse->rc==SQLITE_OK ){
   121784     pParse->rc = SQLITE_ERROR;
   121785   }
   121786   return nErr;
   121787 }
   121788 
   121789 /************** End of tokenize.c ********************************************/
   121790 /************** Begin file complete.c ****************************************/
   121791 /*
   121792 ** 2001 September 15
   121793 **
   121794 ** The author disclaims copyright to this source code.  In place of
   121795 ** a legal notice, here is a blessing:
   121796 **
   121797 **    May you do good and not evil.
   121798 **    May you find forgiveness for yourself and forgive others.
   121799 **    May you share freely, never taking more than you give.
   121800 **
   121801 *************************************************************************
   121802 ** An tokenizer for SQL
   121803 **
   121804 ** This file contains C code that implements the sqlite3_complete() API.
   121805 ** This code used to be part of the tokenizer.c source file.  But by
   121806 ** separating it out, the code will be automatically omitted from
   121807 ** static links that do not use it.
   121808 */
   121809 #ifndef SQLITE_OMIT_COMPLETE
   121810 
   121811 /*
   121812 ** This is defined in tokenize.c.  We just have to import the definition.
   121813 */
   121814 #ifndef SQLITE_AMALGAMATION
   121815 #ifdef SQLITE_ASCII
   121816 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   121817 #endif
   121818 #ifdef SQLITE_EBCDIC
   121819 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
   121820 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   121821 #endif
   121822 #endif /* SQLITE_AMALGAMATION */
   121823 
   121824 
   121825 /*
   121826 ** Token types used by the sqlite3_complete() routine.  See the header
   121827 ** comments on that procedure for additional information.
   121828 */
   121829 #define tkSEMI    0
   121830 #define tkWS      1
   121831 #define tkOTHER   2
   121832 #ifndef SQLITE_OMIT_TRIGGER
   121833 #define tkEXPLAIN 3
   121834 #define tkCREATE  4
   121835 #define tkTEMP    5
   121836 #define tkTRIGGER 6
   121837 #define tkEND     7
   121838 #endif
   121839 
   121840 /*
   121841 ** Return TRUE if the given SQL string ends in a semicolon.
   121842 **
   121843 ** Special handling is require for CREATE TRIGGER statements.
   121844 ** Whenever the CREATE TRIGGER keywords are seen, the statement
   121845 ** must end with ";END;".
   121846 **
   121847 ** This implementation uses a state machine with 8 states:
   121848 **
   121849 **   (0) INVALID   We have not yet seen a non-whitespace character.
   121850 **
   121851 **   (1) START     At the beginning or end of an SQL statement.  This routine
   121852 **                 returns 1 if it ends in the START state and 0 if it ends
   121853 **                 in any other state.
   121854 **
   121855 **   (2) NORMAL    We are in the middle of statement which ends with a single
   121856 **                 semicolon.
   121857 **
   121858 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
   121859 **                 a statement.
   121860 **
   121861 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
   121862 **                 statement, possibly preceeded by EXPLAIN and/or followed by
   121863 **                 TEMP or TEMPORARY
   121864 **
   121865 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
   121866 **                 ended by a semicolon, the keyword END, and another semicolon.
   121867 **
   121868 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
   121869 **                 the end of a trigger definition.
   121870 **
   121871 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
   121872 **                 of a trigger difinition.
   121873 **
   121874 ** Transitions between states above are determined by tokens extracted
   121875 ** from the input.  The following tokens are significant:
   121876 **
   121877 **   (0) tkSEMI      A semicolon.
   121878 **   (1) tkWS        Whitespace.
   121879 **   (2) tkOTHER     Any other SQL token.
   121880 **   (3) tkEXPLAIN   The "explain" keyword.
   121881 **   (4) tkCREATE    The "create" keyword.
   121882 **   (5) tkTEMP      The "temp" or "temporary" keyword.
   121883 **   (6) tkTRIGGER   The "trigger" keyword.
   121884 **   (7) tkEND       The "end" keyword.
   121885 **
   121886 ** Whitespace never causes a state transition and is always ignored.
   121887 ** This means that a SQL string of all whitespace is invalid.
   121888 **
   121889 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
   121890 ** to recognize the end of a trigger can be omitted.  All we have to do
   121891 ** is look for a semicolon that is not part of an string or comment.
   121892 */
   121893 SQLITE_API int sqlite3_complete(const char *zSql){
   121894   u8 state = 0;   /* Current state, using numbers defined in header comment */
   121895   u8 token;       /* Value of the next token */
   121896 
   121897 #ifndef SQLITE_OMIT_TRIGGER
   121898   /* A complex statement machine used to detect the end of a CREATE TRIGGER
   121899   ** statement.  This is the normal case.
   121900   */
   121901   static const u8 trans[8][8] = {
   121902                      /* Token:                                                */
   121903      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
   121904      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
   121905      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
   121906      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
   121907      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
   121908      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
   121909      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
   121910      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
   121911      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
   121912   };
   121913 #else
   121914   /* If triggers are not supported by this compile then the statement machine
   121915   ** used to detect the end of a statement is much simplier
   121916   */
   121917   static const u8 trans[3][3] = {
   121918                      /* Token:           */
   121919      /* State:       **  SEMI  WS  OTHER */
   121920      /* 0 INVALID: */ {    1,  0,     2, },
   121921      /* 1   START: */ {    1,  1,     2, },
   121922      /* 2  NORMAL: */ {    1,  2,     2, },
   121923   };
   121924 #endif /* SQLITE_OMIT_TRIGGER */
   121925 
   121926   while( *zSql ){
   121927     switch( *zSql ){
   121928       case ';': {  /* A semicolon */
   121929         token = tkSEMI;
   121930         break;
   121931       }
   121932       case ' ':
   121933       case '\r':
   121934       case '\t':
   121935       case '\n':
   121936       case '\f': {  /* White space is ignored */
   121937         token = tkWS;
   121938         break;
   121939       }
   121940       case '/': {   /* C-style comments */
   121941         if( zSql[1]!='*' ){
   121942           token = tkOTHER;
   121943           break;
   121944         }
   121945         zSql += 2;
   121946         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
   121947         if( zSql[0]==0 ) return 0;
   121948         zSql++;
   121949         token = tkWS;
   121950         break;
   121951       }
   121952       case '-': {   /* SQL-style comments from "--" to end of line */
   121953         if( zSql[1]!='-' ){
   121954           token = tkOTHER;
   121955           break;
   121956         }
   121957         while( *zSql && *zSql!='\n' ){ zSql++; }
   121958         if( *zSql==0 ) return state==1;
   121959         token = tkWS;
   121960         break;
   121961       }
   121962       case '[': {   /* Microsoft-style identifiers in [...] */
   121963         zSql++;
   121964         while( *zSql && *zSql!=']' ){ zSql++; }
   121965         if( *zSql==0 ) return 0;
   121966         token = tkOTHER;
   121967         break;
   121968       }
   121969       case '`':     /* Grave-accent quoted symbols used by MySQL */
   121970       case '"':     /* single- and double-quoted strings */
   121971       case '\'': {
   121972         int c = *zSql;
   121973         zSql++;
   121974         while( *zSql && *zSql!=c ){ zSql++; }
   121975         if( *zSql==0 ) return 0;
   121976         token = tkOTHER;
   121977         break;
   121978       }
   121979       default: {
   121980 #ifdef SQLITE_EBCDIC
   121981         unsigned char c;
   121982 #endif
   121983         if( IdChar((u8)*zSql) ){
   121984           /* Keywords and unquoted identifiers */
   121985           int nId;
   121986           for(nId=1; IdChar(zSql[nId]); nId++){}
   121987 #ifdef SQLITE_OMIT_TRIGGER
   121988           token = tkOTHER;
   121989 #else
   121990           switch( *zSql ){
   121991             case 'c': case 'C': {
   121992               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
   121993                 token = tkCREATE;
   121994               }else{
   121995                 token = tkOTHER;
   121996               }
   121997               break;
   121998             }
   121999             case 't': case 'T': {
   122000               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
   122001                 token = tkTRIGGER;
   122002               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
   122003                 token = tkTEMP;
   122004               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
   122005                 token = tkTEMP;
   122006               }else{
   122007                 token = tkOTHER;
   122008               }
   122009               break;
   122010             }
   122011             case 'e':  case 'E': {
   122012               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
   122013                 token = tkEND;
   122014               }else
   122015 #ifndef SQLITE_OMIT_EXPLAIN
   122016               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
   122017                 token = tkEXPLAIN;
   122018               }else
   122019 #endif
   122020               {
   122021                 token = tkOTHER;
   122022               }
   122023               break;
   122024             }
   122025             default: {
   122026               token = tkOTHER;
   122027               break;
   122028             }
   122029           }
   122030 #endif /* SQLITE_OMIT_TRIGGER */
   122031           zSql += nId-1;
   122032         }else{
   122033           /* Operators and special symbols */
   122034           token = tkOTHER;
   122035         }
   122036         break;
   122037       }
   122038     }
   122039     state = trans[state][token];
   122040     zSql++;
   122041   }
   122042   return state==1;
   122043 }
   122044 
   122045 #ifndef SQLITE_OMIT_UTF16
   122046 /*
   122047 ** This routine is the same as the sqlite3_complete() routine described
   122048 ** above, except that the parameter is required to be UTF-16 encoded, not
   122049 ** UTF-8.
   122050 */
   122051 SQLITE_API int sqlite3_complete16(const void *zSql){
   122052   sqlite3_value *pVal;
   122053   char const *zSql8;
   122054   int rc = SQLITE_NOMEM;
   122055 
   122056 #ifndef SQLITE_OMIT_AUTOINIT
   122057   rc = sqlite3_initialize();
   122058   if( rc ) return rc;
   122059 #endif
   122060   pVal = sqlite3ValueNew(0);
   122061   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   122062   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   122063   if( zSql8 ){
   122064     rc = sqlite3_complete(zSql8);
   122065   }else{
   122066     rc = SQLITE_NOMEM;
   122067   }
   122068   sqlite3ValueFree(pVal);
   122069   return sqlite3ApiExit(0, rc);
   122070 }
   122071 #endif /* SQLITE_OMIT_UTF16 */
   122072 #endif /* SQLITE_OMIT_COMPLETE */
   122073 
   122074 /************** End of complete.c ********************************************/
   122075 /************** Begin file main.c ********************************************/
   122076 /*
   122077 ** 2001 September 15
   122078 **
   122079 ** The author disclaims copyright to this source code.  In place of
   122080 ** a legal notice, here is a blessing:
   122081 **
   122082 **    May you do good and not evil.
   122083 **    May you find forgiveness for yourself and forgive others.
   122084 **    May you share freely, never taking more than you give.
   122085 **
   122086 *************************************************************************
   122087 ** Main file for the SQLite library.  The routines in this file
   122088 ** implement the programmer interface to the library.  Routines in
   122089 ** other files are for internal use by SQLite and should not be
   122090 ** accessed by users of the library.
   122091 */
   122092 
   122093 #ifdef SQLITE_ENABLE_FTS3
   122094 /************** Include fts3.h in the middle of main.c ***********************/
   122095 /************** Begin file fts3.h ********************************************/
   122096 /*
   122097 ** 2006 Oct 10
   122098 **
   122099 ** The author disclaims copyright to this source code.  In place of
   122100 ** a legal notice, here is a blessing:
   122101 **
   122102 **    May you do good and not evil.
   122103 **    May you find forgiveness for yourself and forgive others.
   122104 **    May you share freely, never taking more than you give.
   122105 **
   122106 ******************************************************************************
   122107 **
   122108 ** This header file is used by programs that want to link against the
   122109 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
   122110 */
   122111 
   122112 #if 0
   122113 extern "C" {
   122114 #endif  /* __cplusplus */
   122115 
   122116 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
   122117 
   122118 #if 0
   122119 }  /* extern "C" */
   122120 #endif  /* __cplusplus */
   122121 
   122122 /************** End of fts3.h ************************************************/
   122123 /************** Continuing where we left off in main.c ***********************/
   122124 #endif
   122125 #ifdef SQLITE_ENABLE_RTREE
   122126 /************** Include rtree.h in the middle of main.c **********************/
   122127 /************** Begin file rtree.h *******************************************/
   122128 /*
   122129 ** 2008 May 26
   122130 **
   122131 ** The author disclaims copyright to this source code.  In place of
   122132 ** a legal notice, here is a blessing:
   122133 **
   122134 **    May you do good and not evil.
   122135 **    May you find forgiveness for yourself and forgive others.
   122136 **    May you share freely, never taking more than you give.
   122137 **
   122138 ******************************************************************************
   122139 **
   122140 ** This header file is used by programs that want to link against the
   122141 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
   122142 */
   122143 
   122144 #if 0
   122145 extern "C" {
   122146 #endif  /* __cplusplus */
   122147 
   122148 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
   122149 
   122150 #if 0
   122151 }  /* extern "C" */
   122152 #endif  /* __cplusplus */
   122153 
   122154 /************** End of rtree.h ***********************************************/
   122155 /************** Continuing where we left off in main.c ***********************/
   122156 #endif
   122157 #ifdef SQLITE_ENABLE_ICU
   122158 /************** Include sqliteicu.h in the middle of main.c ******************/
   122159 /************** Begin file sqliteicu.h ***************************************/
   122160 /*
   122161 ** 2008 May 26
   122162 **
   122163 ** The author disclaims copyright to this source code.  In place of
   122164 ** a legal notice, here is a blessing:
   122165 **
   122166 **    May you do good and not evil.
   122167 **    May you find forgiveness for yourself and forgive others.
   122168 **    May you share freely, never taking more than you give.
   122169 **
   122170 ******************************************************************************
   122171 **
   122172 ** This header file is used by programs that want to link against the
   122173 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
   122174 */
   122175 
   122176 #if 0
   122177 extern "C" {
   122178 #endif  /* __cplusplus */
   122179 
   122180 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
   122181 
   122182 #if 0
   122183 }  /* extern "C" */
   122184 #endif  /* __cplusplus */
   122185 
   122186 
   122187 /************** End of sqliteicu.h *******************************************/
   122188 /************** Continuing where we left off in main.c ***********************/
   122189 #endif
   122190 
   122191 #ifndef SQLITE_AMALGAMATION
   122192 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
   122193 ** contains the text of SQLITE_VERSION macro.
   122194 */
   122195 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   122196 #endif
   122197 
   122198 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
   122199 ** a pointer to the to the sqlite3_version[] string constant.
   122200 */
   122201 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
   122202 
   122203 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
   122204 ** pointer to a string constant whose value is the same as the
   122205 ** SQLITE_SOURCE_ID C preprocessor macro.
   122206 */
   122207 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
   122208 
   122209 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
   122210 ** returns an integer equal to SQLITE_VERSION_NUMBER.
   122211 */
   122212 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
   122213 
   122214 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
   122215 ** zero if and only if SQLite was compiled with mutexing code omitted due to
   122216 ** the SQLITE_THREADSAFE compile-time option being set to 0.
   122217 */
   122218 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
   122219 
   122220 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   122221 /*
   122222 ** If the following function pointer is not NULL and if
   122223 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
   122224 ** I/O active are written using this function.  These messages
   122225 ** are intended for debugging activity only.
   122226 */
   122227 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
   122228 #endif
   122229 
   122230 /*
   122231 ** If the following global variable points to a string which is the
   122232 ** name of a directory, then that directory will be used to store
   122233 ** temporary files.
   122234 **
   122235 ** See also the "PRAGMA temp_store_directory" SQL command.
   122236 */
   122237 SQLITE_API char *sqlite3_temp_directory = 0;
   122238 
   122239 /*
   122240 ** If the following global variable points to a string which is the
   122241 ** name of a directory, then that directory will be used to store
   122242 ** all database files specified with a relative pathname.
   122243 **
   122244 ** See also the "PRAGMA data_store_directory" SQL command.
   122245 */
   122246 SQLITE_API char *sqlite3_data_directory = 0;
   122247 
   122248 /*
   122249 ** Initialize SQLite.
   122250 **
   122251 ** This routine must be called to initialize the memory allocation,
   122252 ** VFS, and mutex subsystems prior to doing any serious work with
   122253 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
   122254 ** this routine will be called automatically by key routines such as
   122255 ** sqlite3_open().
   122256 **
   122257 ** This routine is a no-op except on its very first call for the process,
   122258 ** or for the first call after a call to sqlite3_shutdown.
   122259 **
   122260 ** The first thread to call this routine runs the initialization to
   122261 ** completion.  If subsequent threads call this routine before the first
   122262 ** thread has finished the initialization process, then the subsequent
   122263 ** threads must block until the first thread finishes with the initialization.
   122264 **
   122265 ** The first thread might call this routine recursively.  Recursive
   122266 ** calls to this routine should not block, of course.  Otherwise the
   122267 ** initialization process would never complete.
   122268 **
   122269 ** Let X be the first thread to enter this routine.  Let Y be some other
   122270 ** thread.  Then while the initial invocation of this routine by X is
   122271 ** incomplete, it is required that:
   122272 **
   122273 **    *  Calls to this routine from Y must block until the outer-most
   122274 **       call by X completes.
   122275 **
   122276 **    *  Recursive calls to this routine from thread X return immediately
   122277 **       without blocking.
   122278 */
   122279 SQLITE_API int sqlite3_initialize(void){
   122280   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
   122281   int rc;                                      /* Result code */
   122282 #ifdef SQLITE_EXTRA_INIT
   122283   int bRunExtraInit = 0;                       /* Extra initialization needed */
   122284 #endif
   122285 
   122286 #ifdef SQLITE_OMIT_WSD
   122287   rc = sqlite3_wsd_init(4096, 24);
   122288   if( rc!=SQLITE_OK ){
   122289     return rc;
   122290   }
   122291 #endif
   122292 
   122293   /* If SQLite is already completely initialized, then this call
   122294   ** to sqlite3_initialize() should be a no-op.  But the initialization
   122295   ** must be complete.  So isInit must not be set until the very end
   122296   ** of this routine.
   122297   */
   122298   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
   122299 
   122300   /* Make sure the mutex subsystem is initialized.  If unable to
   122301   ** initialize the mutex subsystem, return early with the error.
   122302   ** If the system is so sick that we are unable to allocate a mutex,
   122303   ** there is not much SQLite is going to be able to do.
   122304   **
   122305   ** The mutex subsystem must take care of serializing its own
   122306   ** initialization.
   122307   */
   122308   rc = sqlite3MutexInit();
   122309   if( rc ) return rc;
   122310 
   122311   /* Initialize the malloc() system and the recursive pInitMutex mutex.
   122312   ** This operation is protected by the STATIC_MASTER mutex.  Note that
   122313   ** MutexAlloc() is called for a static mutex prior to initializing the
   122314   ** malloc subsystem - this implies that the allocation of a static
   122315   ** mutex must not require support from the malloc subsystem.
   122316   */
   122317   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   122318   sqlite3_mutex_enter(pMaster);
   122319   sqlite3GlobalConfig.isMutexInit = 1;
   122320   if( !sqlite3GlobalConfig.isMallocInit ){
   122321     rc = sqlite3MallocInit();
   122322   }
   122323   if( rc==SQLITE_OK ){
   122324     sqlite3GlobalConfig.isMallocInit = 1;
   122325     if( !sqlite3GlobalConfig.pInitMutex ){
   122326       sqlite3GlobalConfig.pInitMutex =
   122327            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   122328       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
   122329         rc = SQLITE_NOMEM;
   122330       }
   122331     }
   122332   }
   122333   if( rc==SQLITE_OK ){
   122334     sqlite3GlobalConfig.nRefInitMutex++;
   122335   }
   122336   sqlite3_mutex_leave(pMaster);
   122337 
   122338   /* If rc is not SQLITE_OK at this point, then either the malloc
   122339   ** subsystem could not be initialized or the system failed to allocate
   122340   ** the pInitMutex mutex. Return an error in either case.  */
   122341   if( rc!=SQLITE_OK ){
   122342     return rc;
   122343   }
   122344 
   122345   /* Do the rest of the initialization under the recursive mutex so
   122346   ** that we will be able to handle recursive calls into
   122347   ** sqlite3_initialize().  The recursive calls normally come through
   122348   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
   122349   ** recursive calls might also be possible.
   122350   **
   122351   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
   122352   ** to the xInit method, so the xInit method need not be threadsafe.
   122353   **
   122354   ** The following mutex is what serializes access to the appdef pcache xInit
   122355   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
   122356   ** call to sqlite3PcacheInitialize().
   122357   */
   122358   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
   122359   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
   122360     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   122361     sqlite3GlobalConfig.inProgress = 1;
   122362     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
   122363     sqlite3RegisterGlobalFunctions();
   122364     if( sqlite3GlobalConfig.isPCacheInit==0 ){
   122365       rc = sqlite3PcacheInitialize();
   122366     }
   122367     if( rc==SQLITE_OK ){
   122368       sqlite3GlobalConfig.isPCacheInit = 1;
   122369       rc = sqlite3OsInit();
   122370     }
   122371     if( rc==SQLITE_OK ){
   122372       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
   122373           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
   122374       sqlite3GlobalConfig.isInit = 1;
   122375 #ifdef SQLITE_EXTRA_INIT
   122376       bRunExtraInit = 1;
   122377 #endif
   122378     }
   122379     sqlite3GlobalConfig.inProgress = 0;
   122380   }
   122381   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
   122382 
   122383   /* Go back under the static mutex and clean up the recursive
   122384   ** mutex to prevent a resource leak.
   122385   */
   122386   sqlite3_mutex_enter(pMaster);
   122387   sqlite3GlobalConfig.nRefInitMutex--;
   122388   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
   122389     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
   122390     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
   122391     sqlite3GlobalConfig.pInitMutex = 0;
   122392   }
   122393   sqlite3_mutex_leave(pMaster);
   122394 
   122395   /* The following is just a sanity check to make sure SQLite has
   122396   ** been compiled correctly.  It is important to run this code, but
   122397   ** we don't want to run it too often and soak up CPU cycles for no
   122398   ** reason.  So we run it once during initialization.
   122399   */
   122400 #ifndef NDEBUG
   122401 #ifndef SQLITE_OMIT_FLOATING_POINT
   122402   /* This section of code's only "output" is via assert() statements. */
   122403   if ( rc==SQLITE_OK ){
   122404     u64 x = (((u64)1)<<63)-1;
   122405     double y;
   122406     assert(sizeof(x)==8);
   122407     assert(sizeof(x)==sizeof(y));
   122408     memcpy(&y, &x, 8);
   122409     assert( sqlite3IsNaN(y) );
   122410   }
   122411 #endif
   122412 #endif
   122413 
   122414   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
   122415   ** compile-time option.
   122416   */
   122417 #ifdef SQLITE_EXTRA_INIT
   122418   if( bRunExtraInit ){
   122419     int SQLITE_EXTRA_INIT(const char*);
   122420     rc = SQLITE_EXTRA_INIT(0);
   122421   }
   122422 #endif
   122423 
   122424   return rc;
   122425 }
   122426 
   122427 /*
   122428 ** Undo the effects of sqlite3_initialize().  Must not be called while
   122429 ** there are outstanding database connections or memory allocations or
   122430 ** while any part of SQLite is otherwise in use in any thread.  This
   122431 ** routine is not threadsafe.  But it is safe to invoke this routine
   122432 ** on when SQLite is already shut down.  If SQLite is already shut down
   122433 ** when this routine is invoked, then this routine is a harmless no-op.
   122434 */
   122435 SQLITE_API int sqlite3_shutdown(void){
   122436   if( sqlite3GlobalConfig.isInit ){
   122437 #ifdef SQLITE_EXTRA_SHUTDOWN
   122438     void SQLITE_EXTRA_SHUTDOWN(void);
   122439     SQLITE_EXTRA_SHUTDOWN();
   122440 #endif
   122441     sqlite3_os_end();
   122442     sqlite3_reset_auto_extension();
   122443     sqlite3GlobalConfig.isInit = 0;
   122444   }
   122445   if( sqlite3GlobalConfig.isPCacheInit ){
   122446     sqlite3PcacheShutdown();
   122447     sqlite3GlobalConfig.isPCacheInit = 0;
   122448   }
   122449   if( sqlite3GlobalConfig.isMallocInit ){
   122450     sqlite3MallocEnd();
   122451     sqlite3GlobalConfig.isMallocInit = 0;
   122452 
   122453 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
   122454     /* The heap subsystem has now been shutdown and these values are supposed
   122455     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
   122456     ** which would rely on that heap subsystem; therefore, make sure these
   122457     ** values cannot refer to heap memory that was just invalidated when the
   122458     ** heap subsystem was shutdown.  This is only done if the current call to
   122459     ** this function resulted in the heap subsystem actually being shutdown.
   122460     */
   122461     sqlite3_data_directory = 0;
   122462     sqlite3_temp_directory = 0;
   122463 #endif
   122464   }
   122465   if( sqlite3GlobalConfig.isMutexInit ){
   122466     sqlite3MutexEnd();
   122467     sqlite3GlobalConfig.isMutexInit = 0;
   122468   }
   122469 
   122470   return SQLITE_OK;
   122471 }
   122472 
   122473 /*
   122474 ** This API allows applications to modify the global configuration of
   122475 ** the SQLite library at run-time.
   122476 **
   122477 ** This routine should only be called when there are no outstanding
   122478 ** database connections or memory allocations.  This routine is not
   122479 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
   122480 ** behavior.
   122481 */
   122482 SQLITE_API int sqlite3_config(int op, ...){
   122483   va_list ap;
   122484   int rc = SQLITE_OK;
   122485 
   122486   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
   122487   ** the SQLite library is in use. */
   122488   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
   122489 
   122490   va_start(ap, op);
   122491   switch( op ){
   122492 
   122493     /* Mutex configuration options are only available in a threadsafe
   122494     ** compile.
   122495     */
   122496 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
   122497     case SQLITE_CONFIG_SINGLETHREAD: {
   122498       /* Disable all mutexing */
   122499       sqlite3GlobalConfig.bCoreMutex = 0;
   122500       sqlite3GlobalConfig.bFullMutex = 0;
   122501       break;
   122502     }
   122503     case SQLITE_CONFIG_MULTITHREAD: {
   122504       /* Disable mutexing of database connections */
   122505       /* Enable mutexing of core data structures */
   122506       sqlite3GlobalConfig.bCoreMutex = 1;
   122507       sqlite3GlobalConfig.bFullMutex = 0;
   122508       break;
   122509     }
   122510     case SQLITE_CONFIG_SERIALIZED: {
   122511       /* Enable all mutexing */
   122512       sqlite3GlobalConfig.bCoreMutex = 1;
   122513       sqlite3GlobalConfig.bFullMutex = 1;
   122514       break;
   122515     }
   122516     case SQLITE_CONFIG_MUTEX: {
   122517       /* Specify an alternative mutex implementation */
   122518       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
   122519       break;
   122520     }
   122521     case SQLITE_CONFIG_GETMUTEX: {
   122522       /* Retrieve the current mutex implementation */
   122523       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
   122524       break;
   122525     }
   122526 #endif
   122527 
   122528 
   122529     case SQLITE_CONFIG_MALLOC: {
   122530       /* Specify an alternative malloc implementation */
   122531       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
   122532       break;
   122533     }
   122534     case SQLITE_CONFIG_GETMALLOC: {
   122535       /* Retrieve the current malloc() implementation */
   122536       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
   122537       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
   122538       break;
   122539     }
   122540     case SQLITE_CONFIG_MEMSTATUS: {
   122541       /* Enable or disable the malloc status collection */
   122542       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
   122543       break;
   122544     }
   122545     case SQLITE_CONFIG_SCRATCH: {
   122546       /* Designate a buffer for scratch memory space */
   122547       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
   122548       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
   122549       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
   122550       break;
   122551     }
   122552     case SQLITE_CONFIG_PAGECACHE: {
   122553       /* Designate a buffer for page cache memory space */
   122554       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
   122555       sqlite3GlobalConfig.szPage = va_arg(ap, int);
   122556       sqlite3GlobalConfig.nPage = va_arg(ap, int);
   122557       break;
   122558     }
   122559 
   122560     case SQLITE_CONFIG_PCACHE: {
   122561       /* no-op */
   122562       break;
   122563     }
   122564     case SQLITE_CONFIG_GETPCACHE: {
   122565       /* now an error */
   122566       rc = SQLITE_ERROR;
   122567       break;
   122568     }
   122569 
   122570     case SQLITE_CONFIG_PCACHE2: {
   122571       /* Specify an alternative page cache implementation */
   122572       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
   122573       break;
   122574     }
   122575     case SQLITE_CONFIG_GETPCACHE2: {
   122576       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   122577         sqlite3PCacheSetDefault();
   122578       }
   122579       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
   122580       break;
   122581     }
   122582 
   122583 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   122584     case SQLITE_CONFIG_HEAP: {
   122585       /* Designate a buffer for heap memory space */
   122586       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
   122587       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   122588       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
   122589 
   122590       if( sqlite3GlobalConfig.mnReq<1 ){
   122591         sqlite3GlobalConfig.mnReq = 1;
   122592       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
   122593         /* cap min request size at 2^12 */
   122594         sqlite3GlobalConfig.mnReq = (1<<12);
   122595       }
   122596 
   122597       if( sqlite3GlobalConfig.pHeap==0 ){
   122598         /* If the heap pointer is NULL, then restore the malloc implementation
   122599         ** back to NULL pointers too.  This will cause the malloc to go
   122600         ** back to its default implementation when sqlite3_initialize() is
   122601         ** run.
   122602         */
   122603         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
   122604       }else{
   122605         /* The heap pointer is not NULL, then install one of the
   122606         ** mem5.c/mem3.c methods.  The enclosing #if guarantees at
   122607         ** least one of these methods is currently enabled.
   122608         */
   122609 #ifdef SQLITE_ENABLE_MEMSYS3
   122610         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
   122611 #endif
   122612 #ifdef SQLITE_ENABLE_MEMSYS5
   122613         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
   122614 #endif
   122615       }
   122616       break;
   122617     }
   122618 #endif
   122619 
   122620     case SQLITE_CONFIG_LOOKASIDE: {
   122621       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
   122622       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
   122623       break;
   122624     }
   122625 
   122626     /* Record a pointer to the logger function and its first argument.
   122627     ** The default is NULL.  Logging is disabled if the function pointer is
   122628     ** NULL.
   122629     */
   122630     case SQLITE_CONFIG_LOG: {
   122631       /* MSVC is picky about pulling func ptrs from va lists.
   122632       ** http://support.microsoft.com/kb/47961
   122633       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
   122634       */
   122635       typedef void(*LOGFUNC_t)(void*,int,const char*);
   122636       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
   122637       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
   122638       break;
   122639     }
   122640 
   122641     case SQLITE_CONFIG_URI: {
   122642       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
   122643       break;
   122644     }
   122645 
   122646     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
   122647       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
   122648       break;
   122649     }
   122650 
   122651 #ifdef SQLITE_ENABLE_SQLLOG
   122652     case SQLITE_CONFIG_SQLLOG: {
   122653       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
   122654       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
   122655       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
   122656       break;
   122657     }
   122658 #endif
   122659 
   122660     case SQLITE_CONFIG_MMAP_SIZE: {
   122661       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
   122662       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
   122663       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
   122664         mxMmap = SQLITE_MAX_MMAP_SIZE;
   122665       }
   122666       sqlite3GlobalConfig.mxMmap = mxMmap;
   122667       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
   122668       if( szMmap>mxMmap) szMmap = mxMmap;
   122669       sqlite3GlobalConfig.szMmap = szMmap;
   122670       break;
   122671     }
   122672 
   122673 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
   122674     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
   122675       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   122676       break;
   122677     }
   122678 #endif
   122679 
   122680     default: {
   122681       rc = SQLITE_ERROR;
   122682       break;
   122683     }
   122684   }
   122685   va_end(ap);
   122686   return rc;
   122687 }
   122688 
   122689 /*
   122690 ** Set up the lookaside buffers for a database connection.
   122691 ** Return SQLITE_OK on success.
   122692 ** If lookaside is already active, return SQLITE_BUSY.
   122693 **
   122694 ** The sz parameter is the number of bytes in each lookaside slot.
   122695 ** The cnt parameter is the number of slots.  If pStart is NULL the
   122696 ** space for the lookaside memory is obtained from sqlite3_malloc().
   122697 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
   122698 ** the lookaside memory.
   122699 */
   122700 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
   122701   void *pStart;
   122702   if( db->lookaside.nOut ){
   122703     return SQLITE_BUSY;
   122704   }
   122705   /* Free any existing lookaside buffer for this handle before
   122706   ** allocating a new one so we don't have to have space for
   122707   ** both at the same time.
   122708   */
   122709   if( db->lookaside.bMalloced ){
   122710     sqlite3_free(db->lookaside.pStart);
   122711   }
   122712   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
   122713   ** than a pointer to be useful.
   122714   */
   122715   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
   122716   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
   122717   if( cnt<0 ) cnt = 0;
   122718   if( sz==0 || cnt==0 ){
   122719     sz = 0;
   122720     pStart = 0;
   122721   }else if( pBuf==0 ){
   122722     sqlite3BeginBenignMalloc();
   122723     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
   122724     sqlite3EndBenignMalloc();
   122725     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
   122726   }else{
   122727     pStart = pBuf;
   122728   }
   122729   db->lookaside.pStart = pStart;
   122730   db->lookaside.pFree = 0;
   122731   db->lookaside.sz = (u16)sz;
   122732   if( pStart ){
   122733     int i;
   122734     LookasideSlot *p;
   122735     assert( sz > (int)sizeof(LookasideSlot*) );
   122736     p = (LookasideSlot*)pStart;
   122737     for(i=cnt-1; i>=0; i--){
   122738       p->pNext = db->lookaside.pFree;
   122739       db->lookaside.pFree = p;
   122740       p = (LookasideSlot*)&((u8*)p)[sz];
   122741     }
   122742     db->lookaside.pEnd = p;
   122743     db->lookaside.bEnabled = 1;
   122744     db->lookaside.bMalloced = pBuf==0 ?1:0;
   122745   }else{
   122746     db->lookaside.pStart = db;
   122747     db->lookaside.pEnd = db;
   122748     db->lookaside.bEnabled = 0;
   122749     db->lookaside.bMalloced = 0;
   122750   }
   122751   return SQLITE_OK;
   122752 }
   122753 
   122754 /*
   122755 ** Return the mutex associated with a database connection.
   122756 */
   122757 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
   122758   return db->mutex;
   122759 }
   122760 
   122761 /*
   122762 ** Free up as much memory as we can from the given database
   122763 ** connection.
   122764 */
   122765 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
   122766   int i;
   122767   sqlite3_mutex_enter(db->mutex);
   122768   sqlite3BtreeEnterAll(db);
   122769   for(i=0; i<db->nDb; i++){
   122770     Btree *pBt = db->aDb[i].pBt;
   122771     if( pBt ){
   122772       Pager *pPager = sqlite3BtreePager(pBt);
   122773       sqlite3PagerShrink(pPager);
   122774     }
   122775   }
   122776   sqlite3BtreeLeaveAll(db);
   122777   sqlite3_mutex_leave(db->mutex);
   122778   return SQLITE_OK;
   122779 }
   122780 
   122781 /*
   122782 ** Configuration settings for an individual database connection
   122783 */
   122784 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
   122785   va_list ap;
   122786   int rc;
   122787   va_start(ap, op);
   122788   switch( op ){
   122789     case SQLITE_DBCONFIG_LOOKASIDE: {
   122790       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
   122791       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
   122792       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
   122793       rc = setupLookaside(db, pBuf, sz, cnt);
   122794       break;
   122795     }
   122796     default: {
   122797       static const struct {
   122798         int op;      /* The opcode */
   122799         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
   122800       } aFlagOp[] = {
   122801         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
   122802         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
   122803       };
   122804       unsigned int i;
   122805       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
   122806       for(i=0; i<ArraySize(aFlagOp); i++){
   122807         if( aFlagOp[i].op==op ){
   122808           int onoff = va_arg(ap, int);
   122809           int *pRes = va_arg(ap, int*);
   122810           int oldFlags = db->flags;
   122811           if( onoff>0 ){
   122812             db->flags |= aFlagOp[i].mask;
   122813           }else if( onoff==0 ){
   122814             db->flags &= ~aFlagOp[i].mask;
   122815           }
   122816           if( oldFlags!=db->flags ){
   122817             sqlite3ExpirePreparedStatements(db);
   122818           }
   122819           if( pRes ){
   122820             *pRes = (db->flags & aFlagOp[i].mask)!=0;
   122821           }
   122822           rc = SQLITE_OK;
   122823           break;
   122824         }
   122825       }
   122826       break;
   122827     }
   122828   }
   122829   va_end(ap);
   122830   return rc;
   122831 }
   122832 
   122833 
   122834 /*
   122835 ** Return true if the buffer z[0..n-1] contains all spaces.
   122836 */
   122837 static int allSpaces(const char *z, int n){
   122838   while( n>0 && z[n-1]==' ' ){ n--; }
   122839   return n==0;
   122840 }
   122841 
   122842 /*
   122843 ** This is the default collating function named "BINARY" which is always
   122844 ** available.
   122845 **
   122846 ** If the padFlag argument is not NULL then space padding at the end
   122847 ** of strings is ignored.  This implements the RTRIM collation.
   122848 */
   122849 static int binCollFunc(
   122850   void *padFlag,
   122851   int nKey1, const void *pKey1,
   122852   int nKey2, const void *pKey2
   122853 ){
   122854   int rc, n;
   122855   n = nKey1<nKey2 ? nKey1 : nKey2;
   122856   rc = memcmp(pKey1, pKey2, n);
   122857   if( rc==0 ){
   122858     if( padFlag
   122859      && allSpaces(((char*)pKey1)+n, nKey1-n)
   122860      && allSpaces(((char*)pKey2)+n, nKey2-n)
   122861     ){
   122862       /* Leave rc unchanged at 0 */
   122863     }else{
   122864       rc = nKey1 - nKey2;
   122865     }
   122866   }
   122867   return rc;
   122868 }
   122869 
   122870 /*
   122871 ** Another built-in collating sequence: NOCASE.
   122872 **
   122873 ** This collating sequence is intended to be used for "case independent
   122874 ** comparison". SQLite's knowledge of upper and lower case equivalents
   122875 ** extends only to the 26 characters used in the English language.
   122876 **
   122877 ** At the moment there is only a UTF-8 implementation.
   122878 */
   122879 static int nocaseCollatingFunc(
   122880   void *NotUsed,
   122881   int nKey1, const void *pKey1,
   122882   int nKey2, const void *pKey2
   122883 ){
   122884   int r = sqlite3StrNICmp(
   122885       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
   122886   UNUSED_PARAMETER(NotUsed);
   122887   if( 0==r ){
   122888     r = nKey1-nKey2;
   122889   }
   122890   return r;
   122891 }
   122892 
   122893 /*
   122894 ** Return the ROWID of the most recent insert
   122895 */
   122896 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
   122897   return db->lastRowid;
   122898 }
   122899 
   122900 /*
   122901 ** Return the number of changes in the most recent call to sqlite3_exec().
   122902 */
   122903 SQLITE_API int sqlite3_changes(sqlite3 *db){
   122904   return db->nChange;
   122905 }
   122906 
   122907 /*
   122908 ** Return the number of changes since the database handle was opened.
   122909 */
   122910 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
   122911   return db->nTotalChange;
   122912 }
   122913 
   122914 /*
   122915 ** Close all open savepoints. This function only manipulates fields of the
   122916 ** database handle object, it does not close any savepoints that may be open
   122917 ** at the b-tree/pager level.
   122918 */
   122919 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
   122920   while( db->pSavepoint ){
   122921     Savepoint *pTmp = db->pSavepoint;
   122922     db->pSavepoint = pTmp->pNext;
   122923     sqlite3DbFree(db, pTmp);
   122924   }
   122925   db->nSavepoint = 0;
   122926   db->nStatement = 0;
   122927   db->isTransactionSavepoint = 0;
   122928 }
   122929 
   122930 /*
   122931 ** Invoke the destructor function associated with FuncDef p, if any. Except,
   122932 ** if this is not the last copy of the function, do not invoke it. Multiple
   122933 ** copies of a single function are created when create_function() is called
   122934 ** with SQLITE_ANY as the encoding.
   122935 */
   122936 static void functionDestroy(sqlite3 *db, FuncDef *p){
   122937   FuncDestructor *pDestructor = p->pDestructor;
   122938   if( pDestructor ){
   122939     pDestructor->nRef--;
   122940     if( pDestructor->nRef==0 ){
   122941       pDestructor->xDestroy(pDestructor->pUserData);
   122942       sqlite3DbFree(db, pDestructor);
   122943     }
   122944   }
   122945 }
   122946 
   122947 /*
   122948 ** Disconnect all sqlite3_vtab objects that belong to database connection
   122949 ** db. This is called when db is being closed.
   122950 */
   122951 static void disconnectAllVtab(sqlite3 *db){
   122952 #ifndef SQLITE_OMIT_VIRTUALTABLE
   122953   int i;
   122954   sqlite3BtreeEnterAll(db);
   122955   for(i=0; i<db->nDb; i++){
   122956     Schema *pSchema = db->aDb[i].pSchema;
   122957     if( db->aDb[i].pSchema ){
   122958       HashElem *p;
   122959       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
   122960         Table *pTab = (Table *)sqliteHashData(p);
   122961         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
   122962       }
   122963     }
   122964   }
   122965   sqlite3VtabUnlockList(db);
   122966   sqlite3BtreeLeaveAll(db);
   122967 #else
   122968   UNUSED_PARAMETER(db);
   122969 #endif
   122970 }
   122971 
   122972 /*
   122973 ** Return TRUE if database connection db has unfinalized prepared
   122974 ** statements or unfinished sqlite3_backup objects.
   122975 */
   122976 static int connectionIsBusy(sqlite3 *db){
   122977   int j;
   122978   assert( sqlite3_mutex_held(db->mutex) );
   122979   if( db->pVdbe ) return 1;
   122980   for(j=0; j<db->nDb; j++){
   122981     Btree *pBt = db->aDb[j].pBt;
   122982     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
   122983   }
   122984   return 0;
   122985 }
   122986 
   122987 /*
   122988 ** Close an existing SQLite database
   122989 */
   122990 static int sqlite3Close(sqlite3 *db, int forceZombie){
   122991   if( !db ){
   122992     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
   122993     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
   122994     return SQLITE_OK;
   122995   }
   122996   if( !sqlite3SafetyCheckSickOrOk(db) ){
   122997     return SQLITE_MISUSE_BKPT;
   122998   }
   122999   sqlite3_mutex_enter(db->mutex);
   123000 
   123001   /* Force xDisconnect calls on all virtual tables */
   123002   disconnectAllVtab(db);
   123003 
   123004   /* If a transaction is open, the disconnectAllVtab() call above
   123005   ** will not have called the xDisconnect() method on any virtual
   123006   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
   123007   ** call will do so. We need to do this before the check for active
   123008   ** SQL statements below, as the v-table implementation may be storing
   123009   ** some prepared statements internally.
   123010   */
   123011   sqlite3VtabRollback(db);
   123012 
   123013   /* Legacy behavior (sqlite3_close() behavior) is to return
   123014   ** SQLITE_BUSY if the connection can not be closed immediately.
   123015   */
   123016   if( !forceZombie && connectionIsBusy(db) ){
   123017     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
   123018        "statements or unfinished backups");
   123019     sqlite3_mutex_leave(db->mutex);
   123020     return SQLITE_BUSY;
   123021   }
   123022 
   123023 #ifdef SQLITE_ENABLE_SQLLOG
   123024   if( sqlite3GlobalConfig.xSqllog ){
   123025     /* Closing the handle. Fourth parameter is passed the value 2. */
   123026     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
   123027   }
   123028 #endif
   123029 
   123030   /* Convert the connection into a zombie and then close it.
   123031   */
   123032   db->magic = SQLITE_MAGIC_ZOMBIE;
   123033   sqlite3LeaveMutexAndCloseZombie(db);
   123034   return SQLITE_OK;
   123035 }
   123036 
   123037 /*
   123038 ** Two variations on the public interface for closing a database
   123039 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
   123040 ** leaves the connection option if there are unfinalized prepared
   123041 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
   123042 ** version forces the connection to become a zombie if there are
   123043 ** unclosed resources, and arranges for deallocation when the last
   123044 ** prepare statement or sqlite3_backup closes.
   123045 */
   123046 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
   123047 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
   123048 
   123049 
   123050 /*
   123051 ** Close the mutex on database connection db.
   123052 **
   123053 ** Furthermore, if database connection db is a zombie (meaning that there
   123054 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
   123055 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
   123056 ** finished, then free all resources.
   123057 */
   123058 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
   123059   HashElem *i;                    /* Hash table iterator */
   123060   int j;
   123061 
   123062   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
   123063   ** or if the connection has not yet been closed by sqlite3_close_v2(),
   123064   ** then just leave the mutex and return.
   123065   */
   123066   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
   123067     sqlite3_mutex_leave(db->mutex);
   123068     return;
   123069   }
   123070 
   123071   /* If we reach this point, it means that the database connection has
   123072   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
   123073   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
   123074   ** go ahead and free all resources.
   123075   */
   123076 
   123077   /* If a transaction is open, roll it back. This also ensures that if
   123078   ** any database schemas have been modified by an uncommitted transaction
   123079   ** they are reset. And that the required b-tree mutex is held to make
   123080   ** the pager rollback and schema reset an atomic operation. */
   123081   sqlite3RollbackAll(db, SQLITE_OK);
   123082 
   123083   /* Free any outstanding Savepoint structures. */
   123084   sqlite3CloseSavepoints(db);
   123085 
   123086   /* Close all database connections */
   123087   for(j=0; j<db->nDb; j++){
   123088     struct Db *pDb = &db->aDb[j];
   123089     if( pDb->pBt ){
   123090       sqlite3BtreeClose(pDb->pBt);
   123091       pDb->pBt = 0;
   123092       if( j!=1 ){
   123093         pDb->pSchema = 0;
   123094       }
   123095     }
   123096   }
   123097   /* Clear the TEMP schema separately and last */
   123098   if( db->aDb[1].pSchema ){
   123099     sqlite3SchemaClear(db->aDb[1].pSchema);
   123100   }
   123101   sqlite3VtabUnlockList(db);
   123102 
   123103   /* Free up the array of auxiliary databases */
   123104   sqlite3CollapseDatabaseArray(db);
   123105   assert( db->nDb<=2 );
   123106   assert( db->aDb==db->aDbStatic );
   123107 
   123108   /* Tell the code in notify.c that the connection no longer holds any
   123109   ** locks and does not require any further unlock-notify callbacks.
   123110   */
   123111   sqlite3ConnectionClosed(db);
   123112 
   123113   for(j=0; j<ArraySize(db->aFunc.a); j++){
   123114     FuncDef *pNext, *pHash, *p;
   123115     for(p=db->aFunc.a[j]; p; p=pHash){
   123116       pHash = p->pHash;
   123117       while( p ){
   123118         functionDestroy(db, p);
   123119         pNext = p->pNext;
   123120         sqlite3DbFree(db, p);
   123121         p = pNext;
   123122       }
   123123     }
   123124   }
   123125   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
   123126     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
   123127     /* Invoke any destructors registered for collation sequence user data. */
   123128     for(j=0; j<3; j++){
   123129       if( pColl[j].xDel ){
   123130         pColl[j].xDel(pColl[j].pUser);
   123131       }
   123132     }
   123133     sqlite3DbFree(db, pColl);
   123134   }
   123135   sqlite3HashClear(&db->aCollSeq);
   123136 #ifndef SQLITE_OMIT_VIRTUALTABLE
   123137   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
   123138     Module *pMod = (Module *)sqliteHashData(i);
   123139     if( pMod->xDestroy ){
   123140       pMod->xDestroy(pMod->pAux);
   123141     }
   123142     sqlite3DbFree(db, pMod);
   123143   }
   123144   sqlite3HashClear(&db->aModule);
   123145 #endif
   123146 
   123147   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
   123148   sqlite3ValueFree(db->pErr);
   123149   sqlite3CloseExtensions(db);
   123150 
   123151   db->magic = SQLITE_MAGIC_ERROR;
   123152 
   123153   /* The temp-database schema is allocated differently from the other schema
   123154   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
   123155   ** So it needs to be freed here. Todo: Why not roll the temp schema into
   123156   ** the same sqliteMalloc() as the one that allocates the database
   123157   ** structure?
   123158   */
   123159   sqlite3DbFree(db, db->aDb[1].pSchema);
   123160   sqlite3_mutex_leave(db->mutex);
   123161   db->magic = SQLITE_MAGIC_CLOSED;
   123162   sqlite3_mutex_free(db->mutex);
   123163   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
   123164   if( db->lookaside.bMalloced ){
   123165     sqlite3_free(db->lookaside.pStart);
   123166   }
   123167   sqlite3_free(db);
   123168 }
   123169 
   123170 /*
   123171 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
   123172 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
   123173 ** breaker") and made to return tripCode if there are any further
   123174 ** attempts to use that cursor.
   123175 */
   123176 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
   123177   int i;
   123178   int inTrans = 0;
   123179   assert( sqlite3_mutex_held(db->mutex) );
   123180   sqlite3BeginBenignMalloc();
   123181 
   123182   /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
   123183   ** This is important in case the transaction being rolled back has
   123184   ** modified the database schema. If the b-tree mutexes are not taken
   123185   ** here, then another shared-cache connection might sneak in between
   123186   ** the database rollback and schema reset, which can cause false
   123187   ** corruption reports in some cases.  */
   123188   sqlite3BtreeEnterAll(db);
   123189 
   123190   for(i=0; i<db->nDb; i++){
   123191     Btree *p = db->aDb[i].pBt;
   123192     if( p ){
   123193       if( sqlite3BtreeIsInTrans(p) ){
   123194         inTrans = 1;
   123195       }
   123196       sqlite3BtreeRollback(p, tripCode);
   123197     }
   123198   }
   123199   sqlite3VtabRollback(db);
   123200   sqlite3EndBenignMalloc();
   123201 
   123202   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
   123203     sqlite3ExpirePreparedStatements(db);
   123204     sqlite3ResetAllSchemasOfConnection(db);
   123205   }
   123206   sqlite3BtreeLeaveAll(db);
   123207 
   123208   /* Any deferred constraint violations have now been resolved. */
   123209   db->nDeferredCons = 0;
   123210   db->nDeferredImmCons = 0;
   123211   db->flags &= ~SQLITE_DeferFKs;
   123212 
   123213   /* If one has been configured, invoke the rollback-hook callback */
   123214   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
   123215     db->xRollbackCallback(db->pRollbackArg);
   123216   }
   123217 }
   123218 
   123219 /*
   123220 ** Return a static string containing the name corresponding to the error code
   123221 ** specified in the argument.
   123222 */
   123223 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
   123224 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
   123225   const char *zName = 0;
   123226   int i, origRc = rc;
   123227   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
   123228     switch( rc ){
   123229       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
   123230       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
   123231       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
   123232       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
   123233       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
   123234       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
   123235       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
   123236       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
   123237       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
   123238       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
   123239       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
   123240       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
   123241       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
   123242       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
   123243       case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
   123244       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
   123245       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
   123246       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
   123247       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
   123248       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
   123249       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
   123250       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
   123251       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
   123252       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
   123253       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
   123254       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
   123255       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
   123256       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
   123257       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
   123258       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
   123259       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
   123260       case SQLITE_IOERR_CHECKRESERVEDLOCK:
   123261                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
   123262       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
   123263       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
   123264       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
   123265       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
   123266       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
   123267       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
   123268       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
   123269       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
   123270       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
   123271       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
   123272       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
   123273       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
   123274       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
   123275       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
   123276       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
   123277       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
   123278       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
   123279       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
   123280       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
   123281       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
   123282       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
   123283       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
   123284       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
   123285       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
   123286       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
   123287       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
   123288       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
   123289       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
   123290       case SQLITE_CONSTRAINT_FOREIGNKEY:
   123291                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
   123292       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
   123293       case SQLITE_CONSTRAINT_PRIMARYKEY:
   123294                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
   123295       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
   123296       case SQLITE_CONSTRAINT_COMMITHOOK:
   123297                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
   123298       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
   123299       case SQLITE_CONSTRAINT_FUNCTION:
   123300                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
   123301       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
   123302       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
   123303       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
   123304       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
   123305       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
   123306       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
   123307       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
   123308       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
   123309       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
   123310       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
   123311       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
   123312       case SQLITE_NOTICE_RECOVER_ROLLBACK:
   123313                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
   123314       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
   123315       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
   123316       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
   123317     }
   123318   }
   123319   if( zName==0 ){
   123320     static char zBuf[50];
   123321     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
   123322     zName = zBuf;
   123323   }
   123324   return zName;
   123325 }
   123326 #endif
   123327 
   123328 /*
   123329 ** Return a static string that describes the kind of error specified in the
   123330 ** argument.
   123331 */
   123332 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
   123333   static const char* const aMsg[] = {
   123334     /* SQLITE_OK          */ "not an error",
   123335     /* SQLITE_ERROR       */ "SQL logic error or missing database",
   123336     /* SQLITE_INTERNAL    */ 0,
   123337     /* SQLITE_PERM        */ "access permission denied",
   123338     /* SQLITE_ABORT       */ "callback requested query abort",
   123339     /* SQLITE_BUSY        */ "database is locked",
   123340     /* SQLITE_LOCKED      */ "database table is locked",
   123341     /* SQLITE_NOMEM       */ "out of memory",
   123342     /* SQLITE_READONLY    */ "attempt to write a readonly database",
   123343     /* SQLITE_INTERRUPT   */ "interrupted",
   123344     /* SQLITE_IOERR       */ "disk I/O error",
   123345     /* SQLITE_CORRUPT     */ "database disk image is malformed",
   123346     /* SQLITE_NOTFOUND    */ "unknown operation",
   123347     /* SQLITE_FULL        */ "database or disk is full",
   123348     /* SQLITE_CANTOPEN    */ "unable to open database file",
   123349     /* SQLITE_PROTOCOL    */ "locking protocol",
   123350     /* SQLITE_EMPTY       */ "table contains no data",
   123351     /* SQLITE_SCHEMA      */ "database schema has changed",
   123352     /* SQLITE_TOOBIG      */ "string or blob too big",
   123353     /* SQLITE_CONSTRAINT  */ "constraint failed",
   123354     /* SQLITE_MISMATCH    */ "datatype mismatch",
   123355     /* SQLITE_MISUSE      */ "library routine called out of sequence",
   123356     /* SQLITE_NOLFS       */ "large file support is disabled",
   123357     /* SQLITE_AUTH        */ "authorization denied",
   123358     /* SQLITE_FORMAT      */ "auxiliary database format error",
   123359     /* SQLITE_RANGE       */ "bind or column index out of range",
   123360     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
   123361   };
   123362   const char *zErr = "unknown error";
   123363   switch( rc ){
   123364     case SQLITE_ABORT_ROLLBACK: {
   123365       zErr = "abort due to ROLLBACK";
   123366       break;
   123367     }
   123368     default: {
   123369       rc &= 0xff;
   123370       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
   123371         zErr = aMsg[rc];
   123372       }
   123373       break;
   123374     }
   123375   }
   123376   return zErr;
   123377 }
   123378 
   123379 /*
   123380 ** This routine implements a busy callback that sleeps and tries
   123381 ** again until a timeout value is reached.  The timeout value is
   123382 ** an integer number of milliseconds passed in as the first
   123383 ** argument.
   123384 */
   123385 static int sqliteDefaultBusyCallback(
   123386  void *ptr,               /* Database connection */
   123387  int count                /* Number of times table has been busy */
   123388 ){
   123389 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
   123390   static const u8 delays[] =
   123391      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
   123392   static const u8 totals[] =
   123393      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
   123394 # define NDELAY ArraySize(delays)
   123395   sqlite3 *db = (sqlite3 *)ptr;
   123396   int timeout = db->busyTimeout;
   123397   int delay, prior;
   123398 
   123399   assert( count>=0 );
   123400   if( count < NDELAY ){
   123401     delay = delays[count];
   123402     prior = totals[count];
   123403   }else{
   123404     delay = delays[NDELAY-1];
   123405     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
   123406   }
   123407   if( prior + delay > timeout ){
   123408     delay = timeout - prior;
   123409     if( delay<=0 ) return 0;
   123410   }
   123411   sqlite3OsSleep(db->pVfs, delay*1000);
   123412   return 1;
   123413 #else
   123414   sqlite3 *db = (sqlite3 *)ptr;
   123415   int timeout = ((sqlite3 *)ptr)->busyTimeout;
   123416   if( (count+1)*1000 > timeout ){
   123417     return 0;
   123418   }
   123419   sqlite3OsSleep(db->pVfs, 1000000);
   123420   return 1;
   123421 #endif
   123422 }
   123423 
   123424 /*
   123425 ** Invoke the given busy handler.
   123426 **
   123427 ** This routine is called when an operation failed with a lock.
   123428 ** If this routine returns non-zero, the lock is retried.  If it
   123429 ** returns 0, the operation aborts with an SQLITE_BUSY error.
   123430 */
   123431 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
   123432   int rc;
   123433   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
   123434   rc = p->xFunc(p->pArg, p->nBusy);
   123435   if( rc==0 ){
   123436     p->nBusy = -1;
   123437   }else{
   123438     p->nBusy++;
   123439   }
   123440   return rc;
   123441 }
   123442 
   123443 /*
   123444 ** This routine sets the busy callback for an Sqlite database to the
   123445 ** given callback function with the given argument.
   123446 */
   123447 SQLITE_API int sqlite3_busy_handler(
   123448   sqlite3 *db,
   123449   int (*xBusy)(void*,int),
   123450   void *pArg
   123451 ){
   123452   sqlite3_mutex_enter(db->mutex);
   123453   db->busyHandler.xFunc = xBusy;
   123454   db->busyHandler.pArg = pArg;
   123455   db->busyHandler.nBusy = 0;
   123456   db->busyTimeout = 0;
   123457   sqlite3_mutex_leave(db->mutex);
   123458   return SQLITE_OK;
   123459 }
   123460 
   123461 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   123462 /*
   123463 ** This routine sets the progress callback for an Sqlite database to the
   123464 ** given callback function with the given argument. The progress callback will
   123465 ** be invoked every nOps opcodes.
   123466 */
   123467 SQLITE_API void sqlite3_progress_handler(
   123468   sqlite3 *db,
   123469   int nOps,
   123470   int (*xProgress)(void*),
   123471   void *pArg
   123472 ){
   123473   sqlite3_mutex_enter(db->mutex);
   123474   if( nOps>0 ){
   123475     db->xProgress = xProgress;
   123476     db->nProgressOps = (unsigned)nOps;
   123477     db->pProgressArg = pArg;
   123478   }else{
   123479     db->xProgress = 0;
   123480     db->nProgressOps = 0;
   123481     db->pProgressArg = 0;
   123482   }
   123483   sqlite3_mutex_leave(db->mutex);
   123484 }
   123485 #endif
   123486 
   123487 
   123488 /*
   123489 ** This routine installs a default busy handler that waits for the
   123490 ** specified number of milliseconds before returning 0.
   123491 */
   123492 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
   123493   if( ms>0 ){
   123494     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
   123495     db->busyTimeout = ms;
   123496   }else{
   123497     sqlite3_busy_handler(db, 0, 0);
   123498   }
   123499   return SQLITE_OK;
   123500 }
   123501 
   123502 /*
   123503 ** Cause any pending operation to stop at its earliest opportunity.
   123504 */
   123505 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
   123506   db->u1.isInterrupted = 1;
   123507 }
   123508 
   123509 
   123510 /*
   123511 ** This function is exactly the same as sqlite3_create_function(), except
   123512 ** that it is designed to be called by internal code. The difference is
   123513 ** that if a malloc() fails in sqlite3_create_function(), an error code
   123514 ** is returned and the mallocFailed flag cleared.
   123515 */
   123516 SQLITE_PRIVATE int sqlite3CreateFunc(
   123517   sqlite3 *db,
   123518   const char *zFunctionName,
   123519   int nArg,
   123520   int enc,
   123521   void *pUserData,
   123522   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   123523   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   123524   void (*xFinal)(sqlite3_context*),
   123525   FuncDestructor *pDestructor
   123526 ){
   123527   FuncDef *p;
   123528   int nName;
   123529   int extraFlags;
   123530 
   123531   assert( sqlite3_mutex_held(db->mutex) );
   123532   if( zFunctionName==0 ||
   123533       (xFunc && (xFinal || xStep)) ||
   123534       (!xFunc && (xFinal && !xStep)) ||
   123535       (!xFunc && (!xFinal && xStep)) ||
   123536       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
   123537       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
   123538     return SQLITE_MISUSE_BKPT;
   123539   }
   123540 
   123541   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
   123542   extraFlags = enc &  SQLITE_DETERMINISTIC;
   123543   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
   123544 
   123545 #ifndef SQLITE_OMIT_UTF16
   123546   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   123547   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   123548   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   123549   **
   123550   ** If SQLITE_ANY is specified, add three versions of the function
   123551   ** to the hash table.
   123552   */
   123553   if( enc==SQLITE_UTF16 ){
   123554     enc = SQLITE_UTF16NATIVE;
   123555   }else if( enc==SQLITE_ANY ){
   123556     int rc;
   123557     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
   123558          pUserData, xFunc, xStep, xFinal, pDestructor);
   123559     if( rc==SQLITE_OK ){
   123560       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
   123561           pUserData, xFunc, xStep, xFinal, pDestructor);
   123562     }
   123563     if( rc!=SQLITE_OK ){
   123564       return rc;
   123565     }
   123566     enc = SQLITE_UTF16BE;
   123567   }
   123568 #else
   123569   enc = SQLITE_UTF8;
   123570 #endif
   123571 
   123572   /* Check if an existing function is being overridden or deleted. If so,
   123573   ** and there are active VMs, then return SQLITE_BUSY. If a function
   123574   ** is being overridden/deleted but there are no active VMs, allow the
   123575   ** operation to continue but invalidate all precompiled statements.
   123576   */
   123577   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
   123578   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
   123579     if( db->nVdbeActive ){
   123580       sqlite3Error(db, SQLITE_BUSY,
   123581         "unable to delete/modify user-function due to active statements");
   123582       assert( !db->mallocFailed );
   123583       return SQLITE_BUSY;
   123584     }else{
   123585       sqlite3ExpirePreparedStatements(db);
   123586     }
   123587   }
   123588 
   123589   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
   123590   assert(p || db->mallocFailed);
   123591   if( !p ){
   123592     return SQLITE_NOMEM;
   123593   }
   123594 
   123595   /* If an older version of the function with a configured destructor is
   123596   ** being replaced invoke the destructor function here. */
   123597   functionDestroy(db, p);
   123598 
   123599   if( pDestructor ){
   123600     pDestructor->nRef++;
   123601   }
   123602   p->pDestructor = pDestructor;
   123603   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
   123604   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
   123605   p->xFunc = xFunc;
   123606   p->xStep = xStep;
   123607   p->xFinalize = xFinal;
   123608   p->pUserData = pUserData;
   123609   p->nArg = (u16)nArg;
   123610   return SQLITE_OK;
   123611 }
   123612 
   123613 /*
   123614 ** Create new user functions.
   123615 */
   123616 SQLITE_API int sqlite3_create_function(
   123617   sqlite3 *db,
   123618   const char *zFunc,
   123619   int nArg,
   123620   int enc,
   123621   void *p,
   123622   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   123623   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   123624   void (*xFinal)(sqlite3_context*)
   123625 ){
   123626   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
   123627                                     xFinal, 0);
   123628 }
   123629 
   123630 SQLITE_API int sqlite3_create_function_v2(
   123631   sqlite3 *db,
   123632   const char *zFunc,
   123633   int nArg,
   123634   int enc,
   123635   void *p,
   123636   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   123637   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   123638   void (*xFinal)(sqlite3_context*),
   123639   void (*xDestroy)(void *)
   123640 ){
   123641   int rc = SQLITE_ERROR;
   123642   FuncDestructor *pArg = 0;
   123643   sqlite3_mutex_enter(db->mutex);
   123644   if( xDestroy ){
   123645     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
   123646     if( !pArg ){
   123647       xDestroy(p);
   123648       goto out;
   123649     }
   123650     pArg->xDestroy = xDestroy;
   123651     pArg->pUserData = p;
   123652   }
   123653   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
   123654   if( pArg && pArg->nRef==0 ){
   123655     assert( rc!=SQLITE_OK );
   123656     xDestroy(p);
   123657     sqlite3DbFree(db, pArg);
   123658   }
   123659 
   123660  out:
   123661   rc = sqlite3ApiExit(db, rc);
   123662   sqlite3_mutex_leave(db->mutex);
   123663   return rc;
   123664 }
   123665 
   123666 #ifndef SQLITE_OMIT_UTF16
   123667 SQLITE_API int sqlite3_create_function16(
   123668   sqlite3 *db,
   123669   const void *zFunctionName,
   123670   int nArg,
   123671   int eTextRep,
   123672   void *p,
   123673   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   123674   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   123675   void (*xFinal)(sqlite3_context*)
   123676 ){
   123677   int rc;
   123678   char *zFunc8;
   123679   sqlite3_mutex_enter(db->mutex);
   123680   assert( !db->mallocFailed );
   123681   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
   123682   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
   123683   sqlite3DbFree(db, zFunc8);
   123684   rc = sqlite3ApiExit(db, rc);
   123685   sqlite3_mutex_leave(db->mutex);
   123686   return rc;
   123687 }
   123688 #endif
   123689 
   123690 
   123691 /*
   123692 ** Declare that a function has been overloaded by a virtual table.
   123693 **
   123694 ** If the function already exists as a regular global function, then
   123695 ** this routine is a no-op.  If the function does not exist, then create
   123696 ** a new one that always throws a run-time error.
   123697 **
   123698 ** When virtual tables intend to provide an overloaded function, they
   123699 ** should call this routine to make sure the global function exists.
   123700 ** A global function must exist in order for name resolution to work
   123701 ** properly.
   123702 */
   123703 SQLITE_API int sqlite3_overload_function(
   123704   sqlite3 *db,
   123705   const char *zName,
   123706   int nArg
   123707 ){
   123708   int nName = sqlite3Strlen30(zName);
   123709   int rc = SQLITE_OK;
   123710   sqlite3_mutex_enter(db->mutex);
   123711   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
   123712     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
   123713                            0, sqlite3InvalidFunction, 0, 0, 0);
   123714   }
   123715   rc = sqlite3ApiExit(db, rc);
   123716   sqlite3_mutex_leave(db->mutex);
   123717   return rc;
   123718 }
   123719 
   123720 #ifndef SQLITE_OMIT_TRACE
   123721 /*
   123722 ** Register a trace function.  The pArg from the previously registered trace
   123723 ** is returned.
   123724 **
   123725 ** A NULL trace function means that no tracing is executes.  A non-NULL
   123726 ** trace is a pointer to a function that is invoked at the start of each
   123727 ** SQL statement.
   123728 */
   123729 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
   123730   void *pOld;
   123731   sqlite3_mutex_enter(db->mutex);
   123732   pOld = db->pTraceArg;
   123733   db->xTrace = xTrace;
   123734   db->pTraceArg = pArg;
   123735   sqlite3_mutex_leave(db->mutex);
   123736   return pOld;
   123737 }
   123738 /*
   123739 ** Register a profile function.  The pArg from the previously registered
   123740 ** profile function is returned.
   123741 **
   123742 ** A NULL profile function means that no profiling is executes.  A non-NULL
   123743 ** profile is a pointer to a function that is invoked at the conclusion of
   123744 ** each SQL statement that is run.
   123745 */
   123746 SQLITE_API void *sqlite3_profile(
   123747   sqlite3 *db,
   123748   void (*xProfile)(void*,const char*,sqlite_uint64),
   123749   void *pArg
   123750 ){
   123751   void *pOld;
   123752   sqlite3_mutex_enter(db->mutex);
   123753   pOld = db->pProfileArg;
   123754   db->xProfile = xProfile;
   123755   db->pProfileArg = pArg;
   123756   sqlite3_mutex_leave(db->mutex);
   123757   return pOld;
   123758 }
   123759 #endif /* SQLITE_OMIT_TRACE */
   123760 
   123761 /*
   123762 ** Register a function to be invoked when a transaction commits.
   123763 ** If the invoked function returns non-zero, then the commit becomes a
   123764 ** rollback.
   123765 */
   123766 SQLITE_API void *sqlite3_commit_hook(
   123767   sqlite3 *db,              /* Attach the hook to this database */
   123768   int (*xCallback)(void*),  /* Function to invoke on each commit */
   123769   void *pArg                /* Argument to the function */
   123770 ){
   123771   void *pOld;
   123772   sqlite3_mutex_enter(db->mutex);
   123773   pOld = db->pCommitArg;
   123774   db->xCommitCallback = xCallback;
   123775   db->pCommitArg = pArg;
   123776   sqlite3_mutex_leave(db->mutex);
   123777   return pOld;
   123778 }
   123779 
   123780 /*
   123781 ** Register a callback to be invoked each time a row is updated,
   123782 ** inserted or deleted using this database connection.
   123783 */
   123784 SQLITE_API void *sqlite3_update_hook(
   123785   sqlite3 *db,              /* Attach the hook to this database */
   123786   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
   123787   void *pArg                /* Argument to the function */
   123788 ){
   123789   void *pRet;
   123790   sqlite3_mutex_enter(db->mutex);
   123791   pRet = db->pUpdateArg;
   123792   db->xUpdateCallback = xCallback;
   123793   db->pUpdateArg = pArg;
   123794   sqlite3_mutex_leave(db->mutex);
   123795   return pRet;
   123796 }
   123797 
   123798 /*
   123799 ** Register a callback to be invoked each time a transaction is rolled
   123800 ** back by this database connection.
   123801 */
   123802 SQLITE_API void *sqlite3_rollback_hook(
   123803   sqlite3 *db,              /* Attach the hook to this database */
   123804   void (*xCallback)(void*), /* Callback function */
   123805   void *pArg                /* Argument to the function */
   123806 ){
   123807   void *pRet;
   123808   sqlite3_mutex_enter(db->mutex);
   123809   pRet = db->pRollbackArg;
   123810   db->xRollbackCallback = xCallback;
   123811   db->pRollbackArg = pArg;
   123812   sqlite3_mutex_leave(db->mutex);
   123813   return pRet;
   123814 }
   123815 
   123816 #ifndef SQLITE_OMIT_WAL
   123817 /*
   123818 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
   123819 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
   123820 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
   123821 ** wal_autocheckpoint()).
   123822 */
   123823 SQLITE_PRIVATE int sqlite3WalDefaultHook(
   123824   void *pClientData,     /* Argument */
   123825   sqlite3 *db,           /* Connection */
   123826   const char *zDb,       /* Database */
   123827   int nFrame             /* Size of WAL */
   123828 ){
   123829   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
   123830     sqlite3BeginBenignMalloc();
   123831     sqlite3_wal_checkpoint(db, zDb);
   123832     sqlite3EndBenignMalloc();
   123833   }
   123834   return SQLITE_OK;
   123835 }
   123836 #endif /* SQLITE_OMIT_WAL */
   123837 
   123838 /*
   123839 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
   123840 ** a database after committing a transaction if there are nFrame or
   123841 ** more frames in the log file. Passing zero or a negative value as the
   123842 ** nFrame parameter disables automatic checkpoints entirely.
   123843 **
   123844 ** The callback registered by this function replaces any existing callback
   123845 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
   123846 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
   123847 ** configured by this function.
   123848 */
   123849 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
   123850 #ifdef SQLITE_OMIT_WAL
   123851   UNUSED_PARAMETER(db);
   123852   UNUSED_PARAMETER(nFrame);
   123853 #else
   123854   if( nFrame>0 ){
   123855     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
   123856   }else{
   123857     sqlite3_wal_hook(db, 0, 0);
   123858   }
   123859 #endif
   123860   return SQLITE_OK;
   123861 }
   123862 
   123863 /*
   123864 ** Register a callback to be invoked each time a transaction is written
   123865 ** into the write-ahead-log by this database connection.
   123866 */
   123867 SQLITE_API void *sqlite3_wal_hook(
   123868   sqlite3 *db,                    /* Attach the hook to this db handle */
   123869   int(*xCallback)(void *, sqlite3*, const char*, int),
   123870   void *pArg                      /* First argument passed to xCallback() */
   123871 ){
   123872 #ifndef SQLITE_OMIT_WAL
   123873   void *pRet;
   123874   sqlite3_mutex_enter(db->mutex);
   123875   pRet = db->pWalArg;
   123876   db->xWalCallback = xCallback;
   123877   db->pWalArg = pArg;
   123878   sqlite3_mutex_leave(db->mutex);
   123879   return pRet;
   123880 #else
   123881   return 0;
   123882 #endif
   123883 }
   123884 
   123885 /*
   123886 ** Checkpoint database zDb.
   123887 */
   123888 SQLITE_API int sqlite3_wal_checkpoint_v2(
   123889   sqlite3 *db,                    /* Database handle */
   123890   const char *zDb,                /* Name of attached database (or NULL) */
   123891   int eMode,                      /* SQLITE_CHECKPOINT_* value */
   123892   int *pnLog,                     /* OUT: Size of WAL log in frames */
   123893   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
   123894 ){
   123895 #ifdef SQLITE_OMIT_WAL
   123896   return SQLITE_OK;
   123897 #else
   123898   int rc;                         /* Return code */
   123899   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
   123900 
   123901   /* Initialize the output variables to -1 in case an error occurs. */
   123902   if( pnLog ) *pnLog = -1;
   123903   if( pnCkpt ) *pnCkpt = -1;
   123904 
   123905   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
   123906   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
   123907   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
   123908   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
   123909     return SQLITE_MISUSE;
   123910   }
   123911 
   123912   sqlite3_mutex_enter(db->mutex);
   123913   if( zDb && zDb[0] ){
   123914     iDb = sqlite3FindDbName(db, zDb);
   123915   }
   123916   if( iDb<0 ){
   123917     rc = SQLITE_ERROR;
   123918     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
   123919   }else{
   123920     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
   123921     sqlite3Error(db, rc, 0);
   123922   }
   123923   rc = sqlite3ApiExit(db, rc);
   123924   sqlite3_mutex_leave(db->mutex);
   123925   return rc;
   123926 #endif
   123927 }
   123928 
   123929 
   123930 /*
   123931 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
   123932 ** to contains a zero-length string, all attached databases are
   123933 ** checkpointed.
   123934 */
   123935 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
   123936   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
   123937 }
   123938 
   123939 #ifndef SQLITE_OMIT_WAL
   123940 /*
   123941 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
   123942 ** not currently open in WAL mode.
   123943 **
   123944 ** If a transaction is open on the database being checkpointed, this
   123945 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
   123946 ** an error occurs while running the checkpoint, an SQLite error code is
   123947 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
   123948 **
   123949 ** The mutex on database handle db should be held by the caller. The mutex
   123950 ** associated with the specific b-tree being checkpointed is taken by
   123951 ** this function while the checkpoint is running.
   123952 **
   123953 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
   123954 ** checkpointed. If an error is encountered it is returned immediately -
   123955 ** no attempt is made to checkpoint any remaining databases.
   123956 **
   123957 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   123958 */
   123959 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
   123960   int rc = SQLITE_OK;             /* Return code */
   123961   int i;                          /* Used to iterate through attached dbs */
   123962   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
   123963 
   123964   assert( sqlite3_mutex_held(db->mutex) );
   123965   assert( !pnLog || *pnLog==-1 );
   123966   assert( !pnCkpt || *pnCkpt==-1 );
   123967 
   123968   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
   123969     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
   123970       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
   123971       pnLog = 0;
   123972       pnCkpt = 0;
   123973       if( rc==SQLITE_BUSY ){
   123974         bBusy = 1;
   123975         rc = SQLITE_OK;
   123976       }
   123977     }
   123978   }
   123979 
   123980   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
   123981 }
   123982 #endif /* SQLITE_OMIT_WAL */
   123983 
   123984 /*
   123985 ** This function returns true if main-memory should be used instead of
   123986 ** a temporary file for transient pager files and statement journals.
   123987 ** The value returned depends on the value of db->temp_store (runtime
   123988 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
   123989 ** following table describes the relationship between these two values
   123990 ** and this functions return value.
   123991 **
   123992 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
   123993 **   -----------------     --------------     ------------------------------
   123994 **   0                     any                file      (return 0)
   123995 **   1                     1                  file      (return 0)
   123996 **   1                     2                  memory    (return 1)
   123997 **   1                     0                  file      (return 0)
   123998 **   2                     1                  file      (return 0)
   123999 **   2                     2                  memory    (return 1)
   124000 **   2                     0                  memory    (return 1)
   124001 **   3                     any                memory    (return 1)
   124002 */
   124003 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
   124004 #if SQLITE_TEMP_STORE==1
   124005   return ( db->temp_store==2 );
   124006 #endif
   124007 #if SQLITE_TEMP_STORE==2
   124008   return ( db->temp_store!=1 );
   124009 #endif
   124010 #if SQLITE_TEMP_STORE==3
   124011   return 1;
   124012 #endif
   124013 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
   124014   return 0;
   124015 #endif
   124016 }
   124017 
   124018 /*
   124019 ** Return UTF-8 encoded English language explanation of the most recent
   124020 ** error.
   124021 */
   124022 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
   124023   const char *z;
   124024   if( !db ){
   124025     return sqlite3ErrStr(SQLITE_NOMEM);
   124026   }
   124027   if( !sqlite3SafetyCheckSickOrOk(db) ){
   124028     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
   124029   }
   124030   sqlite3_mutex_enter(db->mutex);
   124031   if( db->mallocFailed ){
   124032     z = sqlite3ErrStr(SQLITE_NOMEM);
   124033   }else{
   124034     testcase( db->pErr==0 );
   124035     z = (char*)sqlite3_value_text(db->pErr);
   124036     assert( !db->mallocFailed );
   124037     if( z==0 ){
   124038       z = sqlite3ErrStr(db->errCode);
   124039     }
   124040   }
   124041   sqlite3_mutex_leave(db->mutex);
   124042   return z;
   124043 }
   124044 
   124045 #ifndef SQLITE_OMIT_UTF16
   124046 /*
   124047 ** Return UTF-16 encoded English language explanation of the most recent
   124048 ** error.
   124049 */
   124050 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
   124051   static const u16 outOfMem[] = {
   124052     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
   124053   };
   124054   static const u16 misuse[] = {
   124055     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
   124056     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
   124057     'c', 'a', 'l', 'l', 'e', 'd', ' ',
   124058     'o', 'u', 't', ' ',
   124059     'o', 'f', ' ',
   124060     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
   124061   };
   124062 
   124063   const void *z;
   124064   if( !db ){
   124065     return (void *)outOfMem;
   124066   }
   124067   if( !sqlite3SafetyCheckSickOrOk(db) ){
   124068     return (void *)misuse;
   124069   }
   124070   sqlite3_mutex_enter(db->mutex);
   124071   if( db->mallocFailed ){
   124072     z = (void *)outOfMem;
   124073   }else{
   124074     z = sqlite3_value_text16(db->pErr);
   124075     if( z==0 ){
   124076       sqlite3Error(db, db->errCode, sqlite3ErrStr(db->errCode));
   124077       z = sqlite3_value_text16(db->pErr);
   124078     }
   124079     /* A malloc() may have failed within the call to sqlite3_value_text16()
   124080     ** above. If this is the case, then the db->mallocFailed flag needs to
   124081     ** be cleared before returning. Do this directly, instead of via
   124082     ** sqlite3ApiExit(), to avoid setting the database handle error message.
   124083     */
   124084     db->mallocFailed = 0;
   124085   }
   124086   sqlite3_mutex_leave(db->mutex);
   124087   return z;
   124088 }
   124089 #endif /* SQLITE_OMIT_UTF16 */
   124090 
   124091 /*
   124092 ** Return the most recent error code generated by an SQLite routine. If NULL is
   124093 ** passed to this function, we assume a malloc() failed during sqlite3_open().
   124094 */
   124095 SQLITE_API int sqlite3_errcode(sqlite3 *db){
   124096   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   124097     return SQLITE_MISUSE_BKPT;
   124098   }
   124099   if( !db || db->mallocFailed ){
   124100     return SQLITE_NOMEM;
   124101   }
   124102   return db->errCode & db->errMask;
   124103 }
   124104 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
   124105   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   124106     return SQLITE_MISUSE_BKPT;
   124107   }
   124108   if( !db || db->mallocFailed ){
   124109     return SQLITE_NOMEM;
   124110   }
   124111   return db->errCode;
   124112 }
   124113 
   124114 /*
   124115 ** Return a string that describes the kind of error specified in the
   124116 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
   124117 ** function.
   124118 */
   124119 SQLITE_API const char *sqlite3_errstr(int rc){
   124120   return sqlite3ErrStr(rc);
   124121 }
   124122 
   124123 /*
   124124 ** Invalidate all cached KeyInfo objects for database connection "db"
   124125 */
   124126 static void invalidateCachedKeyInfo(sqlite3 *db){
   124127   Db *pDb;                    /* A single database */
   124128   int iDb;                    /* The database index number */
   124129   HashElem *k;                /* For looping over tables in pDb */
   124130   Table *pTab;                /* A table in the database */
   124131   Index *pIdx;                /* Each index */
   124132 
   124133   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   124134     if( pDb->pBt==0 ) continue;
   124135     sqlite3BtreeEnter(pDb->pBt);
   124136     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   124137       pTab = (Table*)sqliteHashData(k);
   124138       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   124139         if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
   124140           sqlite3KeyInfoUnref(pIdx->pKeyInfo);
   124141           pIdx->pKeyInfo = 0;
   124142         }
   124143       }
   124144     }
   124145     sqlite3BtreeLeave(pDb->pBt);
   124146   }
   124147 }
   124148 
   124149 /*
   124150 ** Create a new collating function for database "db".  The name is zName
   124151 ** and the encoding is enc.
   124152 */
   124153 static int createCollation(
   124154   sqlite3* db,
   124155   const char *zName,
   124156   u8 enc,
   124157   void* pCtx,
   124158   int(*xCompare)(void*,int,const void*,int,const void*),
   124159   void(*xDel)(void*)
   124160 ){
   124161   CollSeq *pColl;
   124162   int enc2;
   124163   int nName = sqlite3Strlen30(zName);
   124164 
   124165   assert( sqlite3_mutex_held(db->mutex) );
   124166 
   124167   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   124168   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   124169   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   124170   */
   124171   enc2 = enc;
   124172   testcase( enc2==SQLITE_UTF16 );
   124173   testcase( enc2==SQLITE_UTF16_ALIGNED );
   124174   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
   124175     enc2 = SQLITE_UTF16NATIVE;
   124176   }
   124177   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
   124178     return SQLITE_MISUSE_BKPT;
   124179   }
   124180 
   124181   /* Check if this call is removing or replacing an existing collation
   124182   ** sequence. If so, and there are active VMs, return busy. If there
   124183   ** are no active VMs, invalidate any pre-compiled statements.
   124184   */
   124185   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   124186   if( pColl && pColl->xCmp ){
   124187     if( db->nVdbeActive ){
   124188       sqlite3Error(db, SQLITE_BUSY,
   124189         "unable to delete/modify collation sequence due to active statements");
   124190       return SQLITE_BUSY;
   124191     }
   124192     sqlite3ExpirePreparedStatements(db);
   124193     invalidateCachedKeyInfo(db);
   124194 
   124195     /* If collation sequence pColl was created directly by a call to
   124196     ** sqlite3_create_collation, and not generated by synthCollSeq(),
   124197     ** then any copies made by synthCollSeq() need to be invalidated.
   124198     ** Also, collation destructor - CollSeq.xDel() - function may need
   124199     ** to be called.
   124200     */
   124201     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
   124202       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   124203       int j;
   124204       for(j=0; j<3; j++){
   124205         CollSeq *p = &aColl[j];
   124206         if( p->enc==pColl->enc ){
   124207           if( p->xDel ){
   124208             p->xDel(p->pUser);
   124209           }
   124210           p->xCmp = 0;
   124211         }
   124212       }
   124213     }
   124214   }
   124215 
   124216   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
   124217   if( pColl==0 ) return SQLITE_NOMEM;
   124218   pColl->xCmp = xCompare;
   124219   pColl->pUser = pCtx;
   124220   pColl->xDel = xDel;
   124221   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
   124222   sqlite3Error(db, SQLITE_OK, 0);
   124223   return SQLITE_OK;
   124224 }
   124225 
   124226 
   124227 /*
   124228 ** This array defines hard upper bounds on limit values.  The
   124229 ** initializer must be kept in sync with the SQLITE_LIMIT_*
   124230 ** #defines in sqlite3.h.
   124231 */
   124232 static const int aHardLimit[] = {
   124233   SQLITE_MAX_LENGTH,
   124234   SQLITE_MAX_SQL_LENGTH,
   124235   SQLITE_MAX_COLUMN,
   124236   SQLITE_MAX_EXPR_DEPTH,
   124237   SQLITE_MAX_COMPOUND_SELECT,
   124238   SQLITE_MAX_VDBE_OP,
   124239   SQLITE_MAX_FUNCTION_ARG,
   124240   SQLITE_MAX_ATTACHED,
   124241   SQLITE_MAX_LIKE_PATTERN_LENGTH,
   124242   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
   124243   SQLITE_MAX_TRIGGER_DEPTH,
   124244 };
   124245 
   124246 /*
   124247 ** Make sure the hard limits are set to reasonable values
   124248 */
   124249 #if SQLITE_MAX_LENGTH<100
   124250 # error SQLITE_MAX_LENGTH must be at least 100
   124251 #endif
   124252 #if SQLITE_MAX_SQL_LENGTH<100
   124253 # error SQLITE_MAX_SQL_LENGTH must be at least 100
   124254 #endif
   124255 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
   124256 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
   124257 #endif
   124258 #if SQLITE_MAX_COMPOUND_SELECT<2
   124259 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
   124260 #endif
   124261 #if SQLITE_MAX_VDBE_OP<40
   124262 # error SQLITE_MAX_VDBE_OP must be at least 40
   124263 #endif
   124264 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
   124265 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
   124266 #endif
   124267 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
   124268 # error SQLITE_MAX_ATTACHED must be between 0 and 125
   124269 #endif
   124270 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
   124271 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
   124272 #endif
   124273 #if SQLITE_MAX_COLUMN>32767
   124274 # error SQLITE_MAX_COLUMN must not exceed 32767
   124275 #endif
   124276 #if SQLITE_MAX_TRIGGER_DEPTH<1
   124277 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
   124278 #endif
   124279 
   124280 
   124281 /*
   124282 ** Change the value of a limit.  Report the old value.
   124283 ** If an invalid limit index is supplied, report -1.
   124284 ** Make no changes but still report the old value if the
   124285 ** new limit is negative.
   124286 **
   124287 ** A new lower limit does not shrink existing constructs.
   124288 ** It merely prevents new constructs that exceed the limit
   124289 ** from forming.
   124290 */
   124291 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   124292   int oldLimit;
   124293 
   124294 
   124295   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
   124296   ** there is a hard upper bound set at compile-time by a C preprocessor
   124297   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
   124298   ** "_MAX_".)
   124299   */
   124300   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
   124301   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
   124302   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
   124303   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
   124304   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
   124305   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
   124306   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
   124307   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
   124308   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
   124309                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
   124310   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
   124311   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
   124312   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
   124313 
   124314 
   124315   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
   124316     return -1;
   124317   }
   124318   oldLimit = db->aLimit[limitId];
   124319   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
   124320     if( newLimit>aHardLimit[limitId] ){
   124321       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
   124322     }
   124323     db->aLimit[limitId] = newLimit;
   124324   }
   124325   return oldLimit;                     /* IMP: R-53341-35419 */
   124326 }
   124327 
   124328 /*
   124329 ** This function is used to parse both URIs and non-URI filenames passed by the
   124330 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
   124331 ** URIs specified as part of ATTACH statements.
   124332 **
   124333 ** The first argument to this function is the name of the VFS to use (or
   124334 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
   124335 ** query parameter. The second argument contains the URI (or non-URI filename)
   124336 ** itself. When this function is called the *pFlags variable should contain
   124337 ** the default flags to open the database handle with. The value stored in
   124338 ** *pFlags may be updated before returning if the URI filename contains
   124339 ** "cache=xxx" or "mode=xxx" query parameters.
   124340 **
   124341 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
   124342 ** the VFS that should be used to open the database file. *pzFile is set to
   124343 ** point to a buffer containing the name of the file to open. It is the
   124344 ** responsibility of the caller to eventually call sqlite3_free() to release
   124345 ** this buffer.
   124346 **
   124347 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
   124348 ** may be set to point to a buffer containing an English language error
   124349 ** message. It is the responsibility of the caller to eventually release
   124350 ** this buffer by calling sqlite3_free().
   124351 */
   124352 SQLITE_PRIVATE int sqlite3ParseUri(
   124353   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
   124354   const char *zUri,               /* Nul-terminated URI to parse */
   124355   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
   124356   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
   124357   char **pzFile,                  /* OUT: Filename component of URI */
   124358   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
   124359 ){
   124360   int rc = SQLITE_OK;
   124361   unsigned int flags = *pFlags;
   124362   const char *zVfs = zDefaultVfs;
   124363   char *zFile;
   124364   char c;
   124365   int nUri = sqlite3Strlen30(zUri);
   124366 
   124367   assert( *pzErrMsg==0 );
   124368 
   124369   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
   124370    && nUri>=5 && memcmp(zUri, "file:", 5)==0
   124371   ){
   124372     char *zOpt;
   124373     int eState;                   /* Parser state when parsing URI */
   124374     int iIn;                      /* Input character index */
   124375     int iOut = 0;                 /* Output character index */
   124376     int nByte = nUri+2;           /* Bytes of space to allocate */
   124377 
   124378     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
   124379     ** method that there may be extra parameters following the file-name.  */
   124380     flags |= SQLITE_OPEN_URI;
   124381 
   124382     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
   124383     zFile = sqlite3_malloc(nByte);
   124384     if( !zFile ) return SQLITE_NOMEM;
   124385 
   124386     iIn = 5;
   124387 #ifndef SQLITE_ALLOW_URI_AUTHORITY
   124388     /* Discard the scheme and authority segments of the URI. */
   124389     if( zUri[5]=='/' && zUri[6]=='/' ){
   124390       iIn = 7;
   124391       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
   124392       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
   124393         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
   124394             iIn-7, &zUri[7]);
   124395         rc = SQLITE_ERROR;
   124396         goto parse_uri_out;
   124397       }
   124398     }
   124399 #endif
   124400 
   124401     /* Copy the filename and any query parameters into the zFile buffer.
   124402     ** Decode %HH escape codes along the way.
   124403     **
   124404     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
   124405     ** on the parsing context. As follows:
   124406     **
   124407     **   0: Parsing file-name.
   124408     **   1: Parsing name section of a name=value query parameter.
   124409     **   2: Parsing value section of a name=value query parameter.
   124410     */
   124411     eState = 0;
   124412     while( (c = zUri[iIn])!=0 && c!='#' ){
   124413       iIn++;
   124414       if( c=='%'
   124415        && sqlite3Isxdigit(zUri[iIn])
   124416        && sqlite3Isxdigit(zUri[iIn+1])
   124417       ){
   124418         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
   124419         octet += sqlite3HexToInt(zUri[iIn++]);
   124420 
   124421         assert( octet>=0 && octet<256 );
   124422         if( octet==0 ){
   124423           /* This branch is taken when "%00" appears within the URI. In this
   124424           ** case we ignore all text in the remainder of the path, name or
   124425           ** value currently being parsed. So ignore the current character
   124426           ** and skip to the next "?", "=" or "&", as appropriate. */
   124427           while( (c = zUri[iIn])!=0 && c!='#'
   124428               && (eState!=0 || c!='?')
   124429               && (eState!=1 || (c!='=' && c!='&'))
   124430               && (eState!=2 || c!='&')
   124431           ){
   124432             iIn++;
   124433           }
   124434           continue;
   124435         }
   124436         c = octet;
   124437       }else if( eState==1 && (c=='&' || c=='=') ){
   124438         if( zFile[iOut-1]==0 ){
   124439           /* An empty option name. Ignore this option altogether. */
   124440           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
   124441           continue;
   124442         }
   124443         if( c=='&' ){
   124444           zFile[iOut++] = '\0';
   124445         }else{
   124446           eState = 2;
   124447         }
   124448         c = 0;
   124449       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
   124450         c = 0;
   124451         eState = 1;
   124452       }
   124453       zFile[iOut++] = c;
   124454     }
   124455     if( eState==1 ) zFile[iOut++] = '\0';
   124456     zFile[iOut++] = '\0';
   124457     zFile[iOut++] = '\0';
   124458 
   124459     /* Check if there were any options specified that should be interpreted
   124460     ** here. Options that are interpreted here include "vfs" and those that
   124461     ** correspond to flags that may be passed to the sqlite3_open_v2()
   124462     ** method. */
   124463     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
   124464     while( zOpt[0] ){
   124465       int nOpt = sqlite3Strlen30(zOpt);
   124466       char *zVal = &zOpt[nOpt+1];
   124467       int nVal = sqlite3Strlen30(zVal);
   124468 
   124469       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
   124470         zVfs = zVal;
   124471       }else{
   124472         struct OpenMode {
   124473           const char *z;
   124474           int mode;
   124475         } *aMode = 0;
   124476         char *zModeType = 0;
   124477         int mask = 0;
   124478         int limit = 0;
   124479 
   124480         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
   124481           static struct OpenMode aCacheMode[] = {
   124482             { "shared",  SQLITE_OPEN_SHAREDCACHE },
   124483             { "private", SQLITE_OPEN_PRIVATECACHE },
   124484             { 0, 0 }
   124485           };
   124486 
   124487           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
   124488           aMode = aCacheMode;
   124489           limit = mask;
   124490           zModeType = "cache";
   124491         }
   124492         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
   124493           static struct OpenMode aOpenMode[] = {
   124494             { "ro",  SQLITE_OPEN_READONLY },
   124495             { "rw",  SQLITE_OPEN_READWRITE },
   124496             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
   124497             { "memory", SQLITE_OPEN_MEMORY },
   124498             { 0, 0 }
   124499           };
   124500 
   124501           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
   124502                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
   124503           aMode = aOpenMode;
   124504           limit = mask & flags;
   124505           zModeType = "access";
   124506         }
   124507 
   124508         if( aMode ){
   124509           int i;
   124510           int mode = 0;
   124511           for(i=0; aMode[i].z; i++){
   124512             const char *z = aMode[i].z;
   124513             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
   124514               mode = aMode[i].mode;
   124515               break;
   124516             }
   124517           }
   124518           if( mode==0 ){
   124519             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
   124520             rc = SQLITE_ERROR;
   124521             goto parse_uri_out;
   124522           }
   124523           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
   124524             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
   124525                                         zModeType, zVal);
   124526             rc = SQLITE_PERM;
   124527             goto parse_uri_out;
   124528           }
   124529           flags = (flags & ~mask) | mode;
   124530         }
   124531       }
   124532 
   124533       zOpt = &zVal[nVal+1];
   124534     }
   124535 
   124536   }else{
   124537     zFile = sqlite3_malloc(nUri+2);
   124538     if( !zFile ) return SQLITE_NOMEM;
   124539     memcpy(zFile, zUri, nUri);
   124540     zFile[nUri] = '\0';
   124541     zFile[nUri+1] = '\0';
   124542     flags &= ~SQLITE_OPEN_URI;
   124543   }
   124544 
   124545   *ppVfs = sqlite3_vfs_find(zVfs);
   124546   if( *ppVfs==0 ){
   124547     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
   124548     rc = SQLITE_ERROR;
   124549   }
   124550  parse_uri_out:
   124551   if( rc!=SQLITE_OK ){
   124552     sqlite3_free(zFile);
   124553     zFile = 0;
   124554   }
   124555   *pFlags = flags;
   124556   *pzFile = zFile;
   124557   return rc;
   124558 }
   124559 
   124560 
   124561 /*
   124562 ** This routine does the work of opening a database on behalf of
   124563 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
   124564 ** is UTF-8 encoded.
   124565 */
   124566 static int openDatabase(
   124567   const char *zFilename, /* Database filename UTF-8 encoded */
   124568   sqlite3 **ppDb,        /* OUT: Returned database handle */
   124569   unsigned int flags,    /* Operational flags */
   124570   const char *zVfs       /* Name of the VFS to use */
   124571 ){
   124572   sqlite3 *db;                    /* Store allocated handle here */
   124573   int rc;                         /* Return code */
   124574   int isThreadsafe;               /* True for threadsafe connections */
   124575   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
   124576   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
   124577 
   124578   *ppDb = 0;
   124579 #ifndef SQLITE_OMIT_AUTOINIT
   124580   rc = sqlite3_initialize();
   124581   if( rc ) return rc;
   124582 #endif
   124583 
   124584   /* Only allow sensible combinations of bits in the flags argument.
   124585   ** Throw an error if any non-sense combination is used.  If we
   124586   ** do not block illegal combinations here, it could trigger
   124587   ** assert() statements in deeper layers.  Sensible combinations
   124588   ** are:
   124589   **
   124590   **  1:  SQLITE_OPEN_READONLY
   124591   **  2:  SQLITE_OPEN_READWRITE
   124592   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
   124593   */
   124594   assert( SQLITE_OPEN_READONLY  == 0x01 );
   124595   assert( SQLITE_OPEN_READWRITE == 0x02 );
   124596   assert( SQLITE_OPEN_CREATE    == 0x04 );
   124597   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
   124598   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
   124599   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
   124600   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
   124601 
   124602   if( sqlite3GlobalConfig.bCoreMutex==0 ){
   124603     isThreadsafe = 0;
   124604   }else if( flags & SQLITE_OPEN_NOMUTEX ){
   124605     isThreadsafe = 0;
   124606   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
   124607     isThreadsafe = 1;
   124608   }else{
   124609     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
   124610   }
   124611   if( flags & SQLITE_OPEN_PRIVATECACHE ){
   124612     flags &= ~SQLITE_OPEN_SHAREDCACHE;
   124613   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
   124614     flags |= SQLITE_OPEN_SHAREDCACHE;
   124615   }
   124616 
   124617   /* Remove harmful bits from the flags parameter
   124618   **
   124619   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
   124620   ** dealt with in the previous code block.  Besides these, the only
   124621   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   124622   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
   124623   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
   124624   ** off all other flags.
   124625   */
   124626   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
   124627                SQLITE_OPEN_EXCLUSIVE |
   124628                SQLITE_OPEN_MAIN_DB |
   124629                SQLITE_OPEN_TEMP_DB |
   124630                SQLITE_OPEN_TRANSIENT_DB |
   124631                SQLITE_OPEN_MAIN_JOURNAL |
   124632                SQLITE_OPEN_TEMP_JOURNAL |
   124633                SQLITE_OPEN_SUBJOURNAL |
   124634                SQLITE_OPEN_MASTER_JOURNAL |
   124635                SQLITE_OPEN_NOMUTEX |
   124636                SQLITE_OPEN_FULLMUTEX |
   124637                SQLITE_OPEN_WAL
   124638              );
   124639 
   124640   /* Allocate the sqlite data structure */
   124641   db = sqlite3MallocZero( sizeof(sqlite3) );
   124642   if( db==0 ) goto opendb_out;
   124643   if( isThreadsafe ){
   124644     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   124645     if( db->mutex==0 ){
   124646       sqlite3_free(db);
   124647       db = 0;
   124648       goto opendb_out;
   124649     }
   124650   }
   124651   sqlite3_mutex_enter(db->mutex);
   124652   db->errMask = 0xff;
   124653   db->nDb = 2;
   124654   db->magic = SQLITE_MAGIC_BUSY;
   124655   db->aDb = db->aDbStatic;
   124656 
   124657   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   124658   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
   124659   db->autoCommit = 1;
   124660   db->nextAutovac = -1;
   124661   db->szMmap = sqlite3GlobalConfig.szMmap;
   124662   db->nextPagesize = 0;
   124663   db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
   124664 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
   124665                  | SQLITE_AutoIndex
   124666 #endif
   124667 #if SQLITE_DEFAULT_FILE_FORMAT<4
   124668                  | SQLITE_LegacyFileFmt
   124669 #endif
   124670 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   124671                  | SQLITE_LoadExtension
   124672 #endif
   124673 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   124674                  | SQLITE_RecTriggers
   124675 #endif
   124676 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
   124677                  | SQLITE_ForeignKeys
   124678 #endif
   124679       ;
   124680   sqlite3HashInit(&db->aCollSeq);
   124681 #ifndef SQLITE_OMIT_VIRTUALTABLE
   124682   sqlite3HashInit(&db->aModule);
   124683 #endif
   124684 
   124685   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   124686   ** and UTF-16, so add a version for each to avoid any unnecessary
   124687   ** conversions. The only error that can occur here is a malloc() failure.
   124688   */
   124689   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
   124690   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
   124691   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
   124692   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
   124693   if( db->mallocFailed ){
   124694     goto opendb_out;
   124695   }
   124696   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   124697   assert( db->pDfltColl!=0 );
   124698 
   124699   /* Also add a UTF-8 case-insensitive collation sequence. */
   124700   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
   124701 
   124702   /* Parse the filename/URI argument. */
   124703   db->openFlags = flags;
   124704   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
   124705   if( rc!=SQLITE_OK ){
   124706     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   124707     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
   124708     sqlite3_free(zErrMsg);
   124709     goto opendb_out;
   124710   }
   124711 
   124712   /* Open the backend database driver */
   124713   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
   124714                         flags | SQLITE_OPEN_MAIN_DB);
   124715   if( rc!=SQLITE_OK ){
   124716     if( rc==SQLITE_IOERR_NOMEM ){
   124717       rc = SQLITE_NOMEM;
   124718     }
   124719     sqlite3Error(db, rc, 0);
   124720     goto opendb_out;
   124721   }
   124722   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
   124723   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
   124724 
   124725 
   124726   /* The default safety_level for the main database is 'full'; for the temp
   124727   ** database it is 'NONE'. This matches the pager layer defaults.
   124728   */
   124729   db->aDb[0].zName = "main";
   124730   db->aDb[0].safety_level = 3;
   124731   db->aDb[1].zName = "temp";
   124732   db->aDb[1].safety_level = 1;
   124733 
   124734   db->magic = SQLITE_MAGIC_OPEN;
   124735   if( db->mallocFailed ){
   124736     goto opendb_out;
   124737   }
   124738 
   124739   /* Register all built-in functions, but do not attempt to read the
   124740   ** database schema yet. This is delayed until the first time the database
   124741   ** is accessed.
   124742   */
   124743   sqlite3Error(db, SQLITE_OK, 0);
   124744   sqlite3RegisterBuiltinFunctions(db);
   124745 
   124746   /* Load automatic extensions - extensions that have been registered
   124747   ** using the sqlite3_automatic_extension() API.
   124748   */
   124749   rc = sqlite3_errcode(db);
   124750   if( rc==SQLITE_OK ){
   124751     sqlite3AutoLoadExtensions(db);
   124752     rc = sqlite3_errcode(db);
   124753     if( rc!=SQLITE_OK ){
   124754       goto opendb_out;
   124755     }
   124756   }
   124757 
   124758 #ifdef SQLITE_ENABLE_FTS1
   124759   if( !db->mallocFailed ){
   124760     extern int sqlite3Fts1Init(sqlite3*);
   124761     rc = sqlite3Fts1Init(db);
   124762   }
   124763 #endif
   124764 
   124765 #ifdef SQLITE_ENABLE_FTS2
   124766   if( !db->mallocFailed && rc==SQLITE_OK ){
   124767     extern int sqlite3Fts2Init(sqlite3*);
   124768     rc = sqlite3Fts2Init(db);
   124769   }
   124770 #endif
   124771 
   124772 #ifdef SQLITE_ENABLE_FTS3
   124773   if( !db->mallocFailed && rc==SQLITE_OK ){
   124774     rc = sqlite3Fts3Init(db);
   124775   }
   124776 #endif
   124777 
   124778 #ifdef SQLITE_ENABLE_ICU
   124779   if( !db->mallocFailed && rc==SQLITE_OK ){
   124780     rc = sqlite3IcuInit(db);
   124781   }
   124782 #endif
   124783 
   124784 #ifdef SQLITE_ENABLE_RTREE
   124785   if( !db->mallocFailed && rc==SQLITE_OK){
   124786     rc = sqlite3RtreeInit(db);
   124787   }
   124788 #endif
   124789 
   124790   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
   124791   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
   124792   ** mode.  Doing nothing at all also makes NORMAL the default.
   124793   */
   124794 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   124795   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
   124796   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
   124797                           SQLITE_DEFAULT_LOCKING_MODE);
   124798 #endif
   124799 
   124800   if( rc ) sqlite3Error(db, rc, 0);
   124801 
   124802   /* Enable the lookaside-malloc subsystem */
   124803   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
   124804                         sqlite3GlobalConfig.nLookaside);
   124805 
   124806   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
   124807 
   124808 opendb_out:
   124809   sqlite3_free(zOpen);
   124810   if( db ){
   124811     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
   124812     sqlite3_mutex_leave(db->mutex);
   124813   }
   124814   rc = sqlite3_errcode(db);
   124815   assert( db!=0 || rc==SQLITE_NOMEM );
   124816   if( rc==SQLITE_NOMEM ){
   124817     sqlite3_close(db);
   124818     db = 0;
   124819   }else if( rc!=SQLITE_OK ){
   124820     db->magic = SQLITE_MAGIC_SICK;
   124821   }
   124822   *ppDb = db;
   124823 #ifdef SQLITE_ENABLE_SQLLOG
   124824   if( sqlite3GlobalConfig.xSqllog ){
   124825     /* Opening a db handle. Fourth parameter is passed 0. */
   124826     void *pArg = sqlite3GlobalConfig.pSqllogArg;
   124827     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
   124828   }
   124829 #endif
   124830   return sqlite3ApiExit(0, rc);
   124831 }
   124832 
   124833 /*
   124834 ** Open a new database handle.
   124835 */
   124836 SQLITE_API int sqlite3_open(
   124837   const char *zFilename,
   124838   sqlite3 **ppDb
   124839 ){
   124840   return openDatabase(zFilename, ppDb,
   124841                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   124842 }
   124843 SQLITE_API int sqlite3_open_v2(
   124844   const char *filename,   /* Database filename (UTF-8) */
   124845   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   124846   int flags,              /* Flags */
   124847   const char *zVfs        /* Name of VFS module to use */
   124848 ){
   124849   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
   124850 }
   124851 
   124852 #ifndef SQLITE_OMIT_UTF16
   124853 /*
   124854 ** Open a new database handle.
   124855 */
   124856 SQLITE_API int sqlite3_open16(
   124857   const void *zFilename,
   124858   sqlite3 **ppDb
   124859 ){
   124860   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   124861   sqlite3_value *pVal;
   124862   int rc;
   124863 
   124864   assert( zFilename );
   124865   assert( ppDb );
   124866   *ppDb = 0;
   124867 #ifndef SQLITE_OMIT_AUTOINIT
   124868   rc = sqlite3_initialize();
   124869   if( rc ) return rc;
   124870 #endif
   124871   pVal = sqlite3ValueNew(0);
   124872   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   124873   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   124874   if( zFilename8 ){
   124875     rc = openDatabase(zFilename8, ppDb,
   124876                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   124877     assert( *ppDb || rc==SQLITE_NOMEM );
   124878     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
   124879       ENC(*ppDb) = SQLITE_UTF16NATIVE;
   124880     }
   124881   }else{
   124882     rc = SQLITE_NOMEM;
   124883   }
   124884   sqlite3ValueFree(pVal);
   124885 
   124886   return sqlite3ApiExit(0, rc);
   124887 }
   124888 #endif /* SQLITE_OMIT_UTF16 */
   124889 
   124890 /*
   124891 ** Register a new collation sequence with the database handle db.
   124892 */
   124893 SQLITE_API int sqlite3_create_collation(
   124894   sqlite3* db,
   124895   const char *zName,
   124896   int enc,
   124897   void* pCtx,
   124898   int(*xCompare)(void*,int,const void*,int,const void*)
   124899 ){
   124900   int rc;
   124901   sqlite3_mutex_enter(db->mutex);
   124902   assert( !db->mallocFailed );
   124903   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
   124904   rc = sqlite3ApiExit(db, rc);
   124905   sqlite3_mutex_leave(db->mutex);
   124906   return rc;
   124907 }
   124908 
   124909 /*
   124910 ** Register a new collation sequence with the database handle db.
   124911 */
   124912 SQLITE_API int sqlite3_create_collation_v2(
   124913   sqlite3* db,
   124914   const char *zName,
   124915   int enc,
   124916   void* pCtx,
   124917   int(*xCompare)(void*,int,const void*,int,const void*),
   124918   void(*xDel)(void*)
   124919 ){
   124920   int rc;
   124921   sqlite3_mutex_enter(db->mutex);
   124922   assert( !db->mallocFailed );
   124923   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
   124924   rc = sqlite3ApiExit(db, rc);
   124925   sqlite3_mutex_leave(db->mutex);
   124926   return rc;
   124927 }
   124928 
   124929 #ifndef SQLITE_OMIT_UTF16
   124930 /*
   124931 ** Register a new collation sequence with the database handle db.
   124932 */
   124933 SQLITE_API int sqlite3_create_collation16(
   124934   sqlite3* db,
   124935   const void *zName,
   124936   int enc,
   124937   void* pCtx,
   124938   int(*xCompare)(void*,int,const void*,int,const void*)
   124939 ){
   124940   int rc = SQLITE_OK;
   124941   char *zName8;
   124942   sqlite3_mutex_enter(db->mutex);
   124943   assert( !db->mallocFailed );
   124944   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
   124945   if( zName8 ){
   124946     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
   124947     sqlite3DbFree(db, zName8);
   124948   }
   124949   rc = sqlite3ApiExit(db, rc);
   124950   sqlite3_mutex_leave(db->mutex);
   124951   return rc;
   124952 }
   124953 #endif /* SQLITE_OMIT_UTF16 */
   124954 
   124955 /*
   124956 ** Register a collation sequence factory callback with the database handle
   124957 ** db. Replace any previously installed collation sequence factory.
   124958 */
   124959 SQLITE_API int sqlite3_collation_needed(
   124960   sqlite3 *db,
   124961   void *pCollNeededArg,
   124962   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
   124963 ){
   124964   sqlite3_mutex_enter(db->mutex);
   124965   db->xCollNeeded = xCollNeeded;
   124966   db->xCollNeeded16 = 0;
   124967   db->pCollNeededArg = pCollNeededArg;
   124968   sqlite3_mutex_leave(db->mutex);
   124969   return SQLITE_OK;
   124970 }
   124971 
   124972 #ifndef SQLITE_OMIT_UTF16
   124973 /*
   124974 ** Register a collation sequence factory callback with the database handle
   124975 ** db. Replace any previously installed collation sequence factory.
   124976 */
   124977 SQLITE_API int sqlite3_collation_needed16(
   124978   sqlite3 *db,
   124979   void *pCollNeededArg,
   124980   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
   124981 ){
   124982   sqlite3_mutex_enter(db->mutex);
   124983   db->xCollNeeded = 0;
   124984   db->xCollNeeded16 = xCollNeeded16;
   124985   db->pCollNeededArg = pCollNeededArg;
   124986   sqlite3_mutex_leave(db->mutex);
   124987   return SQLITE_OK;
   124988 }
   124989 #endif /* SQLITE_OMIT_UTF16 */
   124990 
   124991 #ifndef SQLITE_OMIT_DEPRECATED
   124992 /*
   124993 ** This function is now an anachronism. It used to be used to recover from a
   124994 ** malloc() failure, but SQLite now does this automatically.
   124995 */
   124996 SQLITE_API int sqlite3_global_recover(void){
   124997   return SQLITE_OK;
   124998 }
   124999 #endif
   125000 
   125001 /*
   125002 ** Test to see whether or not the database connection is in autocommit
   125003 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
   125004 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
   125005 ** by the next COMMIT or ROLLBACK.
   125006 */
   125007 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
   125008   return db->autoCommit;
   125009 }
   125010 
   125011 /*
   125012 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
   125013 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
   125014 ** constants.  They server two purposes:
   125015 **
   125016 **   1.  Serve as a convenient place to set a breakpoint in a debugger
   125017 **       to detect when version error conditions occurs.
   125018 **
   125019 **   2.  Invoke sqlite3_log() to provide the source code location where
   125020 **       a low-level error is first detected.
   125021 */
   125022 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
   125023   testcase( sqlite3GlobalConfig.xLog!=0 );
   125024   sqlite3_log(SQLITE_CORRUPT,
   125025               "database corruption at line %d of [%.10s]",
   125026               lineno, 20+sqlite3_sourceid());
   125027   return SQLITE_CORRUPT;
   125028 }
   125029 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
   125030   testcase( sqlite3GlobalConfig.xLog!=0 );
   125031   sqlite3_log(SQLITE_MISUSE,
   125032               "misuse at line %d of [%.10s]",
   125033               lineno, 20+sqlite3_sourceid());
   125034   return SQLITE_MISUSE;
   125035 }
   125036 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
   125037   testcase( sqlite3GlobalConfig.xLog!=0 );
   125038   sqlite3_log(SQLITE_CANTOPEN,
   125039               "cannot open file at line %d of [%.10s]",
   125040               lineno, 20+sqlite3_sourceid());
   125041   return SQLITE_CANTOPEN;
   125042 }
   125043 
   125044 
   125045 #ifndef SQLITE_OMIT_DEPRECATED
   125046 /*
   125047 ** This is a convenience routine that makes sure that all thread-specific
   125048 ** data for this thread has been deallocated.
   125049 **
   125050 ** SQLite no longer uses thread-specific data so this routine is now a
   125051 ** no-op.  It is retained for historical compatibility.
   125052 */
   125053 SQLITE_API void sqlite3_thread_cleanup(void){
   125054 }
   125055 #endif
   125056 
   125057 /*
   125058 ** Return meta information about a specific column of a database table.
   125059 ** See comment in sqlite3.h (sqlite.h.in) for details.
   125060 */
   125061 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   125062 SQLITE_API int sqlite3_table_column_metadata(
   125063   sqlite3 *db,                /* Connection handle */
   125064   const char *zDbName,        /* Database name or NULL */
   125065   const char *zTableName,     /* Table name */
   125066   const char *zColumnName,    /* Column name */
   125067   char const **pzDataType,    /* OUTPUT: Declared data type */
   125068   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   125069   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   125070   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   125071   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   125072 ){
   125073   int rc;
   125074   char *zErrMsg = 0;
   125075   Table *pTab = 0;
   125076   Column *pCol = 0;
   125077   int iCol;
   125078 
   125079   char const *zDataType = 0;
   125080   char const *zCollSeq = 0;
   125081   int notnull = 0;
   125082   int primarykey = 0;
   125083   int autoinc = 0;
   125084 
   125085   /* Ensure the database schema has been loaded */
   125086   sqlite3_mutex_enter(db->mutex);
   125087   sqlite3BtreeEnterAll(db);
   125088   rc = sqlite3Init(db, &zErrMsg);
   125089   if( SQLITE_OK!=rc ){
   125090     goto error_out;
   125091   }
   125092 
   125093   /* Locate the table in question */
   125094   pTab = sqlite3FindTable(db, zTableName, zDbName);
   125095   if( !pTab || pTab->pSelect ){
   125096     pTab = 0;
   125097     goto error_out;
   125098   }
   125099 
   125100   /* Find the column for which info is requested */
   125101   if( sqlite3IsRowid(zColumnName) ){
   125102     iCol = pTab->iPKey;
   125103     if( iCol>=0 ){
   125104       pCol = &pTab->aCol[iCol];
   125105     }
   125106   }else{
   125107     for(iCol=0; iCol<pTab->nCol; iCol++){
   125108       pCol = &pTab->aCol[iCol];
   125109       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
   125110         break;
   125111       }
   125112     }
   125113     if( iCol==pTab->nCol ){
   125114       pTab = 0;
   125115       goto error_out;
   125116     }
   125117   }
   125118 
   125119   /* The following block stores the meta information that will be returned
   125120   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   125121   ** and autoinc. At this point there are two possibilities:
   125122   **
   125123   **     1. The specified column name was rowid", "oid" or "_rowid_"
   125124   **        and there is no explicitly declared IPK column.
   125125   **
   125126   **     2. The table is not a view and the column name identified an
   125127   **        explicitly declared column. Copy meta information from *pCol.
   125128   */
   125129   if( pCol ){
   125130     zDataType = pCol->zType;
   125131     zCollSeq = pCol->zColl;
   125132     notnull = pCol->notNull!=0;
   125133     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
   125134     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
   125135   }else{
   125136     zDataType = "INTEGER";
   125137     primarykey = 1;
   125138   }
   125139   if( !zCollSeq ){
   125140     zCollSeq = "BINARY";
   125141   }
   125142 
   125143 error_out:
   125144   sqlite3BtreeLeaveAll(db);
   125145 
   125146   /* Whether the function call succeeded or failed, set the output parameters
   125147   ** to whatever their local counterparts contain. If an error did occur,
   125148   ** this has the effect of zeroing all output parameters.
   125149   */
   125150   if( pzDataType ) *pzDataType = zDataType;
   125151   if( pzCollSeq ) *pzCollSeq = zCollSeq;
   125152   if( pNotNull ) *pNotNull = notnull;
   125153   if( pPrimaryKey ) *pPrimaryKey = primarykey;
   125154   if( pAutoinc ) *pAutoinc = autoinc;
   125155 
   125156   if( SQLITE_OK==rc && !pTab ){
   125157     sqlite3DbFree(db, zErrMsg);
   125158     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
   125159         zColumnName);
   125160     rc = SQLITE_ERROR;
   125161   }
   125162   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
   125163   sqlite3DbFree(db, zErrMsg);
   125164   rc = sqlite3ApiExit(db, rc);
   125165   sqlite3_mutex_leave(db->mutex);
   125166   return rc;
   125167 }
   125168 #endif
   125169 
   125170 /*
   125171 ** Sleep for a little while.  Return the amount of time slept.
   125172 */
   125173 SQLITE_API int sqlite3_sleep(int ms){
   125174   sqlite3_vfs *pVfs;
   125175   int rc;
   125176   pVfs = sqlite3_vfs_find(0);
   125177   if( pVfs==0 ) return 0;
   125178 
   125179   /* This function works in milliseconds, but the underlying OsSleep()
   125180   ** API uses microseconds. Hence the 1000's.
   125181   */
   125182   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
   125183   return rc;
   125184 }
   125185 
   125186 /*
   125187 ** Enable or disable the extended result codes.
   125188 */
   125189 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
   125190   sqlite3_mutex_enter(db->mutex);
   125191   db->errMask = onoff ? 0xffffffff : 0xff;
   125192   sqlite3_mutex_leave(db->mutex);
   125193   return SQLITE_OK;
   125194 }
   125195 
   125196 /*
   125197 ** Invoke the xFileControl method on a particular database.
   125198 */
   125199 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
   125200   int rc = SQLITE_ERROR;
   125201   Btree *pBtree;
   125202 
   125203   sqlite3_mutex_enter(db->mutex);
   125204   pBtree = sqlite3DbNameToBtree(db, zDbName);
   125205   if( pBtree ){
   125206     Pager *pPager;
   125207     sqlite3_file *fd;
   125208     sqlite3BtreeEnter(pBtree);
   125209     pPager = sqlite3BtreePager(pBtree);
   125210     assert( pPager!=0 );
   125211     fd = sqlite3PagerFile(pPager);
   125212     assert( fd!=0 );
   125213     if( op==SQLITE_FCNTL_FILE_POINTER ){
   125214       *(sqlite3_file**)pArg = fd;
   125215       rc = SQLITE_OK;
   125216     }else if( fd->pMethods ){
   125217       rc = sqlite3OsFileControl(fd, op, pArg);
   125218     }else{
   125219       rc = SQLITE_NOTFOUND;
   125220     }
   125221     sqlite3BtreeLeave(pBtree);
   125222   }
   125223   sqlite3_mutex_leave(db->mutex);
   125224   return rc;
   125225 }
   125226 
   125227 /*
   125228 ** Interface to the testing logic.
   125229 */
   125230 SQLITE_API int sqlite3_test_control(int op, ...){
   125231   int rc = 0;
   125232 #ifndef SQLITE_OMIT_BUILTIN_TEST
   125233   va_list ap;
   125234   va_start(ap, op);
   125235   switch( op ){
   125236 
   125237     /*
   125238     ** Save the current state of the PRNG.
   125239     */
   125240     case SQLITE_TESTCTRL_PRNG_SAVE: {
   125241       sqlite3PrngSaveState();
   125242       break;
   125243     }
   125244 
   125245     /*
   125246     ** Restore the state of the PRNG to the last state saved using
   125247     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
   125248     ** this verb acts like PRNG_RESET.
   125249     */
   125250     case SQLITE_TESTCTRL_PRNG_RESTORE: {
   125251       sqlite3PrngRestoreState();
   125252       break;
   125253     }
   125254 
   125255     /*
   125256     ** Reset the PRNG back to its uninitialized state.  The next call
   125257     ** to sqlite3_randomness() will reseed the PRNG using a single call
   125258     ** to the xRandomness method of the default VFS.
   125259     */
   125260     case SQLITE_TESTCTRL_PRNG_RESET: {
   125261       sqlite3_randomness(0,0);
   125262       break;
   125263     }
   125264 
   125265     /*
   125266     **  sqlite3_test_control(BITVEC_TEST, size, program)
   125267     **
   125268     ** Run a test against a Bitvec object of size.  The program argument
   125269     ** is an array of integers that defines the test.  Return -1 on a
   125270     ** memory allocation error, 0 on success, or non-zero for an error.
   125271     ** See the sqlite3BitvecBuiltinTest() for additional information.
   125272     */
   125273     case SQLITE_TESTCTRL_BITVEC_TEST: {
   125274       int sz = va_arg(ap, int);
   125275       int *aProg = va_arg(ap, int*);
   125276       rc = sqlite3BitvecBuiltinTest(sz, aProg);
   125277       break;
   125278     }
   125279 
   125280     /*
   125281     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
   125282     **
   125283     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
   125284     ** if xCallback is not NULL.
   125285     **
   125286     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
   125287     ** is called immediately after installing the new callback and the return
   125288     ** value from sqlite3FaultSim(0) becomes the return from
   125289     ** sqlite3_test_control().
   125290     */
   125291     case SQLITE_TESTCTRL_FAULT_INSTALL: {
   125292       /* MSVC is picky about pulling func ptrs from va lists.
   125293       ** http://support.microsoft.com/kb/47961
   125294       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
   125295       */
   125296       typedef int(*TESTCALLBACKFUNC_t)(int);
   125297       sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
   125298       rc = sqlite3FaultSim(0);
   125299       break;
   125300     }
   125301 
   125302     /*
   125303     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
   125304     **
   125305     ** Register hooks to call to indicate which malloc() failures
   125306     ** are benign.
   125307     */
   125308     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
   125309       typedef void (*void_function)(void);
   125310       void_function xBenignBegin;
   125311       void_function xBenignEnd;
   125312       xBenignBegin = va_arg(ap, void_function);
   125313       xBenignEnd = va_arg(ap, void_function);
   125314       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
   125315       break;
   125316     }
   125317 
   125318     /*
   125319     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
   125320     **
   125321     ** Set the PENDING byte to the value in the argument, if X>0.
   125322     ** Make no changes if X==0.  Return the value of the pending byte
   125323     ** as it existing before this routine was called.
   125324     **
   125325     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
   125326     ** an incompatible database file format.  Changing the PENDING byte
   125327     ** while any database connection is open results in undefined and
   125328     ** dileterious behavior.
   125329     */
   125330     case SQLITE_TESTCTRL_PENDING_BYTE: {
   125331       rc = PENDING_BYTE;
   125332 #ifndef SQLITE_OMIT_WSD
   125333       {
   125334         unsigned int newVal = va_arg(ap, unsigned int);
   125335         if( newVal ) sqlite3PendingByte = newVal;
   125336       }
   125337 #endif
   125338       break;
   125339     }
   125340 
   125341     /*
   125342     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
   125343     **
   125344     ** This action provides a run-time test to see whether or not
   125345     ** assert() was enabled at compile-time.  If X is true and assert()
   125346     ** is enabled, then the return value is true.  If X is true and
   125347     ** assert() is disabled, then the return value is zero.  If X is
   125348     ** false and assert() is enabled, then the assertion fires and the
   125349     ** process aborts.  If X is false and assert() is disabled, then the
   125350     ** return value is zero.
   125351     */
   125352     case SQLITE_TESTCTRL_ASSERT: {
   125353       volatile int x = 0;
   125354       assert( (x = va_arg(ap,int))!=0 );
   125355       rc = x;
   125356       break;
   125357     }
   125358 
   125359 
   125360     /*
   125361     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
   125362     **
   125363     ** This action provides a run-time test to see how the ALWAYS and
   125364     ** NEVER macros were defined at compile-time.
   125365     **
   125366     ** The return value is ALWAYS(X).
   125367     **
   125368     ** The recommended test is X==2.  If the return value is 2, that means
   125369     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
   125370     ** default setting.  If the return value is 1, then ALWAYS() is either
   125371     ** hard-coded to true or else it asserts if its argument is false.
   125372     ** The first behavior (hard-coded to true) is the case if
   125373     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
   125374     ** behavior (assert if the argument to ALWAYS() is false) is the case if
   125375     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
   125376     **
   125377     ** The run-time test procedure might look something like this:
   125378     **
   125379     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
   125380     **      // ALWAYS() and NEVER() are no-op pass-through macros
   125381     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
   125382     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
   125383     **    }else{
   125384     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
   125385     **    }
   125386     */
   125387     case SQLITE_TESTCTRL_ALWAYS: {
   125388       int x = va_arg(ap,int);
   125389       rc = ALWAYS(x);
   125390       break;
   125391     }
   125392 
   125393     /*
   125394     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
   125395     **
   125396     ** The integer returned reveals the byte-order of the computer on which
   125397     ** SQLite is running:
   125398     **
   125399     **       1     big-endian,    determined at run-time
   125400     **      10     little-endian, determined at run-time
   125401     **  432101     big-endian,    determined at compile-time
   125402     **  123410     little-endian, determined at compile-time
   125403     */
   125404     case SQLITE_TESTCTRL_BYTEORDER: {
   125405       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
   125406       break;
   125407     }
   125408 
   125409     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
   125410     **
   125411     ** Set the nReserve size to N for the main database on the database
   125412     ** connection db.
   125413     */
   125414     case SQLITE_TESTCTRL_RESERVE: {
   125415       sqlite3 *db = va_arg(ap, sqlite3*);
   125416       int x = va_arg(ap,int);
   125417       sqlite3_mutex_enter(db->mutex);
   125418       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
   125419       sqlite3_mutex_leave(db->mutex);
   125420       break;
   125421     }
   125422 
   125423     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
   125424     **
   125425     ** Enable or disable various optimizations for testing purposes.  The
   125426     ** argument N is a bitmask of optimizations to be disabled.  For normal
   125427     ** operation N should be 0.  The idea is that a test program (like the
   125428     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
   125429     ** with various optimizations disabled to verify that the same answer
   125430     ** is obtained in every case.
   125431     */
   125432     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   125433       sqlite3 *db = va_arg(ap, sqlite3*);
   125434       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
   125435       break;
   125436     }
   125437 
   125438 #ifdef SQLITE_N_KEYWORD
   125439     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
   125440     **
   125441     ** If zWord is a keyword recognized by the parser, then return the
   125442     ** number of keywords.  Or if zWord is not a keyword, return 0.
   125443     **
   125444     ** This test feature is only available in the amalgamation since
   125445     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
   125446     ** is built using separate source files.
   125447     */
   125448     case SQLITE_TESTCTRL_ISKEYWORD: {
   125449       const char *zWord = va_arg(ap, const char*);
   125450       int n = sqlite3Strlen30(zWord);
   125451       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
   125452       break;
   125453     }
   125454 #endif
   125455 
   125456     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
   125457     **
   125458     ** Pass pFree into sqlite3ScratchFree().
   125459     ** If sz>0 then allocate a scratch buffer into pNew.
   125460     */
   125461     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
   125462       void *pFree, **ppNew;
   125463       int sz;
   125464       sz = va_arg(ap, int);
   125465       ppNew = va_arg(ap, void**);
   125466       pFree = va_arg(ap, void*);
   125467       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
   125468       sqlite3ScratchFree(pFree);
   125469       break;
   125470     }
   125471 
   125472     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
   125473     **
   125474     ** If parameter onoff is non-zero, configure the wrappers so that all
   125475     ** subsequent calls to localtime() and variants fail. If onoff is zero,
   125476     ** undo this setting.
   125477     */
   125478     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
   125479       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
   125480       break;
   125481     }
   125482 
   125483 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   125484     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
   125485     **                        sqlite3_stmt*,const char**);
   125486     **
   125487     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
   125488     ** a string that describes the optimized parse tree.  This test-control
   125489     ** returns a pointer to that string.
   125490     */
   125491     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
   125492       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
   125493       const char **pzRet = va_arg(ap, const char**);
   125494       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
   125495       break;
   125496     }
   125497 #endif
   125498 
   125499     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
   125500     **
   125501     ** Set or clear a flag that indicates that the database file is always well-
   125502     ** formed and never corrupt.  This flag is clear by default, indicating that
   125503     ** database files might have arbitrary corruption.  Setting the flag during
   125504     ** testing causes certain assert() statements in the code to be activated
   125505     ** that demonstrat invariants on well-formed database files.
   125506     */
   125507     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
   125508       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
   125509       break;
   125510     }
   125511 
   125512 
   125513     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
   125514     **
   125515     ** Set the VDBE coverage callback function to xCallback with context
   125516     ** pointer ptr.
   125517     */
   125518     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
   125519 #ifdef SQLITE_VDBE_COVERAGE
   125520       typedef void (*branch_callback)(void*,int,u8,u8);
   125521       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
   125522       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
   125523 #endif
   125524       break;
   125525     }
   125526 
   125527     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
   125528     **
   125529     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
   125530     ** not.
   125531     */
   125532     case SQLITE_TESTCTRL_ISINIT: {
   125533       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
   125534       break;
   125535     }
   125536 
   125537   }
   125538   va_end(ap);
   125539 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   125540   return rc;
   125541 }
   125542 
   125543 /*
   125544 ** This is a utility routine, useful to VFS implementations, that checks
   125545 ** to see if a database file was a URI that contained a specific query
   125546 ** parameter, and if so obtains the value of the query parameter.
   125547 **
   125548 ** The zFilename argument is the filename pointer passed into the xOpen()
   125549 ** method of a VFS implementation.  The zParam argument is the name of the
   125550 ** query parameter we seek.  This routine returns the value of the zParam
   125551 ** parameter if it exists.  If the parameter does not exist, this routine
   125552 ** returns a NULL pointer.
   125553 */
   125554 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
   125555   if( zFilename==0 ) return 0;
   125556   zFilename += sqlite3Strlen30(zFilename) + 1;
   125557   while( zFilename[0] ){
   125558     int x = strcmp(zFilename, zParam);
   125559     zFilename += sqlite3Strlen30(zFilename) + 1;
   125560     if( x==0 ) return zFilename;
   125561     zFilename += sqlite3Strlen30(zFilename) + 1;
   125562   }
   125563   return 0;
   125564 }
   125565 
   125566 /*
   125567 ** Return a boolean value for a query parameter.
   125568 */
   125569 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
   125570   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   125571   bDflt = bDflt!=0;
   125572   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
   125573 }
   125574 
   125575 /*
   125576 ** Return a 64-bit integer value for a query parameter.
   125577 */
   125578 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
   125579   const char *zFilename,    /* Filename as passed to xOpen */
   125580   const char *zParam,       /* URI parameter sought */
   125581   sqlite3_int64 bDflt       /* return if parameter is missing */
   125582 ){
   125583   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   125584   sqlite3_int64 v;
   125585   if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
   125586     bDflt = v;
   125587   }
   125588   return bDflt;
   125589 }
   125590 
   125591 /*
   125592 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
   125593 */
   125594 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
   125595   int i;
   125596   for(i=0; i<db->nDb; i++){
   125597     if( db->aDb[i].pBt
   125598      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
   125599     ){
   125600       return db->aDb[i].pBt;
   125601     }
   125602   }
   125603   return 0;
   125604 }
   125605 
   125606 /*
   125607 ** Return the filename of the database associated with a database
   125608 ** connection.
   125609 */
   125610 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
   125611   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
   125612   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
   125613 }
   125614 
   125615 /*
   125616 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
   125617 ** no such database exists.
   125618 */
   125619 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
   125620   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
   125621   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
   125622 }
   125623 
   125624 /************** End of main.c ************************************************/
   125625 /************** Begin file notify.c ******************************************/
   125626 /*
   125627 ** 2009 March 3
   125628 **
   125629 ** The author disclaims copyright to this source code.  In place of
   125630 ** a legal notice, here is a blessing:
   125631 **
   125632 **    May you do good and not evil.
   125633 **    May you find forgiveness for yourself and forgive others.
   125634 **    May you share freely, never taking more than you give.
   125635 **
   125636 *************************************************************************
   125637 **
   125638 ** This file contains the implementation of the sqlite3_unlock_notify()
   125639 ** API method and its associated functionality.
   125640 */
   125641 
   125642 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
   125643 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   125644 
   125645 /*
   125646 ** Public interfaces:
   125647 **
   125648 **   sqlite3ConnectionBlocked()
   125649 **   sqlite3ConnectionUnlocked()
   125650 **   sqlite3ConnectionClosed()
   125651 **   sqlite3_unlock_notify()
   125652 */
   125653 
   125654 #define assertMutexHeld() \
   125655   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
   125656 
   125657 /*
   125658 ** Head of a linked list of all sqlite3 objects created by this process
   125659 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
   125660 ** is not NULL. This variable may only accessed while the STATIC_MASTER
   125661 ** mutex is held.
   125662 */
   125663 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
   125664 
   125665 #ifndef NDEBUG
   125666 /*
   125667 ** This function is a complex assert() that verifies the following
   125668 ** properties of the blocked connections list:
   125669 **
   125670 **   1) Each entry in the list has a non-NULL value for either
   125671 **      pUnlockConnection or pBlockingConnection, or both.
   125672 **
   125673 **   2) All entries in the list that share a common value for
   125674 **      xUnlockNotify are grouped together.
   125675 **
   125676 **   3) If the argument db is not NULL, then none of the entries in the
   125677 **      blocked connections list have pUnlockConnection or pBlockingConnection
   125678 **      set to db. This is used when closing connection db.
   125679 */
   125680 static void checkListProperties(sqlite3 *db){
   125681   sqlite3 *p;
   125682   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
   125683     int seen = 0;
   125684     sqlite3 *p2;
   125685 
   125686     /* Verify property (1) */
   125687     assert( p->pUnlockConnection || p->pBlockingConnection );
   125688 
   125689     /* Verify property (2) */
   125690     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
   125691       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
   125692       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
   125693       assert( db==0 || p->pUnlockConnection!=db );
   125694       assert( db==0 || p->pBlockingConnection!=db );
   125695     }
   125696   }
   125697 }
   125698 #else
   125699 # define checkListProperties(x)
   125700 #endif
   125701 
   125702 /*
   125703 ** Remove connection db from the blocked connections list. If connection
   125704 ** db is not currently a part of the list, this function is a no-op.
   125705 */
   125706 static void removeFromBlockedList(sqlite3 *db){
   125707   sqlite3 **pp;
   125708   assertMutexHeld();
   125709   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
   125710     if( *pp==db ){
   125711       *pp = (*pp)->pNextBlocked;
   125712       break;
   125713     }
   125714   }
   125715 }
   125716 
   125717 /*
   125718 ** Add connection db to the blocked connections list. It is assumed
   125719 ** that it is not already a part of the list.
   125720 */
   125721 static void addToBlockedList(sqlite3 *db){
   125722   sqlite3 **pp;
   125723   assertMutexHeld();
   125724   for(
   125725     pp=&sqlite3BlockedList;
   125726     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
   125727     pp=&(*pp)->pNextBlocked
   125728   );
   125729   db->pNextBlocked = *pp;
   125730   *pp = db;
   125731 }
   125732 
   125733 /*
   125734 ** Obtain the STATIC_MASTER mutex.
   125735 */
   125736 static void enterMutex(void){
   125737   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   125738   checkListProperties(0);
   125739 }
   125740 
   125741 /*
   125742 ** Release the STATIC_MASTER mutex.
   125743 */
   125744 static void leaveMutex(void){
   125745   assertMutexHeld();
   125746   checkListProperties(0);
   125747   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   125748 }
   125749 
   125750 /*
   125751 ** Register an unlock-notify callback.
   125752 **
   125753 ** This is called after connection "db" has attempted some operation
   125754 ** but has received an SQLITE_LOCKED error because another connection
   125755 ** (call it pOther) in the same process was busy using the same shared
   125756 ** cache.  pOther is found by looking at db->pBlockingConnection.
   125757 **
   125758 ** If there is no blocking connection, the callback is invoked immediately,
   125759 ** before this routine returns.
   125760 **
   125761 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
   125762 ** a deadlock.
   125763 **
   125764 ** Otherwise, make arrangements to invoke xNotify when pOther drops
   125765 ** its locks.
   125766 **
   125767 ** Each call to this routine overrides any prior callbacks registered
   125768 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
   125769 ** cancelled.
   125770 */
   125771 SQLITE_API int sqlite3_unlock_notify(
   125772   sqlite3 *db,
   125773   void (*xNotify)(void **, int),
   125774   void *pArg
   125775 ){
   125776   int rc = SQLITE_OK;
   125777 
   125778   sqlite3_mutex_enter(db->mutex);
   125779   enterMutex();
   125780 
   125781   if( xNotify==0 ){
   125782     removeFromBlockedList(db);
   125783     db->pBlockingConnection = 0;
   125784     db->pUnlockConnection = 0;
   125785     db->xUnlockNotify = 0;
   125786     db->pUnlockArg = 0;
   125787   }else if( 0==db->pBlockingConnection ){
   125788     /* The blocking transaction has been concluded. Or there never was a
   125789     ** blocking transaction. In either case, invoke the notify callback
   125790     ** immediately.
   125791     */
   125792     xNotify(&pArg, 1);
   125793   }else{
   125794     sqlite3 *p;
   125795 
   125796     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
   125797     if( p ){
   125798       rc = SQLITE_LOCKED;              /* Deadlock detected. */
   125799     }else{
   125800       db->pUnlockConnection = db->pBlockingConnection;
   125801       db->xUnlockNotify = xNotify;
   125802       db->pUnlockArg = pArg;
   125803       removeFromBlockedList(db);
   125804       addToBlockedList(db);
   125805     }
   125806   }
   125807 
   125808   leaveMutex();
   125809   assert( !db->mallocFailed );
   125810   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
   125811   sqlite3_mutex_leave(db->mutex);
   125812   return rc;
   125813 }
   125814 
   125815 /*
   125816 ** This function is called while stepping or preparing a statement
   125817 ** associated with connection db. The operation will return SQLITE_LOCKED
   125818 ** to the user because it requires a lock that will not be available
   125819 ** until connection pBlocker concludes its current transaction.
   125820 */
   125821 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
   125822   enterMutex();
   125823   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
   125824     addToBlockedList(db);
   125825   }
   125826   db->pBlockingConnection = pBlocker;
   125827   leaveMutex();
   125828 }
   125829 
   125830 /*
   125831 ** This function is called when
   125832 ** the transaction opened by database db has just finished. Locks held
   125833 ** by database connection db have been released.
   125834 **
   125835 ** This function loops through each entry in the blocked connections
   125836 ** list and does the following:
   125837 **
   125838 **   1) If the sqlite3.pBlockingConnection member of a list entry is
   125839 **      set to db, then set pBlockingConnection=0.
   125840 **
   125841 **   2) If the sqlite3.pUnlockConnection member of a list entry is
   125842 **      set to db, then invoke the configured unlock-notify callback and
   125843 **      set pUnlockConnection=0.
   125844 **
   125845 **   3) If the two steps above mean that pBlockingConnection==0 and
   125846 **      pUnlockConnection==0, remove the entry from the blocked connections
   125847 **      list.
   125848 */
   125849 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
   125850   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
   125851   int nArg = 0;                            /* Number of entries in aArg[] */
   125852   sqlite3 **pp;                            /* Iterator variable */
   125853   void **aArg;               /* Arguments to the unlock callback */
   125854   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
   125855   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
   125856 
   125857   aArg = aStatic;
   125858   enterMutex();         /* Enter STATIC_MASTER mutex */
   125859 
   125860   /* This loop runs once for each entry in the blocked-connections list. */
   125861   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
   125862     sqlite3 *p = *pp;
   125863 
   125864     /* Step 1. */
   125865     if( p->pBlockingConnection==db ){
   125866       p->pBlockingConnection = 0;
   125867     }
   125868 
   125869     /* Step 2. */
   125870     if( p->pUnlockConnection==db ){
   125871       assert( p->xUnlockNotify );
   125872       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
   125873         xUnlockNotify(aArg, nArg);
   125874         nArg = 0;
   125875       }
   125876 
   125877       sqlite3BeginBenignMalloc();
   125878       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
   125879       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
   125880       if( (!aDyn && nArg==(int)ArraySize(aStatic))
   125881        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
   125882       ){
   125883         /* The aArg[] array needs to grow. */
   125884         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
   125885         if( pNew ){
   125886           memcpy(pNew, aArg, nArg*sizeof(void *));
   125887           sqlite3_free(aDyn);
   125888           aDyn = aArg = pNew;
   125889         }else{
   125890           /* This occurs when the array of context pointers that need to
   125891           ** be passed to the unlock-notify callback is larger than the
   125892           ** aStatic[] array allocated on the stack and the attempt to
   125893           ** allocate a larger array from the heap has failed.
   125894           **
   125895           ** This is a difficult situation to handle. Returning an error
   125896           ** code to the caller is insufficient, as even if an error code
   125897           ** is returned the transaction on connection db will still be
   125898           ** closed and the unlock-notify callbacks on blocked connections
   125899           ** will go unissued. This might cause the application to wait
   125900           ** indefinitely for an unlock-notify callback that will never
   125901           ** arrive.
   125902           **
   125903           ** Instead, invoke the unlock-notify callback with the context
   125904           ** array already accumulated. We can then clear the array and
   125905           ** begin accumulating any further context pointers without
   125906           ** requiring any dynamic allocation. This is sub-optimal because
   125907           ** it means that instead of one callback with a large array of
   125908           ** context pointers the application will receive two or more
   125909           ** callbacks with smaller arrays of context pointers, which will
   125910           ** reduce the applications ability to prioritize multiple
   125911           ** connections. But it is the best that can be done under the
   125912           ** circumstances.
   125913           */
   125914           xUnlockNotify(aArg, nArg);
   125915           nArg = 0;
   125916         }
   125917       }
   125918       sqlite3EndBenignMalloc();
   125919 
   125920       aArg[nArg++] = p->pUnlockArg;
   125921       xUnlockNotify = p->xUnlockNotify;
   125922       p->pUnlockConnection = 0;
   125923       p->xUnlockNotify = 0;
   125924       p->pUnlockArg = 0;
   125925     }
   125926 
   125927     /* Step 3. */
   125928     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
   125929       /* Remove connection p from the blocked connections list. */
   125930       *pp = p->pNextBlocked;
   125931       p->pNextBlocked = 0;
   125932     }else{
   125933       pp = &p->pNextBlocked;
   125934     }
   125935   }
   125936 
   125937   if( nArg!=0 ){
   125938     xUnlockNotify(aArg, nArg);
   125939   }
   125940   sqlite3_free(aDyn);
   125941   leaveMutex();         /* Leave STATIC_MASTER mutex */
   125942 }
   125943 
   125944 /*
   125945 ** This is called when the database connection passed as an argument is
   125946 ** being closed. The connection is removed from the blocked list.
   125947 */
   125948 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
   125949   sqlite3ConnectionUnlocked(db);
   125950   enterMutex();
   125951   removeFromBlockedList(db);
   125952   checkListProperties(db);
   125953   leaveMutex();
   125954 }
   125955 #endif
   125956 
   125957 /************** End of notify.c **********************************************/
   125958 /************** Begin file fts3.c ********************************************/
   125959 /*
   125960 ** 2006 Oct 10
   125961 **
   125962 ** The author disclaims copyright to this source code.  In place of
   125963 ** a legal notice, here is a blessing:
   125964 **
   125965 **    May you do good and not evil.
   125966 **    May you find forgiveness for yourself and forgive others.
   125967 **    May you share freely, never taking more than you give.
   125968 **
   125969 ******************************************************************************
   125970 **
   125971 ** This is an SQLite module implementing full-text search.
   125972 */
   125973 
   125974 /*
   125975 ** The code in this file is only compiled if:
   125976 **
   125977 **     * The FTS3 module is being built as an extension
   125978 **       (in which case SQLITE_CORE is not defined), or
   125979 **
   125980 **     * The FTS3 module is being built into the core of
   125981 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   125982 */
   125983 
   125984 /* The full-text index is stored in a series of b+tree (-like)
   125985 ** structures called segments which map terms to doclists.  The
   125986 ** structures are like b+trees in layout, but are constructed from the
   125987 ** bottom up in optimal fashion and are not updatable.  Since trees
   125988 ** are built from the bottom up, things will be described from the
   125989 ** bottom up.
   125990 **
   125991 **
   125992 **** Varints ****
   125993 ** The basic unit of encoding is a variable-length integer called a
   125994 ** varint.  We encode variable-length integers in little-endian order
   125995 ** using seven bits * per byte as follows:
   125996 **
   125997 ** KEY:
   125998 **         A = 0xxxxxxx    7 bits of data and one flag bit
   125999 **         B = 1xxxxxxx    7 bits of data and one flag bit
   126000 **
   126001 **  7 bits - A
   126002 ** 14 bits - BA
   126003 ** 21 bits - BBA
   126004 ** and so on.
   126005 **
   126006 ** This is similar in concept to how sqlite encodes "varints" but
   126007 ** the encoding is not the same.  SQLite varints are big-endian
   126008 ** are are limited to 9 bytes in length whereas FTS3 varints are
   126009 ** little-endian and can be up to 10 bytes in length (in theory).
   126010 **
   126011 ** Example encodings:
   126012 **
   126013 **     1:    0x01
   126014 **   127:    0x7f
   126015 **   128:    0x81 0x00
   126016 **
   126017 **
   126018 **** Document lists ****
   126019 ** A doclist (document list) holds a docid-sorted list of hits for a
   126020 ** given term.  Doclists hold docids and associated token positions.
   126021 ** A docid is the unique integer identifier for a single document.
   126022 ** A position is the index of a word within the document.  The first
   126023 ** word of the document has a position of 0.
   126024 **
   126025 ** FTS3 used to optionally store character offsets using a compile-time
   126026 ** option.  But that functionality is no longer supported.
   126027 **
   126028 ** A doclist is stored like this:
   126029 **
   126030 ** array {
   126031 **   varint docid;          (delta from previous doclist)
   126032 **   array {                (position list for column 0)
   126033 **     varint position;     (2 more than the delta from previous position)
   126034 **   }
   126035 **   array {
   126036 **     varint POS_COLUMN;   (marks start of position list for new column)
   126037 **     varint column;       (index of new column)
   126038 **     array {
   126039 **       varint position;   (2 more than the delta from previous position)
   126040 **     }
   126041 **   }
   126042 **   varint POS_END;        (marks end of positions for this document.
   126043 ** }
   126044 **
   126045 ** Here, array { X } means zero or more occurrences of X, adjacent in
   126046 ** memory.  A "position" is an index of a token in the token stream
   126047 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
   126048 ** in the same logical place as the position element, and act as sentinals
   126049 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
   126050 ** The positions numbers are not stored literally but rather as two more
   126051 ** than the difference from the prior position, or the just the position plus
   126052 ** 2 for the first position.  Example:
   126053 **
   126054 **   label:       A B C D E  F  G H   I  J K
   126055 **   value:     123 5 9 1 1 14 35 0 234 72 0
   126056 **
   126057 ** The 123 value is the first docid.  For column zero in this document
   126058 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
   126059 ** at D signals the start of a new column; the 1 at E indicates that the
   126060 ** new column is column number 1.  There are two positions at 12 and 45
   126061 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
   126062 ** 234 at I is the delta to next docid (357).  It has one position 70
   126063 ** (72-2) and then terminates with the 0 at K.
   126064 **
   126065 ** A "position-list" is the list of positions for multiple columns for
   126066 ** a single docid.  A "column-list" is the set of positions for a single
   126067 ** column.  Hence, a position-list consists of one or more column-lists,
   126068 ** a document record consists of a docid followed by a position-list and
   126069 ** a doclist consists of one or more document records.
   126070 **
   126071 ** A bare doclist omits the position information, becoming an
   126072 ** array of varint-encoded docids.
   126073 **
   126074 **** Segment leaf nodes ****
   126075 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
   126076 ** nodes are written using LeafWriter, and read using LeafReader (to
   126077 ** iterate through a single leaf node's data) and LeavesReader (to
   126078 ** iterate through a segment's entire leaf layer).  Leaf nodes have
   126079 ** the format:
   126080 **
   126081 ** varint iHeight;             (height from leaf level, always 0)
   126082 ** varint nTerm;               (length of first term)
   126083 ** char pTerm[nTerm];          (content of first term)
   126084 ** varint nDoclist;            (length of term's associated doclist)
   126085 ** char pDoclist[nDoclist];    (content of doclist)
   126086 ** array {
   126087 **                             (further terms are delta-encoded)
   126088 **   varint nPrefix;           (length of prefix shared with previous term)
   126089 **   varint nSuffix;           (length of unshared suffix)
   126090 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
   126091 **   varint nDoclist;          (length of term's associated doclist)
   126092 **   char pDoclist[nDoclist];  (content of doclist)
   126093 ** }
   126094 **
   126095 ** Here, array { X } means zero or more occurrences of X, adjacent in
   126096 ** memory.
   126097 **
   126098 ** Leaf nodes are broken into blocks which are stored contiguously in
   126099 ** the %_segments table in sorted order.  This means that when the end
   126100 ** of a node is reached, the next term is in the node with the next
   126101 ** greater node id.
   126102 **
   126103 ** New data is spilled to a new leaf node when the current node
   126104 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
   126105 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
   126106 ** node (a leaf node with a single term and doclist).  The goal of
   126107 ** these settings is to pack together groups of small doclists while
   126108 ** making it efficient to directly access large doclists.  The
   126109 ** assumption is that large doclists represent terms which are more
   126110 ** likely to be query targets.
   126111 **
   126112 ** TODO(shess) It may be useful for blocking decisions to be more
   126113 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
   126114 ** node rather than splitting into 2k and .5k nodes.  My intuition is
   126115 ** that this might extend through 2x or 4x the pagesize.
   126116 **
   126117 **
   126118 **** Segment interior nodes ****
   126119 ** Segment interior nodes store blockids for subtree nodes and terms
   126120 ** to describe what data is stored by the each subtree.  Interior
   126121 ** nodes are written using InteriorWriter, and read using
   126122 ** InteriorReader.  InteriorWriters are created as needed when
   126123 ** SegmentWriter creates new leaf nodes, or when an interior node
   126124 ** itself grows too big and must be split.  The format of interior
   126125 ** nodes:
   126126 **
   126127 ** varint iHeight;           (height from leaf level, always >0)
   126128 ** varint iBlockid;          (block id of node's leftmost subtree)
   126129 ** optional {
   126130 **   varint nTerm;           (length of first term)
   126131 **   char pTerm[nTerm];      (content of first term)
   126132 **   array {
   126133 **                                (further terms are delta-encoded)
   126134 **     varint nPrefix;            (length of shared prefix with previous term)
   126135 **     varint nSuffix;            (length of unshared suffix)
   126136 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
   126137 **   }
   126138 ** }
   126139 **
   126140 ** Here, optional { X } means an optional element, while array { X }
   126141 ** means zero or more occurrences of X, adjacent in memory.
   126142 **
   126143 ** An interior node encodes n terms separating n+1 subtrees.  The
   126144 ** subtree blocks are contiguous, so only the first subtree's blockid
   126145 ** is encoded.  The subtree at iBlockid will contain all terms less
   126146 ** than the first term encoded (or all terms if no term is encoded).
   126147 ** Otherwise, for terms greater than or equal to pTerm[i] but less
   126148 ** than pTerm[i+1], the subtree for that term will be rooted at
   126149 ** iBlockid+i.  Interior nodes only store enough term data to
   126150 ** distinguish adjacent children (if the rightmost term of the left
   126151 ** child is "something", and the leftmost term of the right child is
   126152 ** "wicked", only "w" is stored).
   126153 **
   126154 ** New data is spilled to a new interior node at the same height when
   126155 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
   126156 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
   126157 ** interior nodes and making the tree too skinny.  The interior nodes
   126158 ** at a given height are naturally tracked by interior nodes at
   126159 ** height+1, and so on.
   126160 **
   126161 **
   126162 **** Segment directory ****
   126163 ** The segment directory in table %_segdir stores meta-information for
   126164 ** merging and deleting segments, and also the root node of the
   126165 ** segment's tree.
   126166 **
   126167 ** The root node is the top node of the segment's tree after encoding
   126168 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
   126169 ** This could be either a leaf node or an interior node.  If the top
   126170 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
   126171 ** and a new root interior node is generated (which should always fit
   126172 ** within ROOT_MAX because it only needs space for 2 varints, the
   126173 ** height and the blockid of the previous root).
   126174 **
   126175 ** The meta-information in the segment directory is:
   126176 **   level               - segment level (see below)
   126177 **   idx                 - index within level
   126178 **                       - (level,idx uniquely identify a segment)
   126179 **   start_block         - first leaf node
   126180 **   leaves_end_block    - last leaf node
   126181 **   end_block           - last block (including interior nodes)
   126182 **   root                - contents of root node
   126183 **
   126184 ** If the root node is a leaf node, then start_block,
   126185 ** leaves_end_block, and end_block are all 0.
   126186 **
   126187 **
   126188 **** Segment merging ****
   126189 ** To amortize update costs, segments are grouped into levels and
   126190 ** merged in batches.  Each increase in level represents exponentially
   126191 ** more documents.
   126192 **
   126193 ** New documents (actually, document updates) are tokenized and
   126194 ** written individually (using LeafWriter) to a level 0 segment, with
   126195 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
   126196 ** level 0 segments are merged into a single level 1 segment.  Level 1
   126197 ** is populated like level 0, and eventually MERGE_COUNT level 1
   126198 ** segments are merged to a single level 2 segment (representing
   126199 ** MERGE_COUNT^2 updates), and so on.
   126200 **
   126201 ** A segment merge traverses all segments at a given level in
   126202 ** parallel, performing a straightforward sorted merge.  Since segment
   126203 ** leaf nodes are written in to the %_segments table in order, this
   126204 ** merge traverses the underlying sqlite disk structures efficiently.
   126205 ** After the merge, all segment blocks from the merged level are
   126206 ** deleted.
   126207 **
   126208 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
   126209 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
   126210 ** very similar performance numbers to 16 on insertion, though they're
   126211 ** a tiny bit slower (perhaps due to more overhead in merge-time
   126212 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
   126213 ** 16, 2 about 66% slower than 16.
   126214 **
   126215 ** At query time, high MERGE_COUNT increases the number of segments
   126216 ** which need to be scanned and merged.  For instance, with 100k docs
   126217 ** inserted:
   126218 **
   126219 **    MERGE_COUNT   segments
   126220 **       16           25
   126221 **        8           12
   126222 **        4           10
   126223 **        2            6
   126224 **
   126225 ** This appears to have only a moderate impact on queries for very
   126226 ** frequent terms (which are somewhat dominated by segment merge
   126227 ** costs), and infrequent and non-existent terms still seem to be fast
   126228 ** even with many segments.
   126229 **
   126230 ** TODO(shess) That said, it would be nice to have a better query-side
   126231 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
   126232 ** optimizations to things like doclist merging will swing the sweet
   126233 ** spot around.
   126234 **
   126235 **
   126236 **
   126237 **** Handling of deletions and updates ****
   126238 ** Since we're using a segmented structure, with no docid-oriented
   126239 ** index into the term index, we clearly cannot simply update the term
   126240 ** index when a document is deleted or updated.  For deletions, we
   126241 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
   126242 ** we simply write the new doclist.  Segment merges overwrite older
   126243 ** data for a particular docid with newer data, so deletes or updates
   126244 ** will eventually overtake the earlier data and knock it out.  The
   126245 ** query logic likewise merges doclists so that newer data knocks out
   126246 ** older data.
   126247 */
   126248 
   126249 /************** Include fts3Int.h in the middle of fts3.c ********************/
   126250 /************** Begin file fts3Int.h *****************************************/
   126251 /*
   126252 ** 2009 Nov 12
   126253 **
   126254 ** The author disclaims copyright to this source code.  In place of
   126255 ** a legal notice, here is a blessing:
   126256 **
   126257 **    May you do good and not evil.
   126258 **    May you find forgiveness for yourself and forgive others.
   126259 **    May you share freely, never taking more than you give.
   126260 **
   126261 ******************************************************************************
   126262 **
   126263 */
   126264 #ifndef _FTSINT_H
   126265 #define _FTSINT_H
   126266 
   126267 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   126268 # define NDEBUG 1
   126269 #endif
   126270 
   126271 /*
   126272 ** FTS4 is really an extension for FTS3.  It is enabled using the
   126273 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
   126274 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
   126275 */
   126276 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   126277 # define SQLITE_ENABLE_FTS3
   126278 #endif
   126279 
   126280 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   126281 
   126282 /* If not building as part of the core, include sqlite3ext.h. */
   126283 #ifndef SQLITE_CORE
   126284 SQLITE_EXTENSION_INIT3
   126285 #endif
   126286 
   126287 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
   126288 /************** Begin file fts3_tokenizer.h **********************************/
   126289 /*
   126290 ** 2006 July 10
   126291 **
   126292 ** The author disclaims copyright to this source code.
   126293 **
   126294 *************************************************************************
   126295 ** Defines the interface to tokenizers used by fulltext-search.  There
   126296 ** are three basic components:
   126297 **
   126298 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
   126299 ** interface functions.  This is essentially the class structure for
   126300 ** tokenizers.
   126301 **
   126302 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
   126303 ** including customization information defined at creation time.
   126304 **
   126305 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
   126306 ** tokens from a particular input.
   126307 */
   126308 #ifndef _FTS3_TOKENIZER_H_
   126309 #define _FTS3_TOKENIZER_H_
   126310 
   126311 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
   126312 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
   126313 ** we will need a way to register the API consistently.
   126314 */
   126315 
   126316 /*
   126317 ** Structures used by the tokenizer interface. When a new tokenizer
   126318 ** implementation is registered, the caller provides a pointer to
   126319 ** an sqlite3_tokenizer_module containing pointers to the callback
   126320 ** functions that make up an implementation.
   126321 **
   126322 ** When an fts3 table is created, it passes any arguments passed to
   126323 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
   126324 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
   126325 ** implementation. The xCreate() function in turn returns an
   126326 ** sqlite3_tokenizer structure representing the specific tokenizer to
   126327 ** be used for the fts3 table (customized by the tokenizer clause arguments).
   126328 **
   126329 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
   126330 ** method is called. It returns an sqlite3_tokenizer_cursor object
   126331 ** that may be used to tokenize a specific input buffer based on
   126332 ** the tokenization rules supplied by a specific sqlite3_tokenizer
   126333 ** object.
   126334 */
   126335 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
   126336 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
   126337 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
   126338 
   126339 struct sqlite3_tokenizer_module {
   126340 
   126341   /*
   126342   ** Structure version. Should always be set to 0 or 1.
   126343   */
   126344   int iVersion;
   126345 
   126346   /*
   126347   ** Create a new tokenizer. The values in the argv[] array are the
   126348   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
   126349   ** TABLE statement that created the fts3 table. For example, if
   126350   ** the following SQL is executed:
   126351   **
   126352   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
   126353   **
   126354   ** then argc is set to 2, and the argv[] array contains pointers
   126355   ** to the strings "arg1" and "arg2".
   126356   **
   126357   ** This method should return either SQLITE_OK (0), or an SQLite error
   126358   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
   126359   ** to point at the newly created tokenizer structure. The generic
   126360   ** sqlite3_tokenizer.pModule variable should not be initialized by
   126361   ** this callback. The caller will do so.
   126362   */
   126363   int (*xCreate)(
   126364     int argc,                           /* Size of argv array */
   126365     const char *const*argv,             /* Tokenizer argument strings */
   126366     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
   126367   );
   126368 
   126369   /*
   126370   ** Destroy an existing tokenizer. The fts3 module calls this method
   126371   ** exactly once for each successful call to xCreate().
   126372   */
   126373   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
   126374 
   126375   /*
   126376   ** Create a tokenizer cursor to tokenize an input buffer. The caller
   126377   ** is responsible for ensuring that the input buffer remains valid
   126378   ** until the cursor is closed (using the xClose() method).
   126379   */
   126380   int (*xOpen)(
   126381     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
   126382     const char *pInput, int nBytes,      /* Input buffer */
   126383     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
   126384   );
   126385 
   126386   /*
   126387   ** Destroy an existing tokenizer cursor. The fts3 module calls this
   126388   ** method exactly once for each successful call to xOpen().
   126389   */
   126390   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
   126391 
   126392   /*
   126393   ** Retrieve the next token from the tokenizer cursor pCursor. This
   126394   ** method should either return SQLITE_OK and set the values of the
   126395   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
   126396   ** the end of the buffer has been reached, or an SQLite error code.
   126397   **
   126398   ** *ppToken should be set to point at a buffer containing the
   126399   ** normalized version of the token (i.e. after any case-folding and/or
   126400   ** stemming has been performed). *pnBytes should be set to the length
   126401   ** of this buffer in bytes. The input text that generated the token is
   126402   ** identified by the byte offsets returned in *piStartOffset and
   126403   ** *piEndOffset. *piStartOffset should be set to the index of the first
   126404   ** byte of the token in the input buffer. *piEndOffset should be set
   126405   ** to the index of the first byte just past the end of the token in
   126406   ** the input buffer.
   126407   **
   126408   ** The buffer *ppToken is set to point at is managed by the tokenizer
   126409   ** implementation. It is only required to be valid until the next call
   126410   ** to xNext() or xClose().
   126411   */
   126412   /* TODO(shess) current implementation requires pInput to be
   126413   ** nul-terminated.  This should either be fixed, or pInput/nBytes
   126414   ** should be converted to zInput.
   126415   */
   126416   int (*xNext)(
   126417     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
   126418     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
   126419     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
   126420     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
   126421     int *piPosition      /* OUT: Number of tokens returned before this one */
   126422   );
   126423 
   126424   /***********************************************************************
   126425   ** Methods below this point are only available if iVersion>=1.
   126426   */
   126427 
   126428   /*
   126429   ** Configure the language id of a tokenizer cursor.
   126430   */
   126431   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
   126432 };
   126433 
   126434 struct sqlite3_tokenizer {
   126435   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
   126436   /* Tokenizer implementations will typically add additional fields */
   126437 };
   126438 
   126439 struct sqlite3_tokenizer_cursor {
   126440   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
   126441   /* Tokenizer implementations will typically add additional fields */
   126442 };
   126443 
   126444 int fts3_global_term_cnt(int iTerm, int iCol);
   126445 int fts3_term_cnt(int iTerm, int iCol);
   126446 
   126447 
   126448 #endif /* _FTS3_TOKENIZER_H_ */
   126449 
   126450 /************** End of fts3_tokenizer.h **************************************/
   126451 /************** Continuing where we left off in fts3Int.h ********************/
   126452 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
   126453 /************** Begin file fts3_hash.h ***************************************/
   126454 /*
   126455 ** 2001 September 22
   126456 **
   126457 ** The author disclaims copyright to this source code.  In place of
   126458 ** a legal notice, here is a blessing:
   126459 **
   126460 **    May you do good and not evil.
   126461 **    May you find forgiveness for yourself and forgive others.
   126462 **    May you share freely, never taking more than you give.
   126463 **
   126464 *************************************************************************
   126465 ** This is the header file for the generic hash-table implementation
   126466 ** used in SQLite.  We've modified it slightly to serve as a standalone
   126467 ** hash table implementation for the full-text indexing module.
   126468 **
   126469 */
   126470 #ifndef _FTS3_HASH_H_
   126471 #define _FTS3_HASH_H_
   126472 
   126473 /* Forward declarations of structures. */
   126474 typedef struct Fts3Hash Fts3Hash;
   126475 typedef struct Fts3HashElem Fts3HashElem;
   126476 
   126477 /* A complete hash table is an instance of the following structure.
   126478 ** The internals of this structure are intended to be opaque -- client
   126479 ** code should not attempt to access or modify the fields of this structure
   126480 ** directly.  Change this structure only by using the routines below.
   126481 ** However, many of the "procedures" and "functions" for modifying and
   126482 ** accessing this structure are really macros, so we can't really make
   126483 ** this structure opaque.
   126484 */
   126485 struct Fts3Hash {
   126486   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
   126487   char copyKey;           /* True if copy of key made on insert */
   126488   int count;              /* Number of entries in this table */
   126489   Fts3HashElem *first;    /* The first element of the array */
   126490   int htsize;             /* Number of buckets in the hash table */
   126491   struct _fts3ht {        /* the hash table */
   126492     int count;               /* Number of entries with this hash */
   126493     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
   126494   } *ht;
   126495 };
   126496 
   126497 /* Each element in the hash table is an instance of the following
   126498 ** structure.  All elements are stored on a single doubly-linked list.
   126499 **
   126500 ** Again, this structure is intended to be opaque, but it can't really
   126501 ** be opaque because it is used by macros.
   126502 */
   126503 struct Fts3HashElem {
   126504   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
   126505   void *data;                /* Data associated with this element */
   126506   void *pKey; int nKey;      /* Key associated with this element */
   126507 };
   126508 
   126509 /*
   126510 ** There are 2 different modes of operation for a hash table:
   126511 **
   126512 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
   126513 **                           (including the null-terminator, if any).  Case
   126514 **                           is respected in comparisons.
   126515 **
   126516 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
   126517 **                           memcmp() is used to compare keys.
   126518 **
   126519 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
   126520 */
   126521 #define FTS3_HASH_STRING    1
   126522 #define FTS3_HASH_BINARY    2
   126523 
   126524 /*
   126525 ** Access routines.  To delete, insert a NULL pointer.
   126526 */
   126527 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
   126528 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
   126529 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
   126530 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
   126531 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
   126532 
   126533 /*
   126534 ** Shorthand for the functions above
   126535 */
   126536 #define fts3HashInit     sqlite3Fts3HashInit
   126537 #define fts3HashInsert   sqlite3Fts3HashInsert
   126538 #define fts3HashFind     sqlite3Fts3HashFind
   126539 #define fts3HashClear    sqlite3Fts3HashClear
   126540 #define fts3HashFindElem sqlite3Fts3HashFindElem
   126541 
   126542 /*
   126543 ** Macros for looping over all elements of a hash table.  The idiom is
   126544 ** like this:
   126545 **
   126546 **   Fts3Hash h;
   126547 **   Fts3HashElem *p;
   126548 **   ...
   126549 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
   126550 **     SomeStructure *pData = fts3HashData(p);
   126551 **     // do something with pData
   126552 **   }
   126553 */
   126554 #define fts3HashFirst(H)  ((H)->first)
   126555 #define fts3HashNext(E)   ((E)->next)
   126556 #define fts3HashData(E)   ((E)->data)
   126557 #define fts3HashKey(E)    ((E)->pKey)
   126558 #define fts3HashKeysize(E) ((E)->nKey)
   126559 
   126560 /*
   126561 ** Number of entries in a hash table
   126562 */
   126563 #define fts3HashCount(H)  ((H)->count)
   126564 
   126565 #endif /* _FTS3_HASH_H_ */
   126566 
   126567 /************** End of fts3_hash.h *******************************************/
   126568 /************** Continuing where we left off in fts3Int.h ********************/
   126569 
   126570 /*
   126571 ** This constant determines the maximum depth of an FTS expression tree
   126572 ** that the library will create and use. FTS uses recursion to perform
   126573 ** various operations on the query tree, so the disadvantage of a large
   126574 ** limit is that it may allow very large queries to use large amounts
   126575 ** of stack space (perhaps causing a stack overflow).
   126576 */
   126577 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
   126578 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
   126579 #endif
   126580 
   126581 
   126582 /*
   126583 ** This constant controls how often segments are merged. Once there are
   126584 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
   126585 ** segment of level N+1.
   126586 */
   126587 #define FTS3_MERGE_COUNT 16
   126588 
   126589 /*
   126590 ** This is the maximum amount of data (in bytes) to store in the
   126591 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
   126592 ** populated as documents are inserted/updated/deleted in a transaction
   126593 ** and used to create a new segment when the transaction is committed.
   126594 ** However if this limit is reached midway through a transaction, a new
   126595 ** segment is created and the hash table cleared immediately.
   126596 */
   126597 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
   126598 
   126599 /*
   126600 ** Macro to return the number of elements in an array. SQLite has a
   126601 ** similar macro called ArraySize(). Use a different name to avoid
   126602 ** a collision when building an amalgamation with built-in FTS3.
   126603 */
   126604 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
   126605 
   126606 
   126607 #ifndef MIN
   126608 # define MIN(x,y) ((x)<(y)?(x):(y))
   126609 #endif
   126610 #ifndef MAX
   126611 # define MAX(x,y) ((x)>(y)?(x):(y))
   126612 #endif
   126613 
   126614 /*
   126615 ** Maximum length of a varint encoded integer. The varint format is different
   126616 ** from that used by SQLite, so the maximum length is 10, not 9.
   126617 */
   126618 #define FTS3_VARINT_MAX 10
   126619 
   126620 /*
   126621 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
   126622 ** in the document set and zero or more prefix indexes. All indexes are stored
   126623 ** as one or more b+-trees in the %_segments and %_segdir tables.
   126624 **
   126625 ** It is possible to determine which index a b+-tree belongs to based on the
   126626 ** value stored in the "%_segdir.level" column. Given this value L, the index
   126627 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
   126628 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
   126629 ** between 1024 and 2047 to index 1, and so on.
   126630 **
   126631 ** It is considered impossible for an index to use more than 1024 levels. In
   126632 ** theory though this may happen, but only after at least
   126633 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
   126634 */
   126635 #define FTS3_SEGDIR_MAXLEVEL      1024
   126636 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
   126637 
   126638 /*
   126639 ** The testcase() macro is only used by the amalgamation.  If undefined,
   126640 ** make it a no-op.
   126641 */
   126642 #ifndef testcase
   126643 # define testcase(X)
   126644 #endif
   126645 
   126646 /*
   126647 ** Terminator values for position-lists and column-lists.
   126648 */
   126649 #define POS_COLUMN  (1)     /* Column-list terminator */
   126650 #define POS_END     (0)     /* Position-list terminator */
   126651 
   126652 /*
   126653 ** This section provides definitions to allow the
   126654 ** FTS3 extension to be compiled outside of the
   126655 ** amalgamation.
   126656 */
   126657 #ifndef SQLITE_AMALGAMATION
   126658 /*
   126659 ** Macros indicating that conditional expressions are always true or
   126660 ** false.
   126661 */
   126662 #ifdef SQLITE_COVERAGE_TEST
   126663 # define ALWAYS(x) (1)
   126664 # define NEVER(X)  (0)
   126665 #else
   126666 # define ALWAYS(x) (x)
   126667 # define NEVER(x)  (x)
   126668 #endif
   126669 
   126670 /*
   126671 ** Internal types used by SQLite.
   126672 */
   126673 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
   126674 typedef short int i16;            /* 2-byte (or larger) signed integer */
   126675 typedef unsigned int u32;         /* 4-byte unsigned integer */
   126676 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
   126677 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
   126678 
   126679 /*
   126680 ** Macro used to suppress compiler warnings for unused parameters.
   126681 */
   126682 #define UNUSED_PARAMETER(x) (void)(x)
   126683 
   126684 /*
   126685 ** Activate assert() only if SQLITE_TEST is enabled.
   126686 */
   126687 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   126688 # define NDEBUG 1
   126689 #endif
   126690 
   126691 /*
   126692 ** The TESTONLY macro is used to enclose variable declarations or
   126693 ** other bits of code that are needed to support the arguments
   126694 ** within testcase() and assert() macros.
   126695 */
   126696 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   126697 # define TESTONLY(X)  X
   126698 #else
   126699 # define TESTONLY(X)
   126700 #endif
   126701 
   126702 #endif /* SQLITE_AMALGAMATION */
   126703 
   126704 #ifdef SQLITE_DEBUG
   126705 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
   126706 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
   126707 #else
   126708 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
   126709 #endif
   126710 
   126711 typedef struct Fts3Table Fts3Table;
   126712 typedef struct Fts3Cursor Fts3Cursor;
   126713 typedef struct Fts3Expr Fts3Expr;
   126714 typedef struct Fts3Phrase Fts3Phrase;
   126715 typedef struct Fts3PhraseToken Fts3PhraseToken;
   126716 
   126717 typedef struct Fts3Doclist Fts3Doclist;
   126718 typedef struct Fts3SegFilter Fts3SegFilter;
   126719 typedef struct Fts3DeferredToken Fts3DeferredToken;
   126720 typedef struct Fts3SegReader Fts3SegReader;
   126721 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
   126722 
   126723 /*
   126724 ** A connection to a fulltext index is an instance of the following
   126725 ** structure. The xCreate and xConnect methods create an instance
   126726 ** of this structure and xDestroy and xDisconnect free that instance.
   126727 ** All other methods receive a pointer to the structure as one of their
   126728 ** arguments.
   126729 */
   126730 struct Fts3Table {
   126731   sqlite3_vtab base;              /* Base class used by SQLite core */
   126732   sqlite3 *db;                    /* The database connection */
   126733   const char *zDb;                /* logical database name */
   126734   const char *zName;              /* virtual table name */
   126735   int nColumn;                    /* number of named columns in virtual table */
   126736   char **azColumn;                /* column names.  malloced */
   126737   u8 *abNotindexed;               /* True for 'notindexed' columns */
   126738   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
   126739   char *zContentTbl;              /* content=xxx option, or NULL */
   126740   char *zLanguageid;              /* languageid=xxx option, or NULL */
   126741   int nAutoincrmerge;             /* Value configured by 'automerge' */
   126742   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
   126743 
   126744   /* Precompiled statements used by the implementation. Each of these
   126745   ** statements is run and reset within a single virtual table API call.
   126746   */
   126747   sqlite3_stmt *aStmt[40];
   126748 
   126749   char *zReadExprlist;
   126750   char *zWriteExprlist;
   126751 
   126752   int nNodeSize;                  /* Soft limit for node size */
   126753   u8 bFts4;                       /* True for FTS4, false for FTS3 */
   126754   u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
   126755   u8 bHasDocsize;                 /* True if %_docsize table exists */
   126756   u8 bDescIdx;                    /* True if doclists are in reverse order */
   126757   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
   126758   int nPgsz;                      /* Page size for host database */
   126759   char *zSegmentsTbl;             /* Name of %_segments table */
   126760   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
   126761 
   126762   /*
   126763   ** The following array of hash tables is used to buffer pending index
   126764   ** updates during transactions. All pending updates buffered at any one
   126765   ** time must share a common language-id (see the FTS4 langid= feature).
   126766   ** The current language id is stored in variable iPrevLangid.
   126767   **
   126768   ** A single FTS4 table may have multiple full-text indexes. For each index
   126769   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
   126770   ** terms that appear in the document set. Each subsequent index in aIndex[]
   126771   ** is an index of prefixes of a specific length.
   126772   **
   126773   ** Variable nPendingData contains an estimate the memory consumed by the
   126774   ** pending data structures, including hash table overhead, but not including
   126775   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
   126776   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
   126777   ** recently inserted record.
   126778   */
   126779   int nIndex;                     /* Size of aIndex[] */
   126780   struct Fts3Index {
   126781     int nPrefix;                  /* Prefix length (0 for main terms index) */
   126782     Fts3Hash hPending;            /* Pending terms table for this index */
   126783   } *aIndex;
   126784   int nMaxPendingData;            /* Max pending data before flush to disk */
   126785   int nPendingData;               /* Current bytes of pending data */
   126786   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
   126787   int iPrevLangid;                /* Langid of recently inserted document */
   126788 
   126789 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   126790   /* State variables used for validating that the transaction control
   126791   ** methods of the virtual table are called at appropriate times.  These
   126792   ** values do not contribute to FTS functionality; they are used for
   126793   ** verifying the operation of the SQLite core.
   126794   */
   126795   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
   126796   int mxSavepoint;       /* Largest valid xSavepoint integer */
   126797 #endif
   126798 
   126799 #ifdef SQLITE_TEST
   126800   /* True to disable the incremental doclist optimization. This is controled
   126801   ** by special insert command 'test-no-incr-doclist'.  */
   126802   int bNoIncrDoclist;
   126803 #endif
   126804 };
   126805 
   126806 /*
   126807 ** When the core wants to read from the virtual table, it creates a
   126808 ** virtual table cursor (an instance of the following structure) using
   126809 ** the xOpen method. Cursors are destroyed using the xClose method.
   126810 */
   126811 struct Fts3Cursor {
   126812   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   126813   i16 eSearch;                    /* Search strategy (see below) */
   126814   u8 isEof;                       /* True if at End Of Results */
   126815   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
   126816   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
   126817   Fts3Expr *pExpr;                /* Parsed MATCH query string */
   126818   int iLangid;                    /* Language being queried for */
   126819   int nPhrase;                    /* Number of matchable phrases in query */
   126820   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
   126821   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
   126822   char *pNextId;                  /* Pointer into the body of aDoclist */
   126823   char *aDoclist;                 /* List of docids for full-text queries */
   126824   int nDoclist;                   /* Size of buffer at aDoclist */
   126825   u8 bDesc;                       /* True to sort in descending order */
   126826   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
   126827   int nRowAvg;                    /* Average size of database rows, in pages */
   126828   sqlite3_int64 nDoc;             /* Documents in table */
   126829   i64 iMinDocid;                  /* Minimum docid to return */
   126830   i64 iMaxDocid;                  /* Maximum docid to return */
   126831   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
   126832   u32 *aMatchinfo;                /* Information about most recent match */
   126833   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
   126834   char *zMatchinfo;               /* Matchinfo specification */
   126835 };
   126836 
   126837 #define FTS3_EVAL_FILTER    0
   126838 #define FTS3_EVAL_NEXT      1
   126839 #define FTS3_EVAL_MATCHINFO 2
   126840 
   126841 /*
   126842 ** The Fts3Cursor.eSearch member is always set to one of the following.
   126843 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
   126844 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
   126845 ** of the column to be searched.  For example, in
   126846 **
   126847 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
   126848 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
   126849 **
   126850 ** Because the LHS of the MATCH operator is 2nd column "b",
   126851 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
   126852 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
   126853 ** indicating that all columns should be searched,
   126854 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
   126855 */
   126856 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
   126857 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
   126858 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
   126859 
   126860 /*
   126861 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
   126862 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
   126863 ** above. The upper 16-bits contain a combination of the following
   126864 ** bits, used to describe extra constraints on full-text searches.
   126865 */
   126866 #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
   126867 #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
   126868 #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
   126869 
   126870 struct Fts3Doclist {
   126871   char *aAll;                    /* Array containing doclist (or NULL) */
   126872   int nAll;                      /* Size of a[] in bytes */
   126873   char *pNextDocid;              /* Pointer to next docid */
   126874 
   126875   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
   126876   int bFreeList;                 /* True if pList should be sqlite3_free()d */
   126877   char *pList;                   /* Pointer to position list following iDocid */
   126878   int nList;                     /* Length of position list */
   126879 };
   126880 
   126881 /*
   126882 ** A "phrase" is a sequence of one or more tokens that must match in
   126883 ** sequence.  A single token is the base case and the most common case.
   126884 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
   126885 ** nToken will be the number of tokens in the string.
   126886 */
   126887 struct Fts3PhraseToken {
   126888   char *z;                        /* Text of the token */
   126889   int n;                          /* Number of bytes in buffer z */
   126890   int isPrefix;                   /* True if token ends with a "*" character */
   126891   int bFirst;                     /* True if token must appear at position 0 */
   126892 
   126893   /* Variables above this point are populated when the expression is
   126894   ** parsed (by code in fts3_expr.c). Below this point the variables are
   126895   ** used when evaluating the expression. */
   126896   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
   126897   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
   126898 };
   126899 
   126900 struct Fts3Phrase {
   126901   /* Cache of doclist for this phrase. */
   126902   Fts3Doclist doclist;
   126903   int bIncr;                 /* True if doclist is loaded incrementally */
   126904   int iDoclistToken;
   126905 
   126906   /* Variables below this point are populated by fts3_expr.c when parsing
   126907   ** a MATCH expression. Everything above is part of the evaluation phase.
   126908   */
   126909   int nToken;                /* Number of tokens in the phrase */
   126910   int iColumn;               /* Index of column this phrase must match */
   126911   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
   126912 };
   126913 
   126914 /*
   126915 ** A tree of these objects forms the RHS of a MATCH operator.
   126916 **
   126917 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
   126918 ** points to a malloced buffer, size nDoclist bytes, containing the results
   126919 ** of this phrase query in FTS3 doclist format. As usual, the initial
   126920 ** "Length" field found in doclists stored on disk is omitted from this
   126921 ** buffer.
   126922 **
   126923 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
   126924 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
   126925 ** where nCol is the number of columns in the queried FTS table. The array
   126926 ** is populated as follows:
   126927 **
   126928 **   aMI[iCol*3 + 0] = Undefined
   126929 **   aMI[iCol*3 + 1] = Number of occurrences
   126930 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
   126931 **
   126932 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
   126933 ** when the expression node is.
   126934 */
   126935 struct Fts3Expr {
   126936   int eType;                 /* One of the FTSQUERY_XXX values defined below */
   126937   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
   126938   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
   126939   Fts3Expr *pLeft;           /* Left operand */
   126940   Fts3Expr *pRight;          /* Right operand */
   126941   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
   126942 
   126943   /* The following are used by the fts3_eval.c module. */
   126944   sqlite3_int64 iDocid;      /* Current docid */
   126945   u8 bEof;                   /* True this expression is at EOF already */
   126946   u8 bStart;                 /* True if iDocid is valid */
   126947   u8 bDeferred;              /* True if this expression is entirely deferred */
   126948 
   126949   u32 *aMI;
   126950 };
   126951 
   126952 /*
   126953 ** Candidate values for Fts3Query.eType. Note that the order of the first
   126954 ** four values is in order of precedence when parsing expressions. For
   126955 ** example, the following:
   126956 **
   126957 **   "a OR b AND c NOT d NEAR e"
   126958 **
   126959 ** is equivalent to:
   126960 **
   126961 **   "a OR (b AND (c NOT (d NEAR e)))"
   126962 */
   126963 #define FTSQUERY_NEAR   1
   126964 #define FTSQUERY_NOT    2
   126965 #define FTSQUERY_AND    3
   126966 #define FTSQUERY_OR     4
   126967 #define FTSQUERY_PHRASE 5
   126968 
   126969 
   126970 /* fts3_write.c */
   126971 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
   126972 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
   126973 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
   126974 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
   126975 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
   126976   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
   126977 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   126978   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
   126979 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
   126980 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
   126981 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
   126982 
   126983 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
   126984 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
   126985 
   126986 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   126987 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
   126988 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
   126989 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
   126990 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
   126991 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
   126992 #else
   126993 # define sqlite3Fts3FreeDeferredTokens(x)
   126994 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
   126995 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
   126996 # define sqlite3Fts3FreeDeferredDoclists(x)
   126997 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
   126998 #endif
   126999 
   127000 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
   127001 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
   127002 
   127003 /* Special values interpreted by sqlite3SegReaderCursor() */
   127004 #define FTS3_SEGCURSOR_PENDING        -1
   127005 #define FTS3_SEGCURSOR_ALL            -2
   127006 
   127007 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
   127008 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
   127009 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
   127010 
   127011 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
   127012     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
   127013 
   127014 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
   127015 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
   127016 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
   127017 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
   127018 #define FTS3_SEGMENT_PREFIX        0x00000008
   127019 #define FTS3_SEGMENT_SCAN          0x00000010
   127020 #define FTS3_SEGMENT_FIRST         0x00000020
   127021 
   127022 /* Type passed as 4th argument to SegmentReaderIterate() */
   127023 struct Fts3SegFilter {
   127024   const char *zTerm;
   127025   int nTerm;
   127026   int iCol;
   127027   int flags;
   127028 };
   127029 
   127030 struct Fts3MultiSegReader {
   127031   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
   127032   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
   127033   int nSegment;                   /* Size of apSegment array */
   127034   int nAdvance;                   /* How many seg-readers to advance */
   127035   Fts3SegFilter *pFilter;         /* Pointer to filter object */
   127036   char *aBuffer;                  /* Buffer to merge doclists in */
   127037   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
   127038 
   127039   int iColFilter;                 /* If >=0, filter for this column */
   127040   int bRestart;
   127041 
   127042   /* Used by fts3.c only. */
   127043   int nCost;                      /* Cost of running iterator */
   127044   int bLookup;                    /* True if a lookup of a single entry. */
   127045 
   127046   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
   127047   char *zTerm;                    /* Pointer to term buffer */
   127048   int nTerm;                      /* Size of zTerm in bytes */
   127049   char *aDoclist;                 /* Pointer to doclist buffer */
   127050   int nDoclist;                   /* Size of aDoclist[] in bytes */
   127051 };
   127052 
   127053 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
   127054 
   127055 #define fts3GetVarint32(p, piVal) (                                           \
   127056   (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
   127057 )
   127058 
   127059 /* fts3.c */
   127060 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
   127061 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
   127062 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
   127063 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
   127064 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
   127065 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
   127066 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
   127067 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
   127068 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
   127069 
   127070 /* fts3_tokenizer.c */
   127071 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
   127072 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
   127073 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
   127074     sqlite3_tokenizer **, char **
   127075 );
   127076 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
   127077 
   127078 /* fts3_snippet.c */
   127079 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
   127080 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
   127081   const char *, const char *, int, int
   127082 );
   127083 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
   127084 
   127085 /* fts3_expr.c */
   127086 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
   127087   char **, int, int, int, const char *, int, Fts3Expr **, char **
   127088 );
   127089 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
   127090 #ifdef SQLITE_TEST
   127091 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
   127092 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
   127093 #endif
   127094 
   127095 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
   127096   sqlite3_tokenizer_cursor **
   127097 );
   127098 
   127099 /* fts3_aux.c */
   127100 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
   127101 
   127102 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
   127103 
   127104 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   127105     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
   127106 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   127107     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
   127108 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
   127109 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
   127110 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
   127111 
   127112 /* fts3_tokenize_vtab.c */
   127113 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
   127114 
   127115 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
   127116 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   127117 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
   127118 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
   127119 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
   127120 #endif
   127121 
   127122 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
   127123 #endif /* _FTSINT_H */
   127124 
   127125 /************** End of fts3Int.h *********************************************/
   127126 /************** Continuing where we left off in fts3.c ***********************/
   127127 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   127128 
   127129 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
   127130 # define SQLITE_CORE 1
   127131 #endif
   127132 
   127133 /* #include <assert.h> */
   127134 /* #include <stdlib.h> */
   127135 /* #include <stddef.h> */
   127136 /* #include <stdio.h> */
   127137 /* #include <string.h> */
   127138 /* #include <stdarg.h> */
   127139 
   127140 #ifndef SQLITE_CORE
   127141   SQLITE_EXTENSION_INIT1
   127142 #endif
   127143 
   127144 static int fts3EvalNext(Fts3Cursor *pCsr);
   127145 static int fts3EvalStart(Fts3Cursor *pCsr);
   127146 static int fts3TermSegReaderCursor(
   127147     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
   127148 
   127149 /*
   127150 ** Write a 64-bit variable-length integer to memory starting at p[0].
   127151 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
   127152 ** The number of bytes written is returned.
   127153 */
   127154 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
   127155   unsigned char *q = (unsigned char *) p;
   127156   sqlite_uint64 vu = v;
   127157   do{
   127158     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
   127159     vu >>= 7;
   127160   }while( vu!=0 );
   127161   q[-1] &= 0x7f;  /* turn off high bit in final byte */
   127162   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
   127163   return (int) (q - (unsigned char *)p);
   127164 }
   127165 
   127166 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
   127167   v = (v & mask1) | ( (*ptr++) << shift );                    \
   127168   if( (v & mask2)==0 ){ var = v; return ret; }
   127169 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
   127170   v = (*ptr++);                                               \
   127171   if( (v & mask2)==0 ){ var = v; return ret; }
   127172 
   127173 /*
   127174 ** Read a 64-bit variable-length integer from memory starting at p[0].
   127175 ** Return the number of bytes read, or 0 on error.
   127176 ** The value is stored in *v.
   127177 */
   127178 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
   127179   const char *pStart = p;
   127180   u32 a;
   127181   u64 b;
   127182   int shift;
   127183 
   127184   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
   127185   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
   127186   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
   127187   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
   127188   b = (a & 0x0FFFFFFF );
   127189 
   127190   for(shift=28; shift<=63; shift+=7){
   127191     u64 c = *p++;
   127192     b += (c&0x7F) << shift;
   127193     if( (c & 0x80)==0 ) break;
   127194   }
   127195   *v = b;
   127196   return (int)(p - pStart);
   127197 }
   127198 
   127199 /*
   127200 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
   127201 ** 32-bit integer before it is returned.
   127202 */
   127203 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
   127204   u32 a;
   127205 
   127206 #ifndef fts3GetVarint32
   127207   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
   127208 #else
   127209   a = (*p++);
   127210   assert( a & 0x80 );
   127211 #endif
   127212 
   127213   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
   127214   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
   127215   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
   127216   a = (a & 0x0FFFFFFF );
   127217   *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
   127218   return 5;
   127219 }
   127220 
   127221 /*
   127222 ** Return the number of bytes required to encode v as a varint
   127223 */
   127224 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
   127225   int i = 0;
   127226   do{
   127227     i++;
   127228     v >>= 7;
   127229   }while( v!=0 );
   127230   return i;
   127231 }
   127232 
   127233 /*
   127234 ** Convert an SQL-style quoted string into a normal string by removing
   127235 ** the quote characters.  The conversion is done in-place.  If the
   127236 ** input does not begin with a quote character, then this routine
   127237 ** is a no-op.
   127238 **
   127239 ** Examples:
   127240 **
   127241 **     "abc"   becomes   abc
   127242 **     'xyz'   becomes   xyz
   127243 **     [pqr]   becomes   pqr
   127244 **     `mno`   becomes   mno
   127245 **
   127246 */
   127247 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
   127248   char quote;                     /* Quote character (if any ) */
   127249 
   127250   quote = z[0];
   127251   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
   127252     int iIn = 1;                  /* Index of next byte to read from input */
   127253     int iOut = 0;                 /* Index of next byte to write to output */
   127254 
   127255     /* If the first byte was a '[', then the close-quote character is a ']' */
   127256     if( quote=='[' ) quote = ']';
   127257 
   127258     while( ALWAYS(z[iIn]) ){
   127259       if( z[iIn]==quote ){
   127260         if( z[iIn+1]!=quote ) break;
   127261         z[iOut++] = quote;
   127262         iIn += 2;
   127263       }else{
   127264         z[iOut++] = z[iIn++];
   127265       }
   127266     }
   127267     z[iOut] = '\0';
   127268   }
   127269 }
   127270 
   127271 /*
   127272 ** Read a single varint from the doclist at *pp and advance *pp to point
   127273 ** to the first byte past the end of the varint.  Add the value of the varint
   127274 ** to *pVal.
   127275 */
   127276 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
   127277   sqlite3_int64 iVal;
   127278   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   127279   *pVal += iVal;
   127280 }
   127281 
   127282 /*
   127283 ** When this function is called, *pp points to the first byte following a
   127284 ** varint that is part of a doclist (or position-list, or any other list
   127285 ** of varints). This function moves *pp to point to the start of that varint,
   127286 ** and sets *pVal by the varint value.
   127287 **
   127288 ** Argument pStart points to the first byte of the doclist that the
   127289 ** varint is part of.
   127290 */
   127291 static void fts3GetReverseVarint(
   127292   char **pp,
   127293   char *pStart,
   127294   sqlite3_int64 *pVal
   127295 ){
   127296   sqlite3_int64 iVal;
   127297   char *p;
   127298 
   127299   /* Pointer p now points at the first byte past the varint we are
   127300   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
   127301   ** clear on character p[-1]. */
   127302   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
   127303   p++;
   127304   *pp = p;
   127305 
   127306   sqlite3Fts3GetVarint(p, &iVal);
   127307   *pVal = iVal;
   127308 }
   127309 
   127310 /*
   127311 ** The xDisconnect() virtual table method.
   127312 */
   127313 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
   127314   Fts3Table *p = (Fts3Table *)pVtab;
   127315   int i;
   127316 
   127317   assert( p->nPendingData==0 );
   127318   assert( p->pSegments==0 );
   127319 
   127320   /* Free any prepared statements held */
   127321   for(i=0; i<SizeofArray(p->aStmt); i++){
   127322     sqlite3_finalize(p->aStmt[i]);
   127323   }
   127324   sqlite3_free(p->zSegmentsTbl);
   127325   sqlite3_free(p->zReadExprlist);
   127326   sqlite3_free(p->zWriteExprlist);
   127327   sqlite3_free(p->zContentTbl);
   127328   sqlite3_free(p->zLanguageid);
   127329 
   127330   /* Invoke the tokenizer destructor to free the tokenizer. */
   127331   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
   127332 
   127333   sqlite3_free(p);
   127334   return SQLITE_OK;
   127335 }
   127336 
   127337 /*
   127338 ** Construct one or more SQL statements from the format string given
   127339 ** and then evaluate those statements. The success code is written
   127340 ** into *pRc.
   127341 **
   127342 ** If *pRc is initially non-zero then this routine is a no-op.
   127343 */
   127344 static void fts3DbExec(
   127345   int *pRc,              /* Success code */
   127346   sqlite3 *db,           /* Database in which to run SQL */
   127347   const char *zFormat,   /* Format string for SQL */
   127348   ...                    /* Arguments to the format string */
   127349 ){
   127350   va_list ap;
   127351   char *zSql;
   127352   if( *pRc ) return;
   127353   va_start(ap, zFormat);
   127354   zSql = sqlite3_vmprintf(zFormat, ap);
   127355   va_end(ap);
   127356   if( zSql==0 ){
   127357     *pRc = SQLITE_NOMEM;
   127358   }else{
   127359     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
   127360     sqlite3_free(zSql);
   127361   }
   127362 }
   127363 
   127364 /*
   127365 ** The xDestroy() virtual table method.
   127366 */
   127367 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
   127368   Fts3Table *p = (Fts3Table *)pVtab;
   127369   int rc = SQLITE_OK;              /* Return code */
   127370   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
   127371   sqlite3 *db = p->db;             /* Database handle */
   127372 
   127373   /* Drop the shadow tables */
   127374   if( p->zContentTbl==0 ){
   127375     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
   127376   }
   127377   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
   127378   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
   127379   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
   127380   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
   127381 
   127382   /* If everything has worked, invoke fts3DisconnectMethod() to free the
   127383   ** memory associated with the Fts3Table structure and return SQLITE_OK.
   127384   ** Otherwise, return an SQLite error code.
   127385   */
   127386   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
   127387 }
   127388 
   127389 
   127390 /*
   127391 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
   127392 ** passed as the first argument. This is done as part of the xConnect()
   127393 ** and xCreate() methods.
   127394 **
   127395 ** If *pRc is non-zero when this function is called, it is a no-op.
   127396 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   127397 ** before returning.
   127398 */
   127399 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
   127400   if( *pRc==SQLITE_OK ){
   127401     int i;                        /* Iterator variable */
   127402     int rc;                       /* Return code */
   127403     char *zSql;                   /* SQL statement passed to declare_vtab() */
   127404     char *zCols;                  /* List of user defined columns */
   127405     const char *zLanguageid;
   127406 
   127407     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
   127408     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   127409 
   127410     /* Create a list of user columns for the virtual table */
   127411     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
   127412     for(i=1; zCols && i<p->nColumn; i++){
   127413       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
   127414     }
   127415 
   127416     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
   127417     zSql = sqlite3_mprintf(
   127418         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
   127419         zCols, p->zName, zLanguageid
   127420     );
   127421     if( !zCols || !zSql ){
   127422       rc = SQLITE_NOMEM;
   127423     }else{
   127424       rc = sqlite3_declare_vtab(p->db, zSql);
   127425     }
   127426 
   127427     sqlite3_free(zSql);
   127428     sqlite3_free(zCols);
   127429     *pRc = rc;
   127430   }
   127431 }
   127432 
   127433 /*
   127434 ** Create the %_stat table if it does not already exist.
   127435 */
   127436 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
   127437   fts3DbExec(pRc, p->db,
   127438       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
   127439           "(id INTEGER PRIMARY KEY, value BLOB);",
   127440       p->zDb, p->zName
   127441   );
   127442   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
   127443 }
   127444 
   127445 /*
   127446 ** Create the backing store tables (%_content, %_segments and %_segdir)
   127447 ** required by the FTS3 table passed as the only argument. This is done
   127448 ** as part of the vtab xCreate() method.
   127449 **
   127450 ** If the p->bHasDocsize boolean is true (indicating that this is an
   127451 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
   127452 ** %_stat tables required by FTS4.
   127453 */
   127454 static int fts3CreateTables(Fts3Table *p){
   127455   int rc = SQLITE_OK;             /* Return code */
   127456   int i;                          /* Iterator variable */
   127457   sqlite3 *db = p->db;            /* The database connection */
   127458 
   127459   if( p->zContentTbl==0 ){
   127460     const char *zLanguageid = p->zLanguageid;
   127461     char *zContentCols;           /* Columns of %_content table */
   127462 
   127463     /* Create a list of user columns for the content table */
   127464     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
   127465     for(i=0; zContentCols && i<p->nColumn; i++){
   127466       char *z = p->azColumn[i];
   127467       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
   127468     }
   127469     if( zLanguageid && zContentCols ){
   127470       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
   127471     }
   127472     if( zContentCols==0 ) rc = SQLITE_NOMEM;
   127473 
   127474     /* Create the content table */
   127475     fts3DbExec(&rc, db,
   127476        "CREATE TABLE %Q.'%q_content'(%s)",
   127477        p->zDb, p->zName, zContentCols
   127478     );
   127479     sqlite3_free(zContentCols);
   127480   }
   127481 
   127482   /* Create other tables */
   127483   fts3DbExec(&rc, db,
   127484       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
   127485       p->zDb, p->zName
   127486   );
   127487   fts3DbExec(&rc, db,
   127488       "CREATE TABLE %Q.'%q_segdir'("
   127489         "level INTEGER,"
   127490         "idx INTEGER,"
   127491         "start_block INTEGER,"
   127492         "leaves_end_block INTEGER,"
   127493         "end_block INTEGER,"
   127494         "root BLOB,"
   127495         "PRIMARY KEY(level, idx)"
   127496       ");",
   127497       p->zDb, p->zName
   127498   );
   127499   if( p->bHasDocsize ){
   127500     fts3DbExec(&rc, db,
   127501         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
   127502         p->zDb, p->zName
   127503     );
   127504   }
   127505   assert( p->bHasStat==p->bFts4 );
   127506   if( p->bHasStat ){
   127507     sqlite3Fts3CreateStatTable(&rc, p);
   127508   }
   127509   return rc;
   127510 }
   127511 
   127512 /*
   127513 ** Store the current database page-size in bytes in p->nPgsz.
   127514 **
   127515 ** If *pRc is non-zero when this function is called, it is a no-op.
   127516 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   127517 ** before returning.
   127518 */
   127519 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
   127520   if( *pRc==SQLITE_OK ){
   127521     int rc;                       /* Return code */
   127522     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
   127523     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
   127524 
   127525     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
   127526     if( !zSql ){
   127527       rc = SQLITE_NOMEM;
   127528     }else{
   127529       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
   127530       if( rc==SQLITE_OK ){
   127531         sqlite3_step(pStmt);
   127532         p->nPgsz = sqlite3_column_int(pStmt, 0);
   127533         rc = sqlite3_finalize(pStmt);
   127534       }else if( rc==SQLITE_AUTH ){
   127535         p->nPgsz = 1024;
   127536         rc = SQLITE_OK;
   127537       }
   127538     }
   127539     assert( p->nPgsz>0 || rc!=SQLITE_OK );
   127540     sqlite3_free(zSql);
   127541     *pRc = rc;
   127542   }
   127543 }
   127544 
   127545 /*
   127546 ** "Special" FTS4 arguments are column specifications of the following form:
   127547 **
   127548 **   <key> = <value>
   127549 **
   127550 ** There may not be whitespace surrounding the "=" character. The <value>
   127551 ** term may be quoted, but the <key> may not.
   127552 */
   127553 static int fts3IsSpecialColumn(
   127554   const char *z,
   127555   int *pnKey,
   127556   char **pzValue
   127557 ){
   127558   char *zValue;
   127559   const char *zCsr = z;
   127560 
   127561   while( *zCsr!='=' ){
   127562     if( *zCsr=='\0' ) return 0;
   127563     zCsr++;
   127564   }
   127565 
   127566   *pnKey = (int)(zCsr-z);
   127567   zValue = sqlite3_mprintf("%s", &zCsr[1]);
   127568   if( zValue ){
   127569     sqlite3Fts3Dequote(zValue);
   127570   }
   127571   *pzValue = zValue;
   127572   return 1;
   127573 }
   127574 
   127575 /*
   127576 ** Append the output of a printf() style formatting to an existing string.
   127577 */
   127578 static void fts3Appendf(
   127579   int *pRc,                       /* IN/OUT: Error code */
   127580   char **pz,                      /* IN/OUT: Pointer to string buffer */
   127581   const char *zFormat,            /* Printf format string to append */
   127582   ...                             /* Arguments for printf format string */
   127583 ){
   127584   if( *pRc==SQLITE_OK ){
   127585     va_list ap;
   127586     char *z;
   127587     va_start(ap, zFormat);
   127588     z = sqlite3_vmprintf(zFormat, ap);
   127589     va_end(ap);
   127590     if( z && *pz ){
   127591       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
   127592       sqlite3_free(z);
   127593       z = z2;
   127594     }
   127595     if( z==0 ) *pRc = SQLITE_NOMEM;
   127596     sqlite3_free(*pz);
   127597     *pz = z;
   127598   }
   127599 }
   127600 
   127601 /*
   127602 ** Return a copy of input string zInput enclosed in double-quotes (") and
   127603 ** with all double quote characters escaped. For example:
   127604 **
   127605 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
   127606 **
   127607 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
   127608 ** is the callers responsibility to call sqlite3_free() to release this
   127609 ** memory.
   127610 */
   127611 static char *fts3QuoteId(char const *zInput){
   127612   int nRet;
   127613   char *zRet;
   127614   nRet = 2 + (int)strlen(zInput)*2 + 1;
   127615   zRet = sqlite3_malloc(nRet);
   127616   if( zRet ){
   127617     int i;
   127618     char *z = zRet;
   127619     *(z++) = '"';
   127620     for(i=0; zInput[i]; i++){
   127621       if( zInput[i]=='"' ) *(z++) = '"';
   127622       *(z++) = zInput[i];
   127623     }
   127624     *(z++) = '"';
   127625     *(z++) = '\0';
   127626   }
   127627   return zRet;
   127628 }
   127629 
   127630 /*
   127631 ** Return a list of comma separated SQL expressions and a FROM clause that
   127632 ** could be used in a SELECT statement such as the following:
   127633 **
   127634 **     SELECT <list of expressions> FROM %_content AS x ...
   127635 **
   127636 ** to return the docid, followed by each column of text data in order
   127637 ** from left to write. If parameter zFunc is not NULL, then instead of
   127638 ** being returned directly each column of text data is passed to an SQL
   127639 ** function named zFunc first. For example, if zFunc is "unzip" and the
   127640 ** table has the three user-defined columns "a", "b", and "c", the following
   127641 ** string is returned:
   127642 **
   127643 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
   127644 **
   127645 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   127646 ** is the responsibility of the caller to eventually free it.
   127647 **
   127648 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   127649 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   127650 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   127651 ** no error occurs, *pRc is left unmodified.
   127652 */
   127653 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
   127654   char *zRet = 0;
   127655   char *zFree = 0;
   127656   char *zFunction;
   127657   int i;
   127658 
   127659   if( p->zContentTbl==0 ){
   127660     if( !zFunc ){
   127661       zFunction = "";
   127662     }else{
   127663       zFree = zFunction = fts3QuoteId(zFunc);
   127664     }
   127665     fts3Appendf(pRc, &zRet, "docid");
   127666     for(i=0; i<p->nColumn; i++){
   127667       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
   127668     }
   127669     if( p->zLanguageid ){
   127670       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
   127671     }
   127672     sqlite3_free(zFree);
   127673   }else{
   127674     fts3Appendf(pRc, &zRet, "rowid");
   127675     for(i=0; i<p->nColumn; i++){
   127676       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
   127677     }
   127678     if( p->zLanguageid ){
   127679       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
   127680     }
   127681   }
   127682   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
   127683       p->zDb,
   127684       (p->zContentTbl ? p->zContentTbl : p->zName),
   127685       (p->zContentTbl ? "" : "_content")
   127686   );
   127687   return zRet;
   127688 }
   127689 
   127690 /*
   127691 ** Return a list of N comma separated question marks, where N is the number
   127692 ** of columns in the %_content table (one for the docid plus one for each
   127693 ** user-defined text column).
   127694 **
   127695 ** If argument zFunc is not NULL, then all but the first question mark
   127696 ** is preceded by zFunc and an open bracket, and followed by a closed
   127697 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
   127698 ** user-defined text columns, the following string is returned:
   127699 **
   127700 **     "?, zip(?), zip(?), zip(?)"
   127701 **
   127702 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   127703 ** is the responsibility of the caller to eventually free it.
   127704 **
   127705 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   127706 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   127707 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   127708 ** no error occurs, *pRc is left unmodified.
   127709 */
   127710 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
   127711   char *zRet = 0;
   127712   char *zFree = 0;
   127713   char *zFunction;
   127714   int i;
   127715 
   127716   if( !zFunc ){
   127717     zFunction = "";
   127718   }else{
   127719     zFree = zFunction = fts3QuoteId(zFunc);
   127720   }
   127721   fts3Appendf(pRc, &zRet, "?");
   127722   for(i=0; i<p->nColumn; i++){
   127723     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
   127724   }
   127725   if( p->zLanguageid ){
   127726     fts3Appendf(pRc, &zRet, ", ?");
   127727   }
   127728   sqlite3_free(zFree);
   127729   return zRet;
   127730 }
   127731 
   127732 /*
   127733 ** This function interprets the string at (*pp) as a non-negative integer
   127734 ** value. It reads the integer and sets *pnOut to the value read, then
   127735 ** sets *pp to point to the byte immediately following the last byte of
   127736 ** the integer value.
   127737 **
   127738 ** Only decimal digits ('0'..'9') may be part of an integer value.
   127739 **
   127740 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
   127741 ** the output value undefined. Otherwise SQLITE_OK is returned.
   127742 **
   127743 ** This function is used when parsing the "prefix=" FTS4 parameter.
   127744 */
   127745 static int fts3GobbleInt(const char **pp, int *pnOut){
   127746   const char *p;                  /* Iterator pointer */
   127747   int nInt = 0;                   /* Output value */
   127748 
   127749   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
   127750     nInt = nInt * 10 + (p[0] - '0');
   127751   }
   127752   if( p==*pp ) return SQLITE_ERROR;
   127753   *pnOut = nInt;
   127754   *pp = p;
   127755   return SQLITE_OK;
   127756 }
   127757 
   127758 /*
   127759 ** This function is called to allocate an array of Fts3Index structures
   127760 ** representing the indexes maintained by the current FTS table. FTS tables
   127761 ** always maintain the main "terms" index, but may also maintain one or
   127762 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
   127763 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
   127764 **
   127765 ** Argument zParam is passed the value of the "prefix=" option if one was
   127766 ** specified, or NULL otherwise.
   127767 **
   127768 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
   127769 ** the allocated array. *pnIndex is set to the number of elements in the
   127770 ** array. If an error does occur, an SQLite error code is returned.
   127771 **
   127772 ** Regardless of whether or not an error is returned, it is the responsibility
   127773 ** of the caller to call sqlite3_free() on the output array to free it.
   127774 */
   127775 static int fts3PrefixParameter(
   127776   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
   127777   int *pnIndex,                   /* OUT: size of *apIndex[] array */
   127778   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
   127779 ){
   127780   struct Fts3Index *aIndex;       /* Allocated array */
   127781   int nIndex = 1;                 /* Number of entries in array */
   127782 
   127783   if( zParam && zParam[0] ){
   127784     const char *p;
   127785     nIndex++;
   127786     for(p=zParam; *p; p++){
   127787       if( *p==',' ) nIndex++;
   127788     }
   127789   }
   127790 
   127791   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
   127792   *apIndex = aIndex;
   127793   *pnIndex = nIndex;
   127794   if( !aIndex ){
   127795     return SQLITE_NOMEM;
   127796   }
   127797 
   127798   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
   127799   if( zParam ){
   127800     const char *p = zParam;
   127801     int i;
   127802     for(i=1; i<nIndex; i++){
   127803       int nPrefix;
   127804       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
   127805       aIndex[i].nPrefix = nPrefix;
   127806       p++;
   127807     }
   127808   }
   127809 
   127810   return SQLITE_OK;
   127811 }
   127812 
   127813 /*
   127814 ** This function is called when initializing an FTS4 table that uses the
   127815 ** content=xxx option. It determines the number of and names of the columns
   127816 ** of the new FTS4 table.
   127817 **
   127818 ** The third argument passed to this function is the value passed to the
   127819 ** config=xxx option (i.e. "xxx"). This function queries the database for
   127820 ** a table of that name. If found, the output variables are populated
   127821 ** as follows:
   127822 **
   127823 **   *pnCol:   Set to the number of columns table xxx has,
   127824 **
   127825 **   *pnStr:   Set to the total amount of space required to store a copy
   127826 **             of each columns name, including the nul-terminator.
   127827 **
   127828 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
   127829 **             the name of the corresponding column in table xxx. The array
   127830 **             and its contents are allocated using a single allocation. It
   127831 **             is the responsibility of the caller to free this allocation
   127832 **             by eventually passing the *pazCol value to sqlite3_free().
   127833 **
   127834 ** If the table cannot be found, an error code is returned and the output
   127835 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
   127836 ** returned (and the output variables are undefined).
   127837 */
   127838 static int fts3ContentColumns(
   127839   sqlite3 *db,                    /* Database handle */
   127840   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
   127841   const char *zTbl,               /* Name of content table */
   127842   const char ***pazCol,           /* OUT: Malloc'd array of column names */
   127843   int *pnCol,                     /* OUT: Size of array *pazCol */
   127844   int *pnStr                      /* OUT: Bytes of string content */
   127845 ){
   127846   int rc = SQLITE_OK;             /* Return code */
   127847   char *zSql;                     /* "SELECT *" statement on zTbl */
   127848   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
   127849 
   127850   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
   127851   if( !zSql ){
   127852     rc = SQLITE_NOMEM;
   127853   }else{
   127854     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   127855   }
   127856   sqlite3_free(zSql);
   127857 
   127858   if( rc==SQLITE_OK ){
   127859     const char **azCol;           /* Output array */
   127860     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
   127861     int nCol;                     /* Number of table columns */
   127862     int i;                        /* Used to iterate through columns */
   127863 
   127864     /* Loop through the returned columns. Set nStr to the number of bytes of
   127865     ** space required to store a copy of each column name, including the
   127866     ** nul-terminator byte.  */
   127867     nCol = sqlite3_column_count(pStmt);
   127868     for(i=0; i<nCol; i++){
   127869       const char *zCol = sqlite3_column_name(pStmt, i);
   127870       nStr += (int)strlen(zCol) + 1;
   127871     }
   127872 
   127873     /* Allocate and populate the array to return. */
   127874     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
   127875     if( azCol==0 ){
   127876       rc = SQLITE_NOMEM;
   127877     }else{
   127878       char *p = (char *)&azCol[nCol];
   127879       for(i=0; i<nCol; i++){
   127880         const char *zCol = sqlite3_column_name(pStmt, i);
   127881         int n = (int)strlen(zCol)+1;
   127882         memcpy(p, zCol, n);
   127883         azCol[i] = p;
   127884         p += n;
   127885       }
   127886     }
   127887     sqlite3_finalize(pStmt);
   127888 
   127889     /* Set the output variables. */
   127890     *pnCol = nCol;
   127891     *pnStr = nStr;
   127892     *pazCol = azCol;
   127893   }
   127894 
   127895   return rc;
   127896 }
   127897 
   127898 /*
   127899 ** This function is the implementation of both the xConnect and xCreate
   127900 ** methods of the FTS3 virtual table.
   127901 **
   127902 ** The argv[] array contains the following:
   127903 **
   127904 **   argv[0]   -> module name  ("fts3" or "fts4")
   127905 **   argv[1]   -> database name
   127906 **   argv[2]   -> table name
   127907 **   argv[...] -> "column name" and other module argument fields.
   127908 */
   127909 static int fts3InitVtab(
   127910   int isCreate,                   /* True for xCreate, false for xConnect */
   127911   sqlite3 *db,                    /* The SQLite database connection */
   127912   void *pAux,                     /* Hash table containing tokenizers */
   127913   int argc,                       /* Number of elements in argv array */
   127914   const char * const *argv,       /* xCreate/xConnect argument array */
   127915   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   127916   char **pzErr                    /* Write any error message here */
   127917 ){
   127918   Fts3Hash *pHash = (Fts3Hash *)pAux;
   127919   Fts3Table *p = 0;               /* Pointer to allocated vtab */
   127920   int rc = SQLITE_OK;             /* Return code */
   127921   int i;                          /* Iterator variable */
   127922   int nByte;                      /* Size of allocation used for *p */
   127923   int iCol;                       /* Column index */
   127924   int nString = 0;                /* Bytes required to hold all column names */
   127925   int nCol = 0;                   /* Number of columns in the FTS table */
   127926   char *zCsr;                     /* Space for holding column names */
   127927   int nDb;                        /* Bytes required to hold database name */
   127928   int nName;                      /* Bytes required to hold table name */
   127929   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
   127930   const char **aCol;              /* Array of column names */
   127931   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
   127932 
   127933   int nIndex;                     /* Size of aIndex[] array */
   127934   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
   127935 
   127936   /* The results of parsing supported FTS4 key=value options: */
   127937   int bNoDocsize = 0;             /* True to omit %_docsize table */
   127938   int bDescIdx = 0;               /* True to store descending indexes */
   127939   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
   127940   char *zCompress = 0;            /* compress=? parameter (or NULL) */
   127941   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
   127942   char *zContent = 0;             /* content=? parameter (or NULL) */
   127943   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
   127944   char **azNotindexed = 0;        /* The set of notindexed= columns */
   127945   int nNotindexed = 0;            /* Size of azNotindexed[] array */
   127946 
   127947   assert( strlen(argv[0])==4 );
   127948   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
   127949        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
   127950   );
   127951 
   127952   nDb = (int)strlen(argv[1]) + 1;
   127953   nName = (int)strlen(argv[2]) + 1;
   127954 
   127955   nByte = sizeof(const char *) * (argc-2);
   127956   aCol = (const char **)sqlite3_malloc(nByte);
   127957   if( aCol ){
   127958     memset((void*)aCol, 0, nByte);
   127959     azNotindexed = (char **)sqlite3_malloc(nByte);
   127960   }
   127961   if( azNotindexed ){
   127962     memset(azNotindexed, 0, nByte);
   127963   }
   127964   if( !aCol || !azNotindexed ){
   127965     rc = SQLITE_NOMEM;
   127966     goto fts3_init_out;
   127967   }
   127968 
   127969   /* Loop through all of the arguments passed by the user to the FTS3/4
   127970   ** module (i.e. all the column names and special arguments). This loop
   127971   ** does the following:
   127972   **
   127973   **   + Figures out the number of columns the FTSX table will have, and
   127974   **     the number of bytes of space that must be allocated to store copies
   127975   **     of the column names.
   127976   **
   127977   **   + If there is a tokenizer specification included in the arguments,
   127978   **     initializes the tokenizer pTokenizer.
   127979   */
   127980   for(i=3; rc==SQLITE_OK && i<argc; i++){
   127981     char const *z = argv[i];
   127982     int nKey;
   127983     char *zVal;
   127984 
   127985     /* Check if this is a tokenizer specification */
   127986     if( !pTokenizer
   127987      && strlen(z)>8
   127988      && 0==sqlite3_strnicmp(z, "tokenize", 8)
   127989      && 0==sqlite3Fts3IsIdChar(z[8])
   127990     ){
   127991       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
   127992     }
   127993 
   127994     /* Check if it is an FTS4 special argument. */
   127995     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
   127996       struct Fts4Option {
   127997         const char *zOpt;
   127998         int nOpt;
   127999       } aFts4Opt[] = {
   128000         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
   128001         { "prefix",      6 },     /* 1 -> PREFIX */
   128002         { "compress",    8 },     /* 2 -> COMPRESS */
   128003         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
   128004         { "order",       5 },     /* 4 -> ORDER */
   128005         { "content",     7 },     /* 5 -> CONTENT */
   128006         { "languageid", 10 },     /* 6 -> LANGUAGEID */
   128007         { "notindexed", 10 }      /* 7 -> NOTINDEXED */
   128008       };
   128009 
   128010       int iOpt;
   128011       if( !zVal ){
   128012         rc = SQLITE_NOMEM;
   128013       }else{
   128014         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
   128015           struct Fts4Option *pOp = &aFts4Opt[iOpt];
   128016           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
   128017             break;
   128018           }
   128019         }
   128020         if( iOpt==SizeofArray(aFts4Opt) ){
   128021           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
   128022           rc = SQLITE_ERROR;
   128023         }else{
   128024           switch( iOpt ){
   128025             case 0:               /* MATCHINFO */
   128026               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
   128027                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
   128028                 rc = SQLITE_ERROR;
   128029               }
   128030               bNoDocsize = 1;
   128031               break;
   128032 
   128033             case 1:               /* PREFIX */
   128034               sqlite3_free(zPrefix);
   128035               zPrefix = zVal;
   128036               zVal = 0;
   128037               break;
   128038 
   128039             case 2:               /* COMPRESS */
   128040               sqlite3_free(zCompress);
   128041               zCompress = zVal;
   128042               zVal = 0;
   128043               break;
   128044 
   128045             case 3:               /* UNCOMPRESS */
   128046               sqlite3_free(zUncompress);
   128047               zUncompress = zVal;
   128048               zVal = 0;
   128049               break;
   128050 
   128051             case 4:               /* ORDER */
   128052               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
   128053                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
   128054               ){
   128055                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
   128056                 rc = SQLITE_ERROR;
   128057               }
   128058               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
   128059               break;
   128060 
   128061             case 5:              /* CONTENT */
   128062               sqlite3_free(zContent);
   128063               zContent = zVal;
   128064               zVal = 0;
   128065               break;
   128066 
   128067             case 6:              /* LANGUAGEID */
   128068               assert( iOpt==6 );
   128069               sqlite3_free(zLanguageid);
   128070               zLanguageid = zVal;
   128071               zVal = 0;
   128072               break;
   128073 
   128074             case 7:              /* NOTINDEXED */
   128075               azNotindexed[nNotindexed++] = zVal;
   128076               zVal = 0;
   128077               break;
   128078           }
   128079         }
   128080         sqlite3_free(zVal);
   128081       }
   128082     }
   128083 
   128084     /* Otherwise, the argument is a column name. */
   128085     else {
   128086       nString += (int)(strlen(z) + 1);
   128087       aCol[nCol++] = z;
   128088     }
   128089   }
   128090 
   128091   /* If a content=xxx option was specified, the following:
   128092   **
   128093   **   1. Ignore any compress= and uncompress= options.
   128094   **
   128095   **   2. If no column names were specified as part of the CREATE VIRTUAL
   128096   **      TABLE statement, use all columns from the content table.
   128097   */
   128098   if( rc==SQLITE_OK && zContent ){
   128099     sqlite3_free(zCompress);
   128100     sqlite3_free(zUncompress);
   128101     zCompress = 0;
   128102     zUncompress = 0;
   128103     if( nCol==0 ){
   128104       sqlite3_free((void*)aCol);
   128105       aCol = 0;
   128106       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
   128107 
   128108       /* If a languageid= option was specified, remove the language id
   128109       ** column from the aCol[] array. */
   128110       if( rc==SQLITE_OK && zLanguageid ){
   128111         int j;
   128112         for(j=0; j<nCol; j++){
   128113           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
   128114             int k;
   128115             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
   128116             nCol--;
   128117             break;
   128118           }
   128119         }
   128120       }
   128121     }
   128122   }
   128123   if( rc!=SQLITE_OK ) goto fts3_init_out;
   128124 
   128125   if( nCol==0 ){
   128126     assert( nString==0 );
   128127     aCol[0] = "content";
   128128     nString = 8;
   128129     nCol = 1;
   128130   }
   128131 
   128132   if( pTokenizer==0 ){
   128133     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
   128134     if( rc!=SQLITE_OK ) goto fts3_init_out;
   128135   }
   128136   assert( pTokenizer );
   128137 
   128138   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
   128139   if( rc==SQLITE_ERROR ){
   128140     assert( zPrefix );
   128141     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
   128142   }
   128143   if( rc!=SQLITE_OK ) goto fts3_init_out;
   128144 
   128145   /* Allocate and populate the Fts3Table structure. */
   128146   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
   128147           nCol * sizeof(char *) +              /* azColumn */
   128148           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
   128149           nCol * sizeof(u8) +                  /* abNotindexed */
   128150           nName +                              /* zName */
   128151           nDb +                                /* zDb */
   128152           nString;                             /* Space for azColumn strings */
   128153   p = (Fts3Table*)sqlite3_malloc(nByte);
   128154   if( p==0 ){
   128155     rc = SQLITE_NOMEM;
   128156     goto fts3_init_out;
   128157   }
   128158   memset(p, 0, nByte);
   128159   p->db = db;
   128160   p->nColumn = nCol;
   128161   p->nPendingData = 0;
   128162   p->azColumn = (char **)&p[1];
   128163   p->pTokenizer = pTokenizer;
   128164   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
   128165   p->bHasDocsize = (isFts4 && bNoDocsize==0);
   128166   p->bHasStat = isFts4;
   128167   p->bFts4 = isFts4;
   128168   p->bDescIdx = bDescIdx;
   128169   p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
   128170   p->zContentTbl = zContent;
   128171   p->zLanguageid = zLanguageid;
   128172   zContent = 0;
   128173   zLanguageid = 0;
   128174   TESTONLY( p->inTransaction = -1 );
   128175   TESTONLY( p->mxSavepoint = -1 );
   128176 
   128177   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
   128178   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
   128179   p->nIndex = nIndex;
   128180   for(i=0; i<nIndex; i++){
   128181     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
   128182   }
   128183   p->abNotindexed = (u8 *)&p->aIndex[nIndex];
   128184 
   128185   /* Fill in the zName and zDb fields of the vtab structure. */
   128186   zCsr = (char *)&p->abNotindexed[nCol];
   128187   p->zName = zCsr;
   128188   memcpy(zCsr, argv[2], nName);
   128189   zCsr += nName;
   128190   p->zDb = zCsr;
   128191   memcpy(zCsr, argv[1], nDb);
   128192   zCsr += nDb;
   128193 
   128194   /* Fill in the azColumn array */
   128195   for(iCol=0; iCol<nCol; iCol++){
   128196     char *z;
   128197     int n = 0;
   128198     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
   128199     memcpy(zCsr, z, n);
   128200     zCsr[n] = '\0';
   128201     sqlite3Fts3Dequote(zCsr);
   128202     p->azColumn[iCol] = zCsr;
   128203     zCsr += n+1;
   128204     assert( zCsr <= &((char *)p)[nByte] );
   128205   }
   128206 
   128207   /* Fill in the abNotindexed array */
   128208   for(iCol=0; iCol<nCol; iCol++){
   128209     int n = (int)strlen(p->azColumn[iCol]);
   128210     for(i=0; i<nNotindexed; i++){
   128211       char *zNot = azNotindexed[i];
   128212       if( zNot && n==(int)strlen(zNot)
   128213        && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
   128214       ){
   128215         p->abNotindexed[iCol] = 1;
   128216         sqlite3_free(zNot);
   128217         azNotindexed[i] = 0;
   128218       }
   128219     }
   128220   }
   128221   for(i=0; i<nNotindexed; i++){
   128222     if( azNotindexed[i] ){
   128223       *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
   128224       rc = SQLITE_ERROR;
   128225     }
   128226   }
   128227 
   128228   if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
   128229     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
   128230     rc = SQLITE_ERROR;
   128231     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
   128232   }
   128233   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
   128234   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
   128235   if( rc!=SQLITE_OK ) goto fts3_init_out;
   128236 
   128237   /* If this is an xCreate call, create the underlying tables in the
   128238   ** database. TODO: For xConnect(), it could verify that said tables exist.
   128239   */
   128240   if( isCreate ){
   128241     rc = fts3CreateTables(p);
   128242   }
   128243 
   128244   /* Check to see if a legacy fts3 table has been "upgraded" by the
   128245   ** addition of a %_stat table so that it can use incremental merge.
   128246   */
   128247   if( !isFts4 && !isCreate ){
   128248     p->bHasStat = 2;
   128249   }
   128250 
   128251   /* Figure out the page-size for the database. This is required in order to
   128252   ** estimate the cost of loading large doclists from the database.  */
   128253   fts3DatabasePageSize(&rc, p);
   128254   p->nNodeSize = p->nPgsz-35;
   128255 
   128256   /* Declare the table schema to SQLite. */
   128257   fts3DeclareVtab(&rc, p);
   128258 
   128259 fts3_init_out:
   128260   sqlite3_free(zPrefix);
   128261   sqlite3_free(aIndex);
   128262   sqlite3_free(zCompress);
   128263   sqlite3_free(zUncompress);
   128264   sqlite3_free(zContent);
   128265   sqlite3_free(zLanguageid);
   128266   for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
   128267   sqlite3_free((void *)aCol);
   128268   sqlite3_free((void *)azNotindexed);
   128269   if( rc!=SQLITE_OK ){
   128270     if( p ){
   128271       fts3DisconnectMethod((sqlite3_vtab *)p);
   128272     }else if( pTokenizer ){
   128273       pTokenizer->pModule->xDestroy(pTokenizer);
   128274     }
   128275   }else{
   128276     assert( p->pSegments==0 );
   128277     *ppVTab = &p->base;
   128278   }
   128279   return rc;
   128280 }
   128281 
   128282 /*
   128283 ** The xConnect() and xCreate() methods for the virtual table. All the
   128284 ** work is done in function fts3InitVtab().
   128285 */
   128286 static int fts3ConnectMethod(
   128287   sqlite3 *db,                    /* Database connection */
   128288   void *pAux,                     /* Pointer to tokenizer hash table */
   128289   int argc,                       /* Number of elements in argv array */
   128290   const char * const *argv,       /* xCreate/xConnect argument array */
   128291   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   128292   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   128293 ){
   128294   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
   128295 }
   128296 static int fts3CreateMethod(
   128297   sqlite3 *db,                    /* Database connection */
   128298   void *pAux,                     /* Pointer to tokenizer hash table */
   128299   int argc,                       /* Number of elements in argv array */
   128300   const char * const *argv,       /* xCreate/xConnect argument array */
   128301   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   128302   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   128303 ){
   128304   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
   128305 }
   128306 
   128307 /*
   128308 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
   128309 ** extension is currently being used by a version of SQLite too old to
   128310 ** support estimatedRows. In that case this function is a no-op.
   128311 */
   128312 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
   128313 #if SQLITE_VERSION_NUMBER>=3008002
   128314   if( sqlite3_libversion_number()>=3008002 ){
   128315     pIdxInfo->estimatedRows = nRow;
   128316   }
   128317 #endif
   128318 }
   128319 
   128320 /*
   128321 ** Implementation of the xBestIndex method for FTS3 tables. There
   128322 ** are three possible strategies, in order of preference:
   128323 **
   128324 **   1. Direct lookup by rowid or docid.
   128325 **   2. Full-text search using a MATCH operator on a non-docid column.
   128326 **   3. Linear scan of %_content table.
   128327 */
   128328 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   128329   Fts3Table *p = (Fts3Table *)pVTab;
   128330   int i;                          /* Iterator variable */
   128331   int iCons = -1;                 /* Index of constraint to use */
   128332 
   128333   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
   128334   int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
   128335   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
   128336   int iIdx;
   128337 
   128338   /* By default use a full table scan. This is an expensive option,
   128339   ** so search through the constraints to see if a more efficient
   128340   ** strategy is possible.
   128341   */
   128342   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   128343   pInfo->estimatedCost = 5000000;
   128344   for(i=0; i<pInfo->nConstraint; i++){
   128345     int bDocid;                 /* True if this constraint is on docid */
   128346     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
   128347     if( pCons->usable==0 ){
   128348       if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
   128349         /* There exists an unusable MATCH constraint. This means that if
   128350         ** the planner does elect to use the results of this call as part
   128351         ** of the overall query plan the user will see an "unable to use
   128352         ** function MATCH in the requested context" error. To discourage
   128353         ** this, return a very high cost here.  */
   128354         pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   128355         pInfo->estimatedCost = 1e50;
   128356         fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
   128357         return SQLITE_OK;
   128358       }
   128359       continue;
   128360     }
   128361 
   128362     bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
   128363 
   128364     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
   128365     if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
   128366       pInfo->idxNum = FTS3_DOCID_SEARCH;
   128367       pInfo->estimatedCost = 1.0;
   128368       iCons = i;
   128369     }
   128370 
   128371     /* A MATCH constraint. Use a full-text search.
   128372     **
   128373     ** If there is more than one MATCH constraint available, use the first
   128374     ** one encountered. If there is both a MATCH constraint and a direct
   128375     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
   128376     ** though the rowid/docid lookup is faster than a MATCH query, selecting
   128377     ** it would lead to an "unable to use function MATCH in the requested
   128378     ** context" error.
   128379     */
   128380     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
   128381      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
   128382     ){
   128383       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
   128384       pInfo->estimatedCost = 2.0;
   128385       iCons = i;
   128386     }
   128387 
   128388     /* Equality constraint on the langid column */
   128389     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   128390      && pCons->iColumn==p->nColumn + 2
   128391     ){
   128392       iLangidCons = i;
   128393     }
   128394 
   128395     if( bDocid ){
   128396       switch( pCons->op ){
   128397         case SQLITE_INDEX_CONSTRAINT_GE:
   128398         case SQLITE_INDEX_CONSTRAINT_GT:
   128399           iDocidGe = i;
   128400           break;
   128401 
   128402         case SQLITE_INDEX_CONSTRAINT_LE:
   128403         case SQLITE_INDEX_CONSTRAINT_LT:
   128404           iDocidLe = i;
   128405           break;
   128406       }
   128407     }
   128408   }
   128409 
   128410   iIdx = 1;
   128411   if( iCons>=0 ){
   128412     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
   128413     pInfo->aConstraintUsage[iCons].omit = 1;
   128414   }
   128415   if( iLangidCons>=0 ){
   128416     pInfo->idxNum |= FTS3_HAVE_LANGID;
   128417     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
   128418   }
   128419   if( iDocidGe>=0 ){
   128420     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
   128421     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
   128422   }
   128423   if( iDocidLe>=0 ){
   128424     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
   128425     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
   128426   }
   128427 
   128428   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
   128429   ** docid) order. Both ascending and descending are possible.
   128430   */
   128431   if( pInfo->nOrderBy==1 ){
   128432     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
   128433     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
   128434       if( pOrder->desc ){
   128435         pInfo->idxStr = "DESC";
   128436       }else{
   128437         pInfo->idxStr = "ASC";
   128438       }
   128439       pInfo->orderByConsumed = 1;
   128440     }
   128441   }
   128442 
   128443   assert( p->pSegments==0 );
   128444   return SQLITE_OK;
   128445 }
   128446 
   128447 /*
   128448 ** Implementation of xOpen method.
   128449 */
   128450 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   128451   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
   128452 
   128453   UNUSED_PARAMETER(pVTab);
   128454 
   128455   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
   128456   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
   128457   ** if the allocation fails, return SQLITE_NOMEM.
   128458   */
   128459   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
   128460   if( !pCsr ){
   128461     return SQLITE_NOMEM;
   128462   }
   128463   memset(pCsr, 0, sizeof(Fts3Cursor));
   128464   return SQLITE_OK;
   128465 }
   128466 
   128467 /*
   128468 ** Close the cursor.  For additional information see the documentation
   128469 ** on the xClose method of the virtual table interface.
   128470 */
   128471 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
   128472   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   128473   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   128474   sqlite3_finalize(pCsr->pStmt);
   128475   sqlite3Fts3ExprFree(pCsr->pExpr);
   128476   sqlite3Fts3FreeDeferredTokens(pCsr);
   128477   sqlite3_free(pCsr->aDoclist);
   128478   sqlite3_free(pCsr->aMatchinfo);
   128479   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   128480   sqlite3_free(pCsr);
   128481   return SQLITE_OK;
   128482 }
   128483 
   128484 /*
   128485 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
   128486 ** compose and prepare an SQL statement of the form:
   128487 **
   128488 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
   128489 **
   128490 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
   128491 ** it. If an error occurs, return an SQLite error code.
   128492 **
   128493 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
   128494 */
   128495 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
   128496   int rc = SQLITE_OK;
   128497   if( pCsr->pStmt==0 ){
   128498     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   128499     char *zSql;
   128500     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
   128501     if( !zSql ) return SQLITE_NOMEM;
   128502     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   128503     sqlite3_free(zSql);
   128504   }
   128505   *ppStmt = pCsr->pStmt;
   128506   return rc;
   128507 }
   128508 
   128509 /*
   128510 ** Position the pCsr->pStmt statement so that it is on the row
   128511 ** of the %_content table that contains the last match.  Return
   128512 ** SQLITE_OK on success.
   128513 */
   128514 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
   128515   int rc = SQLITE_OK;
   128516   if( pCsr->isRequireSeek ){
   128517     sqlite3_stmt *pStmt = 0;
   128518 
   128519     rc = fts3CursorSeekStmt(pCsr, &pStmt);
   128520     if( rc==SQLITE_OK ){
   128521       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
   128522       pCsr->isRequireSeek = 0;
   128523       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
   128524         return SQLITE_OK;
   128525       }else{
   128526         rc = sqlite3_reset(pCsr->pStmt);
   128527         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
   128528           /* If no row was found and no error has occurred, then the %_content
   128529           ** table is missing a row that is present in the full-text index.
   128530           ** The data structures are corrupt.  */
   128531           rc = FTS_CORRUPT_VTAB;
   128532           pCsr->isEof = 1;
   128533         }
   128534       }
   128535     }
   128536   }
   128537 
   128538   if( rc!=SQLITE_OK && pContext ){
   128539     sqlite3_result_error_code(pContext, rc);
   128540   }
   128541   return rc;
   128542 }
   128543 
   128544 /*
   128545 ** This function is used to process a single interior node when searching
   128546 ** a b-tree for a term or term prefix. The node data is passed to this
   128547 ** function via the zNode/nNode parameters. The term to search for is
   128548 ** passed in zTerm/nTerm.
   128549 **
   128550 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
   128551 ** of the child node that heads the sub-tree that may contain the term.
   128552 **
   128553 ** If piLast is not NULL, then *piLast is set to the right-most child node
   128554 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
   128555 ** a prefix.
   128556 **
   128557 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
   128558 */
   128559 static int fts3ScanInteriorNode(
   128560   const char *zTerm,              /* Term to select leaves for */
   128561   int nTerm,                      /* Size of term zTerm in bytes */
   128562   const char *zNode,              /* Buffer containing segment interior node */
   128563   int nNode,                      /* Size of buffer at zNode */
   128564   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
   128565   sqlite3_int64 *piLast           /* OUT: Selected child node */
   128566 ){
   128567   int rc = SQLITE_OK;             /* Return code */
   128568   const char *zCsr = zNode;       /* Cursor to iterate through node */
   128569   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
   128570   char *zBuffer = 0;              /* Buffer to load terms into */
   128571   int nAlloc = 0;                 /* Size of allocated buffer */
   128572   int isFirstTerm = 1;            /* True when processing first term on page */
   128573   sqlite3_int64 iChild;           /* Block id of child node to descend to */
   128574 
   128575   /* Skip over the 'height' varint that occurs at the start of every
   128576   ** interior node. Then load the blockid of the left-child of the b-tree
   128577   ** node into variable iChild.
   128578   **
   128579   ** Even if the data structure on disk is corrupted, this (reading two
   128580   ** varints from the buffer) does not risk an overread. If zNode is a
   128581   ** root node, then the buffer comes from a SELECT statement. SQLite does
   128582   ** not make this guarantee explicitly, but in practice there are always
   128583   ** either more than 20 bytes of allocated space following the nNode bytes of
   128584   ** contents, or two zero bytes. Or, if the node is read from the %_segments
   128585   ** table, then there are always 20 bytes of zeroed padding following the
   128586   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
   128587   */
   128588   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   128589   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   128590   if( zCsr>zEnd ){
   128591     return FTS_CORRUPT_VTAB;
   128592   }
   128593 
   128594   while( zCsr<zEnd && (piFirst || piLast) ){
   128595     int cmp;                      /* memcmp() result */
   128596     int nSuffix;                  /* Size of term suffix */
   128597     int nPrefix = 0;              /* Size of term prefix */
   128598     int nBuffer;                  /* Total term size */
   128599 
   128600     /* Load the next term on the node into zBuffer. Use realloc() to expand
   128601     ** the size of zBuffer if required.  */
   128602     if( !isFirstTerm ){
   128603       zCsr += fts3GetVarint32(zCsr, &nPrefix);
   128604     }
   128605     isFirstTerm = 0;
   128606     zCsr += fts3GetVarint32(zCsr, &nSuffix);
   128607 
   128608     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
   128609       rc = FTS_CORRUPT_VTAB;
   128610       goto finish_scan;
   128611     }
   128612     if( nPrefix+nSuffix>nAlloc ){
   128613       char *zNew;
   128614       nAlloc = (nPrefix+nSuffix) * 2;
   128615       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
   128616       if( !zNew ){
   128617         rc = SQLITE_NOMEM;
   128618         goto finish_scan;
   128619       }
   128620       zBuffer = zNew;
   128621     }
   128622     assert( zBuffer );
   128623     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
   128624     nBuffer = nPrefix + nSuffix;
   128625     zCsr += nSuffix;
   128626 
   128627     /* Compare the term we are searching for with the term just loaded from
   128628     ** the interior node. If the specified term is greater than or equal
   128629     ** to the term from the interior node, then all terms on the sub-tree
   128630     ** headed by node iChild are smaller than zTerm. No need to search
   128631     ** iChild.
   128632     **
   128633     ** If the interior node term is larger than the specified term, then
   128634     ** the tree headed by iChild may contain the specified term.
   128635     */
   128636     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
   128637     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
   128638       *piFirst = iChild;
   128639       piFirst = 0;
   128640     }
   128641 
   128642     if( piLast && cmp<0 ){
   128643       *piLast = iChild;
   128644       piLast = 0;
   128645     }
   128646 
   128647     iChild++;
   128648   };
   128649 
   128650   if( piFirst ) *piFirst = iChild;
   128651   if( piLast ) *piLast = iChild;
   128652 
   128653  finish_scan:
   128654   sqlite3_free(zBuffer);
   128655   return rc;
   128656 }
   128657 
   128658 
   128659 /*
   128660 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
   128661 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
   128662 ** contains a term. This function searches the sub-tree headed by the zNode
   128663 ** node for the range of leaf nodes that may contain the specified term
   128664 ** or terms for which the specified term is a prefix.
   128665 **
   128666 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
   128667 ** left-most leaf node in the tree that may contain the specified term.
   128668 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
   128669 ** right-most leaf node that may contain a term for which the specified
   128670 ** term is a prefix.
   128671 **
   128672 ** It is possible that the range of returned leaf nodes does not contain
   128673 ** the specified term or any terms for which it is a prefix. However, if the
   128674 ** segment does contain any such terms, they are stored within the identified
   128675 ** range. Because this function only inspects interior segment nodes (and
   128676 ** never loads leaf nodes into memory), it is not possible to be sure.
   128677 **
   128678 ** If an error occurs, an error code other than SQLITE_OK is returned.
   128679 */
   128680 static int fts3SelectLeaf(
   128681   Fts3Table *p,                   /* Virtual table handle */
   128682   const char *zTerm,              /* Term to select leaves for */
   128683   int nTerm,                      /* Size of term zTerm in bytes */
   128684   const char *zNode,              /* Buffer containing segment interior node */
   128685   int nNode,                      /* Size of buffer at zNode */
   128686   sqlite3_int64 *piLeaf,          /* Selected leaf node */
   128687   sqlite3_int64 *piLeaf2          /* Selected leaf node */
   128688 ){
   128689   int rc;                         /* Return code */
   128690   int iHeight;                    /* Height of this node in tree */
   128691 
   128692   assert( piLeaf || piLeaf2 );
   128693 
   128694   fts3GetVarint32(zNode, &iHeight);
   128695   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
   128696   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
   128697 
   128698   if( rc==SQLITE_OK && iHeight>1 ){
   128699     char *zBlob = 0;              /* Blob read from %_segments table */
   128700     int nBlob;                    /* Size of zBlob in bytes */
   128701 
   128702     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
   128703       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
   128704       if( rc==SQLITE_OK ){
   128705         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
   128706       }
   128707       sqlite3_free(zBlob);
   128708       piLeaf = 0;
   128709       zBlob = 0;
   128710     }
   128711 
   128712     if( rc==SQLITE_OK ){
   128713       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
   128714     }
   128715     if( rc==SQLITE_OK ){
   128716       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
   128717     }
   128718     sqlite3_free(zBlob);
   128719   }
   128720 
   128721   return rc;
   128722 }
   128723 
   128724 /*
   128725 ** This function is used to create delta-encoded serialized lists of FTS3
   128726 ** varints. Each call to this function appends a single varint to a list.
   128727 */
   128728 static void fts3PutDeltaVarint(
   128729   char **pp,                      /* IN/OUT: Output pointer */
   128730   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   128731   sqlite3_int64 iVal              /* Write this value to the list */
   128732 ){
   128733   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
   128734   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
   128735   *piPrev = iVal;
   128736 }
   128737 
   128738 /*
   128739 ** When this function is called, *ppPoslist is assumed to point to the
   128740 ** start of a position-list. After it returns, *ppPoslist points to the
   128741 ** first byte after the position-list.
   128742 **
   128743 ** A position list is list of positions (delta encoded) and columns for
   128744 ** a single document record of a doclist.  So, in other words, this
   128745 ** routine advances *ppPoslist so that it points to the next docid in
   128746 ** the doclist, or to the first byte past the end of the doclist.
   128747 **
   128748 ** If pp is not NULL, then the contents of the position list are copied
   128749 ** to *pp. *pp is set to point to the first byte past the last byte copied
   128750 ** before this function returns.
   128751 */
   128752 static void fts3PoslistCopy(char **pp, char **ppPoslist){
   128753   char *pEnd = *ppPoslist;
   128754   char c = 0;
   128755 
   128756   /* The end of a position list is marked by a zero encoded as an FTS3
   128757   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
   128758   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
   128759   ** of some other, multi-byte, value.
   128760   **
   128761   ** The following while-loop moves pEnd to point to the first byte that is not
   128762   ** immediately preceded by a byte with the 0x80 bit set. Then increments
   128763   ** pEnd once more so that it points to the byte immediately following the
   128764   ** last byte in the position-list.
   128765   */
   128766   while( *pEnd | c ){
   128767     c = *pEnd++ & 0x80;
   128768     testcase( c!=0 && (*pEnd)==0 );
   128769   }
   128770   pEnd++;  /* Advance past the POS_END terminator byte */
   128771 
   128772   if( pp ){
   128773     int n = (int)(pEnd - *ppPoslist);
   128774     char *p = *pp;
   128775     memcpy(p, *ppPoslist, n);
   128776     p += n;
   128777     *pp = p;
   128778   }
   128779   *ppPoslist = pEnd;
   128780 }
   128781 
   128782 /*
   128783 ** When this function is called, *ppPoslist is assumed to point to the
   128784 ** start of a column-list. After it returns, *ppPoslist points to the
   128785 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
   128786 **
   128787 ** A column-list is list of delta-encoded positions for a single column
   128788 ** within a single document within a doclist.
   128789 **
   128790 ** The column-list is terminated either by a POS_COLUMN varint (1) or
   128791 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
   128792 ** the POS_COLUMN or POS_END that terminates the column-list.
   128793 **
   128794 ** If pp is not NULL, then the contents of the column-list are copied
   128795 ** to *pp. *pp is set to point to the first byte past the last byte copied
   128796 ** before this function returns.  The POS_COLUMN or POS_END terminator
   128797 ** is not copied into *pp.
   128798 */
   128799 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
   128800   char *pEnd = *ppPoslist;
   128801   char c = 0;
   128802 
   128803   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
   128804   ** not part of a multi-byte varint.
   128805   */
   128806   while( 0xFE & (*pEnd | c) ){
   128807     c = *pEnd++ & 0x80;
   128808     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
   128809   }
   128810   if( pp ){
   128811     int n = (int)(pEnd - *ppPoslist);
   128812     char *p = *pp;
   128813     memcpy(p, *ppPoslist, n);
   128814     p += n;
   128815     *pp = p;
   128816   }
   128817   *ppPoslist = pEnd;
   128818 }
   128819 
   128820 /*
   128821 ** Value used to signify the end of an position-list. This is safe because
   128822 ** it is not possible to have a document with 2^31 terms.
   128823 */
   128824 #define POSITION_LIST_END 0x7fffffff
   128825 
   128826 /*
   128827 ** This function is used to help parse position-lists. When this function is
   128828 ** called, *pp may point to the start of the next varint in the position-list
   128829 ** being parsed, or it may point to 1 byte past the end of the position-list
   128830 ** (in which case **pp will be a terminator bytes POS_END (0) or
   128831 ** (1)).
   128832 **
   128833 ** If *pp points past the end of the current position-list, set *pi to
   128834 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
   128835 ** increment the current value of *pi by the value read, and set *pp to
   128836 ** point to the next value before returning.
   128837 **
   128838 ** Before calling this routine *pi must be initialized to the value of
   128839 ** the previous position, or zero if we are reading the first position
   128840 ** in the position-list.  Because positions are delta-encoded, the value
   128841 ** of the previous position is needed in order to compute the value of
   128842 ** the next position.
   128843 */
   128844 static void fts3ReadNextPos(
   128845   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
   128846   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
   128847 ){
   128848   if( (**pp)&0xFE ){
   128849     fts3GetDeltaVarint(pp, pi);
   128850     *pi -= 2;
   128851   }else{
   128852     *pi = POSITION_LIST_END;
   128853   }
   128854 }
   128855 
   128856 /*
   128857 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
   128858 ** the value of iCol encoded as a varint to *pp.   This will start a new
   128859 ** column list.
   128860 **
   128861 ** Set *pp to point to the byte just after the last byte written before
   128862 ** returning (do not modify it if iCol==0). Return the total number of bytes
   128863 ** written (0 if iCol==0).
   128864 */
   128865 static int fts3PutColNumber(char **pp, int iCol){
   128866   int n = 0;                      /* Number of bytes written */
   128867   if( iCol ){
   128868     char *p = *pp;                /* Output pointer */
   128869     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
   128870     *p = 0x01;
   128871     *pp = &p[n];
   128872   }
   128873   return n;
   128874 }
   128875 
   128876 /*
   128877 ** Compute the union of two position lists.  The output written
   128878 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
   128879 ** order and with any duplicates removed.  All pointers are
   128880 ** updated appropriately.   The caller is responsible for insuring
   128881 ** that there is enough space in *pp to hold the complete output.
   128882 */
   128883 static void fts3PoslistMerge(
   128884   char **pp,                      /* Output buffer */
   128885   char **pp1,                     /* Left input list */
   128886   char **pp2                      /* Right input list */
   128887 ){
   128888   char *p = *pp;
   128889   char *p1 = *pp1;
   128890   char *p2 = *pp2;
   128891 
   128892   while( *p1 || *p2 ){
   128893     int iCol1;         /* The current column index in pp1 */
   128894     int iCol2;         /* The current column index in pp2 */
   128895 
   128896     if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
   128897     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
   128898     else iCol1 = 0;
   128899 
   128900     if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
   128901     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
   128902     else iCol2 = 0;
   128903 
   128904     if( iCol1==iCol2 ){
   128905       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
   128906       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
   128907       sqlite3_int64 iPrev = 0;
   128908       int n = fts3PutColNumber(&p, iCol1);
   128909       p1 += n;
   128910       p2 += n;
   128911 
   128912       /* At this point, both p1 and p2 point to the start of column-lists
   128913       ** for the same column (the column with index iCol1 and iCol2).
   128914       ** A column-list is a list of non-negative delta-encoded varints, each
   128915       ** incremented by 2 before being stored. Each list is terminated by a
   128916       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
   128917       ** and writes the results to buffer p. p is left pointing to the byte
   128918       ** after the list written. No terminator (POS_END or POS_COLUMN) is
   128919       ** written to the output.
   128920       */
   128921       fts3GetDeltaVarint(&p1, &i1);
   128922       fts3GetDeltaVarint(&p2, &i2);
   128923       do {
   128924         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
   128925         iPrev -= 2;
   128926         if( i1==i2 ){
   128927           fts3ReadNextPos(&p1, &i1);
   128928           fts3ReadNextPos(&p2, &i2);
   128929         }else if( i1<i2 ){
   128930           fts3ReadNextPos(&p1, &i1);
   128931         }else{
   128932           fts3ReadNextPos(&p2, &i2);
   128933         }
   128934       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
   128935     }else if( iCol1<iCol2 ){
   128936       p1 += fts3PutColNumber(&p, iCol1);
   128937       fts3ColumnlistCopy(&p, &p1);
   128938     }else{
   128939       p2 += fts3PutColNumber(&p, iCol2);
   128940       fts3ColumnlistCopy(&p, &p2);
   128941     }
   128942   }
   128943 
   128944   *p++ = POS_END;
   128945   *pp = p;
   128946   *pp1 = p1 + 1;
   128947   *pp2 = p2 + 1;
   128948 }
   128949 
   128950 /*
   128951 ** This function is used to merge two position lists into one. When it is
   128952 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
   128953 ** the part of a doclist that follows each document id. For example, if a row
   128954 ** contains:
   128955 **
   128956 **     'a b c'|'x y z'|'a b b a'
   128957 **
   128958 ** Then the position list for this row for token 'b' would consist of:
   128959 **
   128960 **     0x02 0x01 0x02 0x03 0x03 0x00
   128961 **
   128962 ** When this function returns, both *pp1 and *pp2 are left pointing to the
   128963 ** byte following the 0x00 terminator of their respective position lists.
   128964 **
   128965 ** If isSaveLeft is 0, an entry is added to the output position list for
   128966 ** each position in *pp2 for which there exists one or more positions in
   128967 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
   128968 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
   128969 ** slots before it.
   128970 **
   128971 ** e.g. nToken==1 searches for adjacent positions.
   128972 */
   128973 static int fts3PoslistPhraseMerge(
   128974   char **pp,                      /* IN/OUT: Preallocated output buffer */
   128975   int nToken,                     /* Maximum difference in token positions */
   128976   int isSaveLeft,                 /* Save the left position */
   128977   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
   128978   char **pp1,                     /* IN/OUT: Left input list */
   128979   char **pp2                      /* IN/OUT: Right input list */
   128980 ){
   128981   char *p = *pp;
   128982   char *p1 = *pp1;
   128983   char *p2 = *pp2;
   128984   int iCol1 = 0;
   128985   int iCol2 = 0;
   128986 
   128987   /* Never set both isSaveLeft and isExact for the same invocation. */
   128988   assert( isSaveLeft==0 || isExact==0 );
   128989 
   128990   assert( p!=0 && *p1!=0 && *p2!=0 );
   128991   if( *p1==POS_COLUMN ){
   128992     p1++;
   128993     p1 += fts3GetVarint32(p1, &iCol1);
   128994   }
   128995   if( *p2==POS_COLUMN ){
   128996     p2++;
   128997     p2 += fts3GetVarint32(p2, &iCol2);
   128998   }
   128999 
   129000   while( 1 ){
   129001     if( iCol1==iCol2 ){
   129002       char *pSave = p;
   129003       sqlite3_int64 iPrev = 0;
   129004       sqlite3_int64 iPos1 = 0;
   129005       sqlite3_int64 iPos2 = 0;
   129006 
   129007       if( iCol1 ){
   129008         *p++ = POS_COLUMN;
   129009         p += sqlite3Fts3PutVarint(p, iCol1);
   129010       }
   129011 
   129012       assert( *p1!=POS_END && *p1!=POS_COLUMN );
   129013       assert( *p2!=POS_END && *p2!=POS_COLUMN );
   129014       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   129015       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   129016 
   129017       while( 1 ){
   129018         if( iPos2==iPos1+nToken
   129019          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
   129020         ){
   129021           sqlite3_int64 iSave;
   129022           iSave = isSaveLeft ? iPos1 : iPos2;
   129023           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
   129024           pSave = 0;
   129025           assert( p );
   129026         }
   129027         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
   129028           if( (*p2&0xFE)==0 ) break;
   129029           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   129030         }else{
   129031           if( (*p1&0xFE)==0 ) break;
   129032           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   129033         }
   129034       }
   129035 
   129036       if( pSave ){
   129037         assert( pp && p );
   129038         p = pSave;
   129039       }
   129040 
   129041       fts3ColumnlistCopy(0, &p1);
   129042       fts3ColumnlistCopy(0, &p2);
   129043       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
   129044       if( 0==*p1 || 0==*p2 ) break;
   129045 
   129046       p1++;
   129047       p1 += fts3GetVarint32(p1, &iCol1);
   129048       p2++;
   129049       p2 += fts3GetVarint32(p2, &iCol2);
   129050     }
   129051 
   129052     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
   129053     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
   129054     ** end of the position list, or the 0x01 that precedes the next
   129055     ** column-number in the position list.
   129056     */
   129057     else if( iCol1<iCol2 ){
   129058       fts3ColumnlistCopy(0, &p1);
   129059       if( 0==*p1 ) break;
   129060       p1++;
   129061       p1 += fts3GetVarint32(p1, &iCol1);
   129062     }else{
   129063       fts3ColumnlistCopy(0, &p2);
   129064       if( 0==*p2 ) break;
   129065       p2++;
   129066       p2 += fts3GetVarint32(p2, &iCol2);
   129067     }
   129068   }
   129069 
   129070   fts3PoslistCopy(0, &p2);
   129071   fts3PoslistCopy(0, &p1);
   129072   *pp1 = p1;
   129073   *pp2 = p2;
   129074   if( *pp==p ){
   129075     return 0;
   129076   }
   129077   *p++ = 0x00;
   129078   *pp = p;
   129079   return 1;
   129080 }
   129081 
   129082 /*
   129083 ** Merge two position-lists as required by the NEAR operator. The argument
   129084 ** position lists correspond to the left and right phrases of an expression
   129085 ** like:
   129086 **
   129087 **     "phrase 1" NEAR "phrase number 2"
   129088 **
   129089 ** Position list *pp1 corresponds to the left-hand side of the NEAR
   129090 ** expression and *pp2 to the right. As usual, the indexes in the position
   129091 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
   129092 ** in the example above).
   129093 **
   129094 ** The output position list - written to *pp - is a copy of *pp2 with those
   129095 ** entries that are not sufficiently NEAR entries in *pp1 removed.
   129096 */
   129097 static int fts3PoslistNearMerge(
   129098   char **pp,                      /* Output buffer */
   129099   char *aTmp,                     /* Temporary buffer space */
   129100   int nRight,                     /* Maximum difference in token positions */
   129101   int nLeft,                      /* Maximum difference in token positions */
   129102   char **pp1,                     /* IN/OUT: Left input list */
   129103   char **pp2                      /* IN/OUT: Right input list */
   129104 ){
   129105   char *p1 = *pp1;
   129106   char *p2 = *pp2;
   129107 
   129108   char *pTmp1 = aTmp;
   129109   char *pTmp2;
   129110   char *aTmp2;
   129111   int res = 1;
   129112 
   129113   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
   129114   aTmp2 = pTmp2 = pTmp1;
   129115   *pp1 = p1;
   129116   *pp2 = p2;
   129117   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
   129118   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
   129119     fts3PoslistMerge(pp, &aTmp, &aTmp2);
   129120   }else if( pTmp1!=aTmp ){
   129121     fts3PoslistCopy(pp, &aTmp);
   129122   }else if( pTmp2!=aTmp2 ){
   129123     fts3PoslistCopy(pp, &aTmp2);
   129124   }else{
   129125     res = 0;
   129126   }
   129127 
   129128   return res;
   129129 }
   129130 
   129131 /*
   129132 ** An instance of this function is used to merge together the (potentially
   129133 ** large number of) doclists for each term that matches a prefix query.
   129134 ** See function fts3TermSelectMerge() for details.
   129135 */
   129136 typedef struct TermSelect TermSelect;
   129137 struct TermSelect {
   129138   char *aaOutput[16];             /* Malloc'd output buffers */
   129139   int anOutput[16];               /* Size each output buffer in bytes */
   129140 };
   129141 
   129142 /*
   129143 ** This function is used to read a single varint from a buffer. Parameter
   129144 ** pEnd points 1 byte past the end of the buffer. When this function is
   129145 ** called, if *pp points to pEnd or greater, then the end of the buffer
   129146 ** has been reached. In this case *pp is set to 0 and the function returns.
   129147 **
   129148 ** If *pp does not point to or past pEnd, then a single varint is read
   129149 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
   129150 **
   129151 ** If bDescIdx is false, the value read is added to *pVal before returning.
   129152 ** If it is true, the value read is subtracted from *pVal before this
   129153 ** function returns.
   129154 */
   129155 static void fts3GetDeltaVarint3(
   129156   char **pp,                      /* IN/OUT: Point to read varint from */
   129157   char *pEnd,                     /* End of buffer */
   129158   int bDescIdx,                   /* True if docids are descending */
   129159   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
   129160 ){
   129161   if( *pp>=pEnd ){
   129162     *pp = 0;
   129163   }else{
   129164     sqlite3_int64 iVal;
   129165     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   129166     if( bDescIdx ){
   129167       *pVal -= iVal;
   129168     }else{
   129169       *pVal += iVal;
   129170     }
   129171   }
   129172 }
   129173 
   129174 /*
   129175 ** This function is used to write a single varint to a buffer. The varint
   129176 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
   129177 ** end of the value written.
   129178 **
   129179 ** If *pbFirst is zero when this function is called, the value written to
   129180 ** the buffer is that of parameter iVal.
   129181 **
   129182 ** If *pbFirst is non-zero when this function is called, then the value
   129183 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
   129184 ** (if bDescIdx is non-zero).
   129185 **
   129186 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
   129187 ** to the value of parameter iVal.
   129188 */
   129189 static void fts3PutDeltaVarint3(
   129190   char **pp,                      /* IN/OUT: Output pointer */
   129191   int bDescIdx,                   /* True for descending docids */
   129192   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   129193   int *pbFirst,                   /* IN/OUT: True after first int written */
   129194   sqlite3_int64 iVal              /* Write this value to the list */
   129195 ){
   129196   sqlite3_int64 iWrite;
   129197   if( bDescIdx==0 || *pbFirst==0 ){
   129198     iWrite = iVal - *piPrev;
   129199   }else{
   129200     iWrite = *piPrev - iVal;
   129201   }
   129202   assert( *pbFirst || *piPrev==0 );
   129203   assert( *pbFirst==0 || iWrite>0 );
   129204   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
   129205   *piPrev = iVal;
   129206   *pbFirst = 1;
   129207 }
   129208 
   129209 
   129210 /*
   129211 ** This macro is used by various functions that merge doclists. The two
   129212 ** arguments are 64-bit docid values. If the value of the stack variable
   129213 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
   129214 ** Otherwise, (i2-i1).
   129215 **
   129216 ** Using this makes it easier to write code that can merge doclists that are
   129217 ** sorted in either ascending or descending order.
   129218 */
   129219 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
   129220 
   129221 /*
   129222 ** This function does an "OR" merge of two doclists (output contains all
   129223 ** positions contained in either argument doclist). If the docids in the
   129224 ** input doclists are sorted in ascending order, parameter bDescDoclist
   129225 ** should be false. If they are sorted in ascending order, it should be
   129226 ** passed a non-zero value.
   129227 **
   129228 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
   129229 ** containing the output doclist and SQLITE_OK is returned. In this case
   129230 ** *pnOut is set to the number of bytes in the output doclist.
   129231 **
   129232 ** If an error occurs, an SQLite error code is returned. The output values
   129233 ** are undefined in this case.
   129234 */
   129235 static int fts3DoclistOrMerge(
   129236   int bDescDoclist,               /* True if arguments are desc */
   129237   char *a1, int n1,               /* First doclist */
   129238   char *a2, int n2,               /* Second doclist */
   129239   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
   129240 ){
   129241   sqlite3_int64 i1 = 0;
   129242   sqlite3_int64 i2 = 0;
   129243   sqlite3_int64 iPrev = 0;
   129244   char *pEnd1 = &a1[n1];
   129245   char *pEnd2 = &a2[n2];
   129246   char *p1 = a1;
   129247   char *p2 = a2;
   129248   char *p;
   129249   char *aOut;
   129250   int bFirstOut = 0;
   129251 
   129252   *paOut = 0;
   129253   *pnOut = 0;
   129254 
   129255   /* Allocate space for the output. Both the input and output doclists
   129256   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
   129257   ** then the first docid in each list is simply encoded as a varint. For
   129258   ** each subsequent docid, the varint stored is the difference between the
   129259   ** current and previous docid (a positive number - since the list is in
   129260   ** ascending order).
   129261   **
   129262   ** The first docid written to the output is therefore encoded using the
   129263   ** same number of bytes as it is in whichever of the input lists it is
   129264   ** read from. And each subsequent docid read from the same input list
   129265   ** consumes either the same or less bytes as it did in the input (since
   129266   ** the difference between it and the previous value in the output must
   129267   ** be a positive value less than or equal to the delta value read from
   129268   ** the input list). The same argument applies to all but the first docid
   129269   ** read from the 'other' list. And to the contents of all position lists
   129270   ** that will be copied and merged from the input to the output.
   129271   **
   129272   ** However, if the first docid copied to the output is a negative number,
   129273   ** then the encoding of the first docid from the 'other' input list may
   129274   ** be larger in the output than it was in the input (since the delta value
   129275   ** may be a larger positive integer than the actual docid).
   129276   **
   129277   ** The space required to store the output is therefore the sum of the
   129278   ** sizes of the two inputs, plus enough space for exactly one of the input
   129279   ** docids to grow.
   129280   **
   129281   ** A symetric argument may be made if the doclists are in descending
   129282   ** order.
   129283   */
   129284   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
   129285   if( !aOut ) return SQLITE_NOMEM;
   129286 
   129287   p = aOut;
   129288   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   129289   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   129290   while( p1 || p2 ){
   129291     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   129292 
   129293     if( p2 && p1 && iDiff==0 ){
   129294       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   129295       fts3PoslistMerge(&p, &p1, &p2);
   129296       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   129297       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   129298     }else if( !p2 || (p1 && iDiff<0) ){
   129299       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   129300       fts3PoslistCopy(&p, &p1);
   129301       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   129302     }else{
   129303       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
   129304       fts3PoslistCopy(&p, &p2);
   129305       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   129306     }
   129307   }
   129308 
   129309   *paOut = aOut;
   129310   *pnOut = (int)(p-aOut);
   129311   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
   129312   return SQLITE_OK;
   129313 }
   129314 
   129315 /*
   129316 ** This function does a "phrase" merge of two doclists. In a phrase merge,
   129317 ** the output contains a copy of each position from the right-hand input
   129318 ** doclist for which there is a position in the left-hand input doclist
   129319 ** exactly nDist tokens before it.
   129320 **
   129321 ** If the docids in the input doclists are sorted in ascending order,
   129322 ** parameter bDescDoclist should be false. If they are sorted in ascending
   129323 ** order, it should be passed a non-zero value.
   129324 **
   129325 ** The right-hand input doclist is overwritten by this function.
   129326 */
   129327 static void fts3DoclistPhraseMerge(
   129328   int bDescDoclist,               /* True if arguments are desc */
   129329   int nDist,                      /* Distance from left to right (1=adjacent) */
   129330   char *aLeft, int nLeft,         /* Left doclist */
   129331   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
   129332 ){
   129333   sqlite3_int64 i1 = 0;
   129334   sqlite3_int64 i2 = 0;
   129335   sqlite3_int64 iPrev = 0;
   129336   char *pEnd1 = &aLeft[nLeft];
   129337   char *pEnd2 = &aRight[*pnRight];
   129338   char *p1 = aLeft;
   129339   char *p2 = aRight;
   129340   char *p;
   129341   int bFirstOut = 0;
   129342   char *aOut = aRight;
   129343 
   129344   assert( nDist>0 );
   129345 
   129346   p = aOut;
   129347   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   129348   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   129349 
   129350   while( p1 && p2 ){
   129351     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   129352     if( iDiff==0 ){
   129353       char *pSave = p;
   129354       sqlite3_int64 iPrevSave = iPrev;
   129355       int bFirstOutSave = bFirstOut;
   129356 
   129357       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   129358       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
   129359         p = pSave;
   129360         iPrev = iPrevSave;
   129361         bFirstOut = bFirstOutSave;
   129362       }
   129363       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   129364       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   129365     }else if( iDiff<0 ){
   129366       fts3PoslistCopy(0, &p1);
   129367       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   129368     }else{
   129369       fts3PoslistCopy(0, &p2);
   129370       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   129371     }
   129372   }
   129373 
   129374   *pnRight = (int)(p - aOut);
   129375 }
   129376 
   129377 /*
   129378 ** Argument pList points to a position list nList bytes in size. This
   129379 ** function checks to see if the position list contains any entries for
   129380 ** a token in position 0 (of any column). If so, it writes argument iDelta
   129381 ** to the output buffer pOut, followed by a position list consisting only
   129382 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
   129383 ** The value returned is the number of bytes written to pOut (if any).
   129384 */
   129385 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
   129386   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
   129387   char *pList,                    /* Position list (no 0x00 term) */
   129388   int nList,                      /* Size of pList in bytes */
   129389   char *pOut                      /* Write output here */
   129390 ){
   129391   int nOut = 0;
   129392   int bWritten = 0;               /* True once iDelta has been written */
   129393   char *p = pList;
   129394   char *pEnd = &pList[nList];
   129395 
   129396   if( *p!=0x01 ){
   129397     if( *p==0x02 ){
   129398       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   129399       pOut[nOut++] = 0x02;
   129400       bWritten = 1;
   129401     }
   129402     fts3ColumnlistCopy(0, &p);
   129403   }
   129404 
   129405   while( p<pEnd && *p==0x01 ){
   129406     sqlite3_int64 iCol;
   129407     p++;
   129408     p += sqlite3Fts3GetVarint(p, &iCol);
   129409     if( *p==0x02 ){
   129410       if( bWritten==0 ){
   129411         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   129412         bWritten = 1;
   129413       }
   129414       pOut[nOut++] = 0x01;
   129415       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
   129416       pOut[nOut++] = 0x02;
   129417     }
   129418     fts3ColumnlistCopy(0, &p);
   129419   }
   129420   if( bWritten ){
   129421     pOut[nOut++] = 0x00;
   129422   }
   129423 
   129424   return nOut;
   129425 }
   129426 
   129427 
   129428 /*
   129429 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
   129430 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
   129431 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
   129432 **
   129433 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
   129434 ** the responsibility of the caller to free any doclists left in the
   129435 ** TermSelect.aaOutput[] array.
   129436 */
   129437 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
   129438   char *aOut = 0;
   129439   int nOut = 0;
   129440   int i;
   129441 
   129442   /* Loop through the doclists in the aaOutput[] array. Merge them all
   129443   ** into a single doclist.
   129444   */
   129445   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
   129446     if( pTS->aaOutput[i] ){
   129447       if( !aOut ){
   129448         aOut = pTS->aaOutput[i];
   129449         nOut = pTS->anOutput[i];
   129450         pTS->aaOutput[i] = 0;
   129451       }else{
   129452         int nNew;
   129453         char *aNew;
   129454 
   129455         int rc = fts3DoclistOrMerge(p->bDescIdx,
   129456             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
   129457         );
   129458         if( rc!=SQLITE_OK ){
   129459           sqlite3_free(aOut);
   129460           return rc;
   129461         }
   129462 
   129463         sqlite3_free(pTS->aaOutput[i]);
   129464         sqlite3_free(aOut);
   129465         pTS->aaOutput[i] = 0;
   129466         aOut = aNew;
   129467         nOut = nNew;
   129468       }
   129469     }
   129470   }
   129471 
   129472   pTS->aaOutput[0] = aOut;
   129473   pTS->anOutput[0] = nOut;
   129474   return SQLITE_OK;
   129475 }
   129476 
   129477 /*
   129478 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
   129479 ** as the first argument. The merge is an "OR" merge (see function
   129480 ** fts3DoclistOrMerge() for details).
   129481 **
   129482 ** This function is called with the doclist for each term that matches
   129483 ** a queried prefix. It merges all these doclists into one, the doclist
   129484 ** for the specified prefix. Since there can be a very large number of
   129485 ** doclists to merge, the merging is done pair-wise using the TermSelect
   129486 ** object.
   129487 **
   129488 ** This function returns SQLITE_OK if the merge is successful, or an
   129489 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
   129490 */
   129491 static int fts3TermSelectMerge(
   129492   Fts3Table *p,                   /* FTS table handle */
   129493   TermSelect *pTS,                /* TermSelect object to merge into */
   129494   char *aDoclist,                 /* Pointer to doclist */
   129495   int nDoclist                    /* Size of aDoclist in bytes */
   129496 ){
   129497   if( pTS->aaOutput[0]==0 ){
   129498     /* If this is the first term selected, copy the doclist to the output
   129499     ** buffer using memcpy(). */
   129500     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
   129501     pTS->anOutput[0] = nDoclist;
   129502     if( pTS->aaOutput[0] ){
   129503       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
   129504     }else{
   129505       return SQLITE_NOMEM;
   129506     }
   129507   }else{
   129508     char *aMerge = aDoclist;
   129509     int nMerge = nDoclist;
   129510     int iOut;
   129511 
   129512     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
   129513       if( pTS->aaOutput[iOut]==0 ){
   129514         assert( iOut>0 );
   129515         pTS->aaOutput[iOut] = aMerge;
   129516         pTS->anOutput[iOut] = nMerge;
   129517         break;
   129518       }else{
   129519         char *aNew;
   129520         int nNew;
   129521 
   129522         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
   129523             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
   129524         );
   129525         if( rc!=SQLITE_OK ){
   129526           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   129527           return rc;
   129528         }
   129529 
   129530         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   129531         sqlite3_free(pTS->aaOutput[iOut]);
   129532         pTS->aaOutput[iOut] = 0;
   129533 
   129534         aMerge = aNew;
   129535         nMerge = nNew;
   129536         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
   129537           pTS->aaOutput[iOut] = aMerge;
   129538           pTS->anOutput[iOut] = nMerge;
   129539         }
   129540       }
   129541     }
   129542   }
   129543   return SQLITE_OK;
   129544 }
   129545 
   129546 /*
   129547 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
   129548 */
   129549 static int fts3SegReaderCursorAppend(
   129550   Fts3MultiSegReader *pCsr,
   129551   Fts3SegReader *pNew
   129552 ){
   129553   if( (pCsr->nSegment%16)==0 ){
   129554     Fts3SegReader **apNew;
   129555     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
   129556     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
   129557     if( !apNew ){
   129558       sqlite3Fts3SegReaderFree(pNew);
   129559       return SQLITE_NOMEM;
   129560     }
   129561     pCsr->apSegment = apNew;
   129562   }
   129563   pCsr->apSegment[pCsr->nSegment++] = pNew;
   129564   return SQLITE_OK;
   129565 }
   129566 
   129567 /*
   129568 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
   129569 ** 8th argument.
   129570 **
   129571 ** This function returns SQLITE_OK if successful, or an SQLite error code
   129572 ** otherwise.
   129573 */
   129574 static int fts3SegReaderCursor(
   129575   Fts3Table *p,                   /* FTS3 table handle */
   129576   int iLangid,                    /* Language id */
   129577   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   129578   int iLevel,                     /* Level of segments to scan */
   129579   const char *zTerm,              /* Term to query for */
   129580   int nTerm,                      /* Size of zTerm in bytes */
   129581   int isPrefix,                   /* True for a prefix search */
   129582   int isScan,                     /* True to scan from zTerm to EOF */
   129583   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
   129584 ){
   129585   int rc = SQLITE_OK;             /* Error code */
   129586   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
   129587   int rc2;                        /* Result of sqlite3_reset() */
   129588 
   129589   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
   129590   ** for the pending-terms. If this is a scan, then this call must be being
   129591   ** made by an fts4aux module, not an FTS table. In this case calling
   129592   ** Fts3SegReaderPending might segfault, as the data structures used by
   129593   ** fts4aux are not completely populated. So it's easiest to filter these
   129594   ** calls out here.  */
   129595   if( iLevel<0 && p->aIndex ){
   129596     Fts3SegReader *pSeg = 0;
   129597     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
   129598     if( rc==SQLITE_OK && pSeg ){
   129599       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   129600     }
   129601   }
   129602 
   129603   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   129604     if( rc==SQLITE_OK ){
   129605       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
   129606     }
   129607 
   129608     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   129609       Fts3SegReader *pSeg = 0;
   129610 
   129611       /* Read the values returned by the SELECT into local variables. */
   129612       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
   129613       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
   129614       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
   129615       int nRoot = sqlite3_column_bytes(pStmt, 4);
   129616       char const *zRoot = sqlite3_column_blob(pStmt, 4);
   129617 
   129618       /* If zTerm is not NULL, and this segment is not stored entirely on its
   129619       ** root node, the range of leaves scanned can be reduced. Do this. */
   129620       if( iStartBlock && zTerm ){
   129621         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
   129622         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
   129623         if( rc!=SQLITE_OK ) goto finished;
   129624         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
   129625       }
   129626 
   129627       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
   129628           (isPrefix==0 && isScan==0),
   129629           iStartBlock, iLeavesEndBlock,
   129630           iEndBlock, zRoot, nRoot, &pSeg
   129631       );
   129632       if( rc!=SQLITE_OK ) goto finished;
   129633       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   129634     }
   129635   }
   129636 
   129637  finished:
   129638   rc2 = sqlite3_reset(pStmt);
   129639   if( rc==SQLITE_DONE ) rc = rc2;
   129640 
   129641   return rc;
   129642 }
   129643 
   129644 /*
   129645 ** Set up a cursor object for iterating through a full-text index or a
   129646 ** single level therein.
   129647 */
   129648 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
   129649   Fts3Table *p,                   /* FTS3 table handle */
   129650   int iLangid,                    /* Language-id to search */
   129651   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   129652   int iLevel,                     /* Level of segments to scan */
   129653   const char *zTerm,              /* Term to query for */
   129654   int nTerm,                      /* Size of zTerm in bytes */
   129655   int isPrefix,                   /* True for a prefix search */
   129656   int isScan,                     /* True to scan from zTerm to EOF */
   129657   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
   129658 ){
   129659   assert( iIndex>=0 && iIndex<p->nIndex );
   129660   assert( iLevel==FTS3_SEGCURSOR_ALL
   129661       ||  iLevel==FTS3_SEGCURSOR_PENDING
   129662       ||  iLevel>=0
   129663   );
   129664   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   129665   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
   129666   assert( isPrefix==0 || isScan==0 );
   129667 
   129668   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
   129669   return fts3SegReaderCursor(
   129670       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
   129671   );
   129672 }
   129673 
   129674 /*
   129675 ** In addition to its current configuration, have the Fts3MultiSegReader
   129676 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
   129677 **
   129678 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   129679 */
   129680 static int fts3SegReaderCursorAddZero(
   129681   Fts3Table *p,                   /* FTS virtual table handle */
   129682   int iLangid,
   129683   const char *zTerm,              /* Term to scan doclist of */
   129684   int nTerm,                      /* Number of bytes in zTerm */
   129685   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
   129686 ){
   129687   return fts3SegReaderCursor(p,
   129688       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
   129689   );
   129690 }
   129691 
   129692 /*
   129693 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
   129694 ** if isPrefix is true, to scan the doclist for all terms for which
   129695 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
   129696 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
   129697 ** an SQLite error code.
   129698 **
   129699 ** It is the responsibility of the caller to free this object by eventually
   129700 ** passing it to fts3SegReaderCursorFree()
   129701 **
   129702 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   129703 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
   129704 */
   129705 static int fts3TermSegReaderCursor(
   129706   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
   129707   const char *zTerm,              /* Term to query for */
   129708   int nTerm,                      /* Size of zTerm in bytes */
   129709   int isPrefix,                   /* True for a prefix search */
   129710   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
   129711 ){
   129712   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
   129713   int rc = SQLITE_NOMEM;          /* Return code */
   129714 
   129715   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
   129716   if( pSegcsr ){
   129717     int i;
   129718     int bFound = 0;               /* True once an index has been found */
   129719     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   129720 
   129721     if( isPrefix ){
   129722       for(i=1; bFound==0 && i<p->nIndex; i++){
   129723         if( p->aIndex[i].nPrefix==nTerm ){
   129724           bFound = 1;
   129725           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   129726               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
   129727           );
   129728           pSegcsr->bLookup = 1;
   129729         }
   129730       }
   129731 
   129732       for(i=1; bFound==0 && i<p->nIndex; i++){
   129733         if( p->aIndex[i].nPrefix==nTerm+1 ){
   129734           bFound = 1;
   129735           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   129736               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
   129737           );
   129738           if( rc==SQLITE_OK ){
   129739             rc = fts3SegReaderCursorAddZero(
   129740                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
   129741             );
   129742           }
   129743         }
   129744       }
   129745     }
   129746 
   129747     if( bFound==0 ){
   129748       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   129749           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
   129750       );
   129751       pSegcsr->bLookup = !isPrefix;
   129752     }
   129753   }
   129754 
   129755   *ppSegcsr = pSegcsr;
   129756   return rc;
   129757 }
   129758 
   129759 /*
   129760 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
   129761 */
   129762 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
   129763   sqlite3Fts3SegReaderFinish(pSegcsr);
   129764   sqlite3_free(pSegcsr);
   129765 }
   129766 
   129767 /*
   129768 ** This function retrieves the doclist for the specified term (or term
   129769 ** prefix) from the database.
   129770 */
   129771 static int fts3TermSelect(
   129772   Fts3Table *p,                   /* Virtual table handle */
   129773   Fts3PhraseToken *pTok,          /* Token to query for */
   129774   int iColumn,                    /* Column to query (or -ve for all columns) */
   129775   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
   129776   char **ppOut                    /* OUT: Malloced result buffer */
   129777 ){
   129778   int rc;                         /* Return code */
   129779   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
   129780   TermSelect tsc;                 /* Object for pair-wise doclist merging */
   129781   Fts3SegFilter filter;           /* Segment term filter configuration */
   129782 
   129783   pSegcsr = pTok->pSegcsr;
   129784   memset(&tsc, 0, sizeof(TermSelect));
   129785 
   129786   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
   129787         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
   129788         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
   129789         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
   129790   filter.iCol = iColumn;
   129791   filter.zTerm = pTok->z;
   129792   filter.nTerm = pTok->n;
   129793 
   129794   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
   129795   while( SQLITE_OK==rc
   129796       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
   129797   ){
   129798     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
   129799   }
   129800 
   129801   if( rc==SQLITE_OK ){
   129802     rc = fts3TermSelectFinishMerge(p, &tsc);
   129803   }
   129804   if( rc==SQLITE_OK ){
   129805     *ppOut = tsc.aaOutput[0];
   129806     *pnOut = tsc.anOutput[0];
   129807   }else{
   129808     int i;
   129809     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
   129810       sqlite3_free(tsc.aaOutput[i]);
   129811     }
   129812   }
   129813 
   129814   fts3SegReaderCursorFree(pSegcsr);
   129815   pTok->pSegcsr = 0;
   129816   return rc;
   129817 }
   129818 
   129819 /*
   129820 ** This function counts the total number of docids in the doclist stored
   129821 ** in buffer aList[], size nList bytes.
   129822 **
   129823 ** If the isPoslist argument is true, then it is assumed that the doclist
   129824 ** contains a position-list following each docid. Otherwise, it is assumed
   129825 ** that the doclist is simply a list of docids stored as delta encoded
   129826 ** varints.
   129827 */
   129828 static int fts3DoclistCountDocids(char *aList, int nList){
   129829   int nDoc = 0;                   /* Return value */
   129830   if( aList ){
   129831     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
   129832     char *p = aList;              /* Cursor */
   129833     while( p<aEnd ){
   129834       nDoc++;
   129835       while( (*p++)&0x80 );     /* Skip docid varint */
   129836       fts3PoslistCopy(0, &p);   /* Skip over position list */
   129837     }
   129838   }
   129839 
   129840   return nDoc;
   129841 }
   129842 
   129843 /*
   129844 ** Advance the cursor to the next row in the %_content table that
   129845 ** matches the search criteria.  For a MATCH search, this will be
   129846 ** the next row that matches. For a full-table scan, this will be
   129847 ** simply the next row in the %_content table.  For a docid lookup,
   129848 ** this routine simply sets the EOF flag.
   129849 **
   129850 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
   129851 ** even if we reach end-of-file.  The fts3EofMethod() will be called
   129852 ** subsequently to determine whether or not an EOF was hit.
   129853 */
   129854 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
   129855   int rc;
   129856   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   129857   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
   129858     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
   129859       pCsr->isEof = 1;
   129860       rc = sqlite3_reset(pCsr->pStmt);
   129861     }else{
   129862       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
   129863       rc = SQLITE_OK;
   129864     }
   129865   }else{
   129866     rc = fts3EvalNext((Fts3Cursor *)pCursor);
   129867   }
   129868   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   129869   return rc;
   129870 }
   129871 
   129872 /*
   129873 ** The following are copied from sqliteInt.h.
   129874 **
   129875 ** Constants for the largest and smallest possible 64-bit signed integers.
   129876 ** These macros are designed to work correctly on both 32-bit and 64-bit
   129877 ** compilers.
   129878 */
   129879 #ifndef SQLITE_AMALGAMATION
   129880 # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
   129881 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
   129882 #endif
   129883 
   129884 /*
   129885 ** If the numeric type of argument pVal is "integer", then return it
   129886 ** converted to a 64-bit signed integer. Otherwise, return a copy of
   129887 ** the second parameter, iDefault.
   129888 */
   129889 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
   129890   if( pVal ){
   129891     int eType = sqlite3_value_numeric_type(pVal);
   129892     if( eType==SQLITE_INTEGER ){
   129893       return sqlite3_value_int64(pVal);
   129894     }
   129895   }
   129896   return iDefault;
   129897 }
   129898 
   129899 /*
   129900 ** This is the xFilter interface for the virtual table.  See
   129901 ** the virtual table xFilter method documentation for additional
   129902 ** information.
   129903 **
   129904 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
   129905 ** the %_content table.
   129906 **
   129907 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
   129908 ** in the %_content table.
   129909 **
   129910 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
   129911 ** column on the left-hand side of the MATCH operator is column
   129912 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
   129913 ** side of the MATCH operator.
   129914 */
   129915 static int fts3FilterMethod(
   129916   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   129917   int idxNum,                     /* Strategy index */
   129918   const char *idxStr,             /* Unused */
   129919   int nVal,                       /* Number of elements in apVal */
   129920   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   129921 ){
   129922   int rc;
   129923   char *zSql;                     /* SQL statement used to access %_content */
   129924   int eSearch;
   129925   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   129926   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   129927 
   129928   sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
   129929   sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
   129930   sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
   129931   sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
   129932   int iIdx;
   129933 
   129934   UNUSED_PARAMETER(idxStr);
   129935   UNUSED_PARAMETER(nVal);
   129936 
   129937   eSearch = (idxNum & 0x0000FFFF);
   129938   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
   129939   assert( p->pSegments==0 );
   129940 
   129941   /* Collect arguments into local variables */
   129942   iIdx = 0;
   129943   if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
   129944   if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
   129945   if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
   129946   if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
   129947   assert( iIdx==nVal );
   129948 
   129949   /* In case the cursor has been used before, clear it now. */
   129950   sqlite3_finalize(pCsr->pStmt);
   129951   sqlite3_free(pCsr->aDoclist);
   129952   sqlite3Fts3ExprFree(pCsr->pExpr);
   129953   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
   129954 
   129955   /* Set the lower and upper bounds on docids to return */
   129956   pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
   129957   pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
   129958 
   129959   if( idxStr ){
   129960     pCsr->bDesc = (idxStr[0]=='D');
   129961   }else{
   129962     pCsr->bDesc = p->bDescIdx;
   129963   }
   129964   pCsr->eSearch = (i16)eSearch;
   129965 
   129966   if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
   129967     int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
   129968     const char *zQuery = (const char *)sqlite3_value_text(pCons);
   129969 
   129970     if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
   129971       return SQLITE_NOMEM;
   129972     }
   129973 
   129974     pCsr->iLangid = 0;
   129975     if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
   129976 
   129977     assert( p->base.zErrMsg==0 );
   129978     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
   129979         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
   129980         &p->base.zErrMsg
   129981     );
   129982     if( rc!=SQLITE_OK ){
   129983       return rc;
   129984     }
   129985 
   129986     rc = fts3EvalStart(pCsr);
   129987     sqlite3Fts3SegmentsClose(p);
   129988     if( rc!=SQLITE_OK ) return rc;
   129989     pCsr->pNextId = pCsr->aDoclist;
   129990     pCsr->iPrevId = 0;
   129991   }
   129992 
   129993   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
   129994   ** statement loops through all rows of the %_content table. For a
   129995   ** full-text query or docid lookup, the statement retrieves a single
   129996   ** row by docid.
   129997   */
   129998   if( eSearch==FTS3_FULLSCAN_SEARCH ){
   129999     zSql = sqlite3_mprintf(
   130000         "SELECT %s ORDER BY rowid %s",
   130001         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
   130002     );
   130003     if( zSql ){
   130004       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   130005       sqlite3_free(zSql);
   130006     }else{
   130007       rc = SQLITE_NOMEM;
   130008     }
   130009   }else if( eSearch==FTS3_DOCID_SEARCH ){
   130010     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
   130011     if( rc==SQLITE_OK ){
   130012       rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
   130013     }
   130014   }
   130015   if( rc!=SQLITE_OK ) return rc;
   130016 
   130017   return fts3NextMethod(pCursor);
   130018 }
   130019 
   130020 /*
   130021 ** This is the xEof method of the virtual table. SQLite calls this
   130022 ** routine to find out if it has reached the end of a result set.
   130023 */
   130024 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
   130025   return ((Fts3Cursor *)pCursor)->isEof;
   130026 }
   130027 
   130028 /*
   130029 ** This is the xRowid method. The SQLite core calls this routine to
   130030 ** retrieve the rowid for the current row of the result set. fts3
   130031 ** exposes %_content.docid as the rowid for the virtual table. The
   130032 ** rowid should be written to *pRowid.
   130033 */
   130034 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   130035   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   130036   *pRowid = pCsr->iPrevId;
   130037   return SQLITE_OK;
   130038 }
   130039 
   130040 /*
   130041 ** This is the xColumn method, called by SQLite to request a value from
   130042 ** the row that the supplied cursor currently points to.
   130043 **
   130044 ** If:
   130045 **
   130046 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
   130047 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
   130048 **   (iCol == p->nColumn+1) -> Docid column
   130049 **   (iCol == p->nColumn+2) -> Langid column
   130050 */
   130051 static int fts3ColumnMethod(
   130052   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   130053   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   130054   int iCol                        /* Index of column to read value from */
   130055 ){
   130056   int rc = SQLITE_OK;             /* Return Code */
   130057   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   130058   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   130059 
   130060   /* The column value supplied by SQLite must be in range. */
   130061   assert( iCol>=0 && iCol<=p->nColumn+2 );
   130062 
   130063   if( iCol==p->nColumn+1 ){
   130064     /* This call is a request for the "docid" column. Since "docid" is an
   130065     ** alias for "rowid", use the xRowid() method to obtain the value.
   130066     */
   130067     sqlite3_result_int64(pCtx, pCsr->iPrevId);
   130068   }else if( iCol==p->nColumn ){
   130069     /* The extra column whose name is the same as the table.
   130070     ** Return a blob which is a pointer to the cursor.  */
   130071     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
   130072   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
   130073     sqlite3_result_int64(pCtx, pCsr->iLangid);
   130074   }else{
   130075     /* The requested column is either a user column (one that contains
   130076     ** indexed data), or the language-id column.  */
   130077     rc = fts3CursorSeek(0, pCsr);
   130078 
   130079     if( rc==SQLITE_OK ){
   130080       if( iCol==p->nColumn+2 ){
   130081         int iLangid = 0;
   130082         if( p->zLanguageid ){
   130083           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
   130084         }
   130085         sqlite3_result_int(pCtx, iLangid);
   130086       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
   130087         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
   130088       }
   130089     }
   130090   }
   130091 
   130092   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   130093   return rc;
   130094 }
   130095 
   130096 /*
   130097 ** This function is the implementation of the xUpdate callback used by
   130098 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
   130099 ** inserted, updated or deleted.
   130100 */
   130101 static int fts3UpdateMethod(
   130102   sqlite3_vtab *pVtab,            /* Virtual table handle */
   130103   int nArg,                       /* Size of argument array */
   130104   sqlite3_value **apVal,          /* Array of arguments */
   130105   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   130106 ){
   130107   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
   130108 }
   130109 
   130110 /*
   130111 ** Implementation of xSync() method. Flush the contents of the pending-terms
   130112 ** hash-table to the database.
   130113 */
   130114 static int fts3SyncMethod(sqlite3_vtab *pVtab){
   130115 
   130116   /* Following an incremental-merge operation, assuming that the input
   130117   ** segments are not completely consumed (the usual case), they are updated
   130118   ** in place to remove the entries that have already been merged. This
   130119   ** involves updating the leaf block that contains the smallest unmerged
   130120   ** entry and each block (if any) between the leaf and the root node. So
   130121   ** if the height of the input segment b-trees is N, and input segments
   130122   ** are merged eight at a time, updating the input segments at the end
   130123   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
   130124   ** small - often between 0 and 2. So the overhead of the incremental
   130125   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
   130126   ** dwarfing the actual productive work accomplished, the incremental merge
   130127   ** is only attempted if it will write at least 64 leaf blocks. Hence
   130128   ** nMinMerge.
   130129   **
   130130   ** Of course, updating the input segments also involves deleting a bunch
   130131   ** of blocks from the segments table. But this is not considered overhead
   130132   ** as it would also be required by a crisis-merge that used the same input
   130133   ** segments.
   130134   */
   130135   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
   130136 
   130137   Fts3Table *p = (Fts3Table*)pVtab;
   130138   int rc = sqlite3Fts3PendingTermsFlush(p);
   130139 
   130140   if( rc==SQLITE_OK
   130141    && p->nLeafAdd>(nMinMerge/16)
   130142    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
   130143   ){
   130144     int mxLevel = 0;              /* Maximum relative level value in db */
   130145     int A;                        /* Incr-merge parameter A */
   130146 
   130147     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
   130148     assert( rc==SQLITE_OK || mxLevel==0 );
   130149     A = p->nLeafAdd * mxLevel;
   130150     A += (A/2);
   130151     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
   130152   }
   130153   sqlite3Fts3SegmentsClose(p);
   130154   return rc;
   130155 }
   130156 
   130157 /*
   130158 ** If it is currently unknown whether or not the FTS table has an %_stat
   130159 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
   130160 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
   130161 ** if an error occurs.
   130162 */
   130163 static int fts3SetHasStat(Fts3Table *p){
   130164   int rc = SQLITE_OK;
   130165   if( p->bHasStat==2 ){
   130166     const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
   130167     char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
   130168     if( zSql ){
   130169       sqlite3_stmt *pStmt = 0;
   130170       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   130171       if( rc==SQLITE_OK ){
   130172         int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
   130173         rc = sqlite3_finalize(pStmt);
   130174         if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
   130175       }
   130176       sqlite3_free(zSql);
   130177     }else{
   130178       rc = SQLITE_NOMEM;
   130179     }
   130180   }
   130181   return rc;
   130182 }
   130183 
   130184 /*
   130185 ** Implementation of xBegin() method.
   130186 */
   130187 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   130188   Fts3Table *p = (Fts3Table*)pVtab;
   130189   UNUSED_PARAMETER(pVtab);
   130190   assert( p->pSegments==0 );
   130191   assert( p->nPendingData==0 );
   130192   assert( p->inTransaction!=1 );
   130193   TESTONLY( p->inTransaction = 1 );
   130194   TESTONLY( p->mxSavepoint = -1; );
   130195   p->nLeafAdd = 0;
   130196   return fts3SetHasStat(p);
   130197 }
   130198 
   130199 /*
   130200 ** Implementation of xCommit() method. This is a no-op. The contents of
   130201 ** the pending-terms hash-table have already been flushed into the database
   130202 ** by fts3SyncMethod().
   130203 */
   130204 static int fts3CommitMethod(sqlite3_vtab *pVtab){
   130205   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   130206   UNUSED_PARAMETER(pVtab);
   130207   assert( p->nPendingData==0 );
   130208   assert( p->inTransaction!=0 );
   130209   assert( p->pSegments==0 );
   130210   TESTONLY( p->inTransaction = 0 );
   130211   TESTONLY( p->mxSavepoint = -1; );
   130212   return SQLITE_OK;
   130213 }
   130214 
   130215 /*
   130216 ** Implementation of xRollback(). Discard the contents of the pending-terms
   130217 ** hash-table. Any changes made to the database are reverted by SQLite.
   130218 */
   130219 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
   130220   Fts3Table *p = (Fts3Table*)pVtab;
   130221   sqlite3Fts3PendingTermsClear(p);
   130222   assert( p->inTransaction!=0 );
   130223   TESTONLY( p->inTransaction = 0 );
   130224   TESTONLY( p->mxSavepoint = -1; );
   130225   return SQLITE_OK;
   130226 }
   130227 
   130228 /*
   130229 ** When called, *ppPoslist must point to the byte immediately following the
   130230 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
   130231 ** moves *ppPoslist so that it instead points to the first byte of the
   130232 ** same position list.
   130233 */
   130234 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
   130235   char *p = &(*ppPoslist)[-2];
   130236   char c = 0;
   130237 
   130238   while( p>pStart && (c=*p--)==0 );
   130239   while( p>pStart && (*p & 0x80) | c ){
   130240     c = *p--;
   130241   }
   130242   if( p>pStart ){ p = &p[2]; }
   130243   while( *p++&0x80 );
   130244   *ppPoslist = p;
   130245 }
   130246 
   130247 /*
   130248 ** Helper function used by the implementation of the overloaded snippet(),
   130249 ** offsets() and optimize() SQL functions.
   130250 **
   130251 ** If the value passed as the third argument is a blob of size
   130252 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
   130253 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
   130254 ** message is written to context pContext and SQLITE_ERROR returned. The
   130255 ** string passed via zFunc is used as part of the error message.
   130256 */
   130257 static int fts3FunctionArg(
   130258   sqlite3_context *pContext,      /* SQL function call context */
   130259   const char *zFunc,              /* Function name */
   130260   sqlite3_value *pVal,            /* argv[0] passed to function */
   130261   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
   130262 ){
   130263   Fts3Cursor *pRet;
   130264   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
   130265    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
   130266   ){
   130267     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
   130268     sqlite3_result_error(pContext, zErr, -1);
   130269     sqlite3_free(zErr);
   130270     return SQLITE_ERROR;
   130271   }
   130272   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
   130273   *ppCsr = pRet;
   130274   return SQLITE_OK;
   130275 }
   130276 
   130277 /*
   130278 ** Implementation of the snippet() function for FTS3
   130279 */
   130280 static void fts3SnippetFunc(
   130281   sqlite3_context *pContext,      /* SQLite function call context */
   130282   int nVal,                       /* Size of apVal[] array */
   130283   sqlite3_value **apVal           /* Array of arguments */
   130284 ){
   130285   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   130286   const char *zStart = "<b>";
   130287   const char *zEnd = "</b>";
   130288   const char *zEllipsis = "<b>...</b>";
   130289   int iCol = -1;
   130290   int nToken = 15;                /* Default number of tokens in snippet */
   130291 
   130292   /* There must be at least one argument passed to this function (otherwise
   130293   ** the non-overloaded version would have been called instead of this one).
   130294   */
   130295   assert( nVal>=1 );
   130296 
   130297   if( nVal>6 ){
   130298     sqlite3_result_error(pContext,
   130299         "wrong number of arguments to function snippet()", -1);
   130300     return;
   130301   }
   130302   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
   130303 
   130304   switch( nVal ){
   130305     case 6: nToken = sqlite3_value_int(apVal[5]);
   130306     case 5: iCol = sqlite3_value_int(apVal[4]);
   130307     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
   130308     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
   130309     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   130310   }
   130311   if( !zEllipsis || !zEnd || !zStart ){
   130312     sqlite3_result_error_nomem(pContext);
   130313   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   130314     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
   130315   }
   130316 }
   130317 
   130318 /*
   130319 ** Implementation of the offsets() function for FTS3
   130320 */
   130321 static void fts3OffsetsFunc(
   130322   sqlite3_context *pContext,      /* SQLite function call context */
   130323   int nVal,                       /* Size of argument array */
   130324   sqlite3_value **apVal           /* Array of arguments */
   130325 ){
   130326   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   130327 
   130328   UNUSED_PARAMETER(nVal);
   130329 
   130330   assert( nVal==1 );
   130331   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
   130332   assert( pCsr );
   130333   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   130334     sqlite3Fts3Offsets(pContext, pCsr);
   130335   }
   130336 }
   130337 
   130338 /*
   130339 ** Implementation of the special optimize() function for FTS3. This
   130340 ** function merges all segments in the database to a single segment.
   130341 ** Example usage is:
   130342 **
   130343 **   SELECT optimize(t) FROM t LIMIT 1;
   130344 **
   130345 ** where 't' is the name of an FTS3 table.
   130346 */
   130347 static void fts3OptimizeFunc(
   130348   sqlite3_context *pContext,      /* SQLite function call context */
   130349   int nVal,                       /* Size of argument array */
   130350   sqlite3_value **apVal           /* Array of arguments */
   130351 ){
   130352   int rc;                         /* Return code */
   130353   Fts3Table *p;                   /* Virtual table handle */
   130354   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
   130355 
   130356   UNUSED_PARAMETER(nVal);
   130357 
   130358   assert( nVal==1 );
   130359   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
   130360   p = (Fts3Table *)pCursor->base.pVtab;
   130361   assert( p );
   130362 
   130363   rc = sqlite3Fts3Optimize(p);
   130364 
   130365   switch( rc ){
   130366     case SQLITE_OK:
   130367       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
   130368       break;
   130369     case SQLITE_DONE:
   130370       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
   130371       break;
   130372     default:
   130373       sqlite3_result_error_code(pContext, rc);
   130374       break;
   130375   }
   130376 }
   130377 
   130378 /*
   130379 ** Implementation of the matchinfo() function for FTS3
   130380 */
   130381 static void fts3MatchinfoFunc(
   130382   sqlite3_context *pContext,      /* SQLite function call context */
   130383   int nVal,                       /* Size of argument array */
   130384   sqlite3_value **apVal           /* Array of arguments */
   130385 ){
   130386   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   130387   assert( nVal==1 || nVal==2 );
   130388   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
   130389     const char *zArg = 0;
   130390     if( nVal>1 ){
   130391       zArg = (const char *)sqlite3_value_text(apVal[1]);
   130392     }
   130393     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
   130394   }
   130395 }
   130396 
   130397 /*
   130398 ** This routine implements the xFindFunction method for the FTS3
   130399 ** virtual table.
   130400 */
   130401 static int fts3FindFunctionMethod(
   130402   sqlite3_vtab *pVtab,            /* Virtual table handle */
   130403   int nArg,                       /* Number of SQL function arguments */
   130404   const char *zName,              /* Name of SQL function */
   130405   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   130406   void **ppArg                    /* Unused */
   130407 ){
   130408   struct Overloaded {
   130409     const char *zName;
   130410     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   130411   } aOverload[] = {
   130412     { "snippet", fts3SnippetFunc },
   130413     { "offsets", fts3OffsetsFunc },
   130414     { "optimize", fts3OptimizeFunc },
   130415     { "matchinfo", fts3MatchinfoFunc },
   130416   };
   130417   int i;                          /* Iterator variable */
   130418 
   130419   UNUSED_PARAMETER(pVtab);
   130420   UNUSED_PARAMETER(nArg);
   130421   UNUSED_PARAMETER(ppArg);
   130422 
   130423   for(i=0; i<SizeofArray(aOverload); i++){
   130424     if( strcmp(zName, aOverload[i].zName)==0 ){
   130425       *pxFunc = aOverload[i].xFunc;
   130426       return 1;
   130427     }
   130428   }
   130429 
   130430   /* No function of the specified name was found. Return 0. */
   130431   return 0;
   130432 }
   130433 
   130434 /*
   130435 ** Implementation of FTS3 xRename method. Rename an fts3 table.
   130436 */
   130437 static int fts3RenameMethod(
   130438   sqlite3_vtab *pVtab,            /* Virtual table handle */
   130439   const char *zName               /* New name of table */
   130440 ){
   130441   Fts3Table *p = (Fts3Table *)pVtab;
   130442   sqlite3 *db = p->db;            /* Database connection */
   130443   int rc;                         /* Return Code */
   130444 
   130445   /* At this point it must be known if the %_stat table exists or not.
   130446   ** So bHasStat may not be 2.  */
   130447   rc = fts3SetHasStat(p);
   130448 
   130449   /* As it happens, the pending terms table is always empty here. This is
   130450   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
   130451   ** always opens a savepoint transaction. And the xSavepoint() method
   130452   ** flushes the pending terms table. But leave the (no-op) call to
   130453   ** PendingTermsFlush() in in case that changes.
   130454   */
   130455   assert( p->nPendingData==0 );
   130456   if( rc==SQLITE_OK ){
   130457     rc = sqlite3Fts3PendingTermsFlush(p);
   130458   }
   130459 
   130460   if( p->zContentTbl==0 ){
   130461     fts3DbExec(&rc, db,
   130462       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
   130463       p->zDb, p->zName, zName
   130464     );
   130465   }
   130466 
   130467   if( p->bHasDocsize ){
   130468     fts3DbExec(&rc, db,
   130469       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
   130470       p->zDb, p->zName, zName
   130471     );
   130472   }
   130473   if( p->bHasStat ){
   130474     fts3DbExec(&rc, db,
   130475       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
   130476       p->zDb, p->zName, zName
   130477     );
   130478   }
   130479   fts3DbExec(&rc, db,
   130480     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
   130481     p->zDb, p->zName, zName
   130482   );
   130483   fts3DbExec(&rc, db,
   130484     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
   130485     p->zDb, p->zName, zName
   130486   );
   130487   return rc;
   130488 }
   130489 
   130490 /*
   130491 ** The xSavepoint() method.
   130492 **
   130493 ** Flush the contents of the pending-terms table to disk.
   130494 */
   130495 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
   130496   int rc = SQLITE_OK;
   130497   UNUSED_PARAMETER(iSavepoint);
   130498   assert( ((Fts3Table *)pVtab)->inTransaction );
   130499   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
   130500   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
   130501   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
   130502     rc = fts3SyncMethod(pVtab);
   130503   }
   130504   return rc;
   130505 }
   130506 
   130507 /*
   130508 ** The xRelease() method.
   130509 **
   130510 ** This is a no-op.
   130511 */
   130512 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
   130513   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   130514   UNUSED_PARAMETER(iSavepoint);
   130515   UNUSED_PARAMETER(pVtab);
   130516   assert( p->inTransaction );
   130517   assert( p->mxSavepoint >= iSavepoint );
   130518   TESTONLY( p->mxSavepoint = iSavepoint-1 );
   130519   return SQLITE_OK;
   130520 }
   130521 
   130522 /*
   130523 ** The xRollbackTo() method.
   130524 **
   130525 ** Discard the contents of the pending terms table.
   130526 */
   130527 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
   130528   Fts3Table *p = (Fts3Table*)pVtab;
   130529   UNUSED_PARAMETER(iSavepoint);
   130530   assert( p->inTransaction );
   130531   assert( p->mxSavepoint >= iSavepoint );
   130532   TESTONLY( p->mxSavepoint = iSavepoint );
   130533   sqlite3Fts3PendingTermsClear(p);
   130534   return SQLITE_OK;
   130535 }
   130536 
   130537 static const sqlite3_module fts3Module = {
   130538   /* iVersion      */ 2,
   130539   /* xCreate       */ fts3CreateMethod,
   130540   /* xConnect      */ fts3ConnectMethod,
   130541   /* xBestIndex    */ fts3BestIndexMethod,
   130542   /* xDisconnect   */ fts3DisconnectMethod,
   130543   /* xDestroy      */ fts3DestroyMethod,
   130544   /* xOpen         */ fts3OpenMethod,
   130545   /* xClose        */ fts3CloseMethod,
   130546   /* xFilter       */ fts3FilterMethod,
   130547   /* xNext         */ fts3NextMethod,
   130548   /* xEof          */ fts3EofMethod,
   130549   /* xColumn       */ fts3ColumnMethod,
   130550   /* xRowid        */ fts3RowidMethod,
   130551   /* xUpdate       */ fts3UpdateMethod,
   130552   /* xBegin        */ fts3BeginMethod,
   130553   /* xSync         */ fts3SyncMethod,
   130554   /* xCommit       */ fts3CommitMethod,
   130555   /* xRollback     */ fts3RollbackMethod,
   130556   /* xFindFunction */ fts3FindFunctionMethod,
   130557   /* xRename */       fts3RenameMethod,
   130558   /* xSavepoint    */ fts3SavepointMethod,
   130559   /* xRelease      */ fts3ReleaseMethod,
   130560   /* xRollbackTo   */ fts3RollbackToMethod,
   130561 };
   130562 
   130563 /*
   130564 ** This function is registered as the module destructor (called when an
   130565 ** FTS3 enabled database connection is closed). It frees the memory
   130566 ** allocated for the tokenizer hash table.
   130567 */
   130568 static void hashDestroy(void *p){
   130569   Fts3Hash *pHash = (Fts3Hash *)p;
   130570   sqlite3Fts3HashClear(pHash);
   130571   sqlite3_free(pHash);
   130572 }
   130573 
   130574 /*
   130575 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
   130576 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
   130577 ** respectively. The following three forward declarations are for functions
   130578 ** declared in these files used to retrieve the respective implementations.
   130579 **
   130580 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
   130581 ** to by the argument to point to the "simple" tokenizer implementation.
   130582 ** And so on.
   130583 */
   130584 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   130585 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   130586 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   130587 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
   130588 #endif
   130589 #ifdef SQLITE_ENABLE_ICU
   130590 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   130591 #endif
   130592 
   130593 /*
   130594 ** Initialize the fts3 extension. If this extension is built as part
   130595 ** of the sqlite library, then this function is called directly by
   130596 ** SQLite. If fts3 is built as a dynamically loadable extension, this
   130597 ** function is called by the sqlite3_extension_init() entry point.
   130598 */
   130599 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   130600   int rc = SQLITE_OK;
   130601   Fts3Hash *pHash = 0;
   130602   const sqlite3_tokenizer_module *pSimple = 0;
   130603   const sqlite3_tokenizer_module *pPorter = 0;
   130604 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   130605   const sqlite3_tokenizer_module *pUnicode = 0;
   130606 #endif
   130607 
   130608 #ifdef SQLITE_ENABLE_ICU
   130609   const sqlite3_tokenizer_module *pIcu = 0;
   130610   sqlite3Fts3IcuTokenizerModule(&pIcu);
   130611 #endif
   130612 
   130613 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   130614   sqlite3Fts3UnicodeTokenizer(&pUnicode);
   130615 #endif
   130616 
   130617 #ifdef SQLITE_TEST
   130618   rc = sqlite3Fts3InitTerm(db);
   130619   if( rc!=SQLITE_OK ) return rc;
   130620 #endif
   130621 
   130622   rc = sqlite3Fts3InitAux(db);
   130623   if( rc!=SQLITE_OK ) return rc;
   130624 
   130625   sqlite3Fts3SimpleTokenizerModule(&pSimple);
   130626   sqlite3Fts3PorterTokenizerModule(&pPorter);
   130627 
   130628   /* Allocate and initialize the hash-table used to store tokenizers. */
   130629   pHash = sqlite3_malloc(sizeof(Fts3Hash));
   130630   if( !pHash ){
   130631     rc = SQLITE_NOMEM;
   130632   }else{
   130633     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   130634   }
   130635 
   130636   /* Load the built-in tokenizers into the hash table */
   130637   if( rc==SQLITE_OK ){
   130638     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
   130639      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
   130640 
   130641 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   130642      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
   130643 #endif
   130644 #ifdef SQLITE_ENABLE_ICU
   130645      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
   130646 #endif
   130647     ){
   130648       rc = SQLITE_NOMEM;
   130649     }
   130650   }
   130651 
   130652 #ifdef SQLITE_TEST
   130653   if( rc==SQLITE_OK ){
   130654     rc = sqlite3Fts3ExprInitTestInterface(db);
   130655   }
   130656 #endif
   130657 
   130658   /* Create the virtual table wrapper around the hash-table and overload
   130659   ** the two scalar functions. If this is successful, register the
   130660   ** module with sqlite.
   130661   */
   130662   if( SQLITE_OK==rc
   130663    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
   130664    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   130665    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
   130666    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
   130667    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
   130668    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
   130669   ){
   130670     rc = sqlite3_create_module_v2(
   130671         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
   130672     );
   130673     if( rc==SQLITE_OK ){
   130674       rc = sqlite3_create_module_v2(
   130675           db, "fts4", &fts3Module, (void *)pHash, 0
   130676       );
   130677     }
   130678     if( rc==SQLITE_OK ){
   130679       rc = sqlite3Fts3InitTok(db, (void *)pHash);
   130680     }
   130681     return rc;
   130682   }
   130683 
   130684 
   130685   /* An error has occurred. Delete the hash table and return the error code. */
   130686   assert( rc!=SQLITE_OK );
   130687   if( pHash ){
   130688     sqlite3Fts3HashClear(pHash);
   130689     sqlite3_free(pHash);
   130690   }
   130691   return rc;
   130692 }
   130693 
   130694 /*
   130695 ** Allocate an Fts3MultiSegReader for each token in the expression headed
   130696 ** by pExpr.
   130697 **
   130698 ** An Fts3SegReader object is a cursor that can seek or scan a range of
   130699 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
   130700 ** Fts3SegReader objects internally to provide an interface to seek or scan
   130701 ** within the union of all segments of a b-tree. Hence the name.
   130702 **
   130703 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
   130704 ** segment b-tree (if the term is not a prefix or it is a prefix for which
   130705 ** there exists prefix b-tree of the right length) then it may be traversed
   130706 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
   130707 ** doclist and then traversed.
   130708 */
   130709 static void fts3EvalAllocateReaders(
   130710   Fts3Cursor *pCsr,               /* FTS cursor handle */
   130711   Fts3Expr *pExpr,                /* Allocate readers for this expression */
   130712   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
   130713   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
   130714   int *pRc                        /* IN/OUT: Error code */
   130715 ){
   130716   if( pExpr && SQLITE_OK==*pRc ){
   130717     if( pExpr->eType==FTSQUERY_PHRASE ){
   130718       int i;
   130719       int nToken = pExpr->pPhrase->nToken;
   130720       *pnToken += nToken;
   130721       for(i=0; i<nToken; i++){
   130722         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
   130723         int rc = fts3TermSegReaderCursor(pCsr,
   130724             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
   130725         );
   130726         if( rc!=SQLITE_OK ){
   130727           *pRc = rc;
   130728           return;
   130729         }
   130730       }
   130731       assert( pExpr->pPhrase->iDoclistToken==0 );
   130732       pExpr->pPhrase->iDoclistToken = -1;
   130733     }else{
   130734       *pnOr += (pExpr->eType==FTSQUERY_OR);
   130735       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
   130736       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
   130737     }
   130738   }
   130739 }
   130740 
   130741 /*
   130742 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
   130743 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
   130744 **
   130745 ** This function assumes that pList points to a buffer allocated using
   130746 ** sqlite3_malloc(). This function takes responsibility for eventually
   130747 ** freeing the buffer.
   130748 */
   130749 static void fts3EvalPhraseMergeToken(
   130750   Fts3Table *pTab,                /* FTS Table pointer */
   130751   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
   130752   int iToken,                     /* Token pList/nList corresponds to */
   130753   char *pList,                    /* Pointer to doclist */
   130754   int nList                       /* Number of bytes in pList */
   130755 ){
   130756   assert( iToken!=p->iDoclistToken );
   130757 
   130758   if( pList==0 ){
   130759     sqlite3_free(p->doclist.aAll);
   130760     p->doclist.aAll = 0;
   130761     p->doclist.nAll = 0;
   130762   }
   130763 
   130764   else if( p->iDoclistToken<0 ){
   130765     p->doclist.aAll = pList;
   130766     p->doclist.nAll = nList;
   130767   }
   130768 
   130769   else if( p->doclist.aAll==0 ){
   130770     sqlite3_free(pList);
   130771   }
   130772 
   130773   else {
   130774     char *pLeft;
   130775     char *pRight;
   130776     int nLeft;
   130777     int nRight;
   130778     int nDiff;
   130779 
   130780     if( p->iDoclistToken<iToken ){
   130781       pLeft = p->doclist.aAll;
   130782       nLeft = p->doclist.nAll;
   130783       pRight = pList;
   130784       nRight = nList;
   130785       nDiff = iToken - p->iDoclistToken;
   130786     }else{
   130787       pRight = p->doclist.aAll;
   130788       nRight = p->doclist.nAll;
   130789       pLeft = pList;
   130790       nLeft = nList;
   130791       nDiff = p->iDoclistToken - iToken;
   130792     }
   130793 
   130794     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
   130795     sqlite3_free(pLeft);
   130796     p->doclist.aAll = pRight;
   130797     p->doclist.nAll = nRight;
   130798   }
   130799 
   130800   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
   130801 }
   130802 
   130803 /*
   130804 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
   130805 ** does not take deferred tokens into account.
   130806 **
   130807 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   130808 */
   130809 static int fts3EvalPhraseLoad(
   130810   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   130811   Fts3Phrase *p                   /* Phrase object */
   130812 ){
   130813   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   130814   int iToken;
   130815   int rc = SQLITE_OK;
   130816 
   130817   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
   130818     Fts3PhraseToken *pToken = &p->aToken[iToken];
   130819     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
   130820 
   130821     if( pToken->pSegcsr ){
   130822       int nThis = 0;
   130823       char *pThis = 0;
   130824       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
   130825       if( rc==SQLITE_OK ){
   130826         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
   130827       }
   130828     }
   130829     assert( pToken->pSegcsr==0 );
   130830   }
   130831 
   130832   return rc;
   130833 }
   130834 
   130835 /*
   130836 ** This function is called on each phrase after the position lists for
   130837 ** any deferred tokens have been loaded into memory. It updates the phrases
   130838 ** current position list to include only those positions that are really
   130839 ** instances of the phrase (after considering deferred tokens). If this
   130840 ** means that the phrase does not appear in the current row, doclist.pList
   130841 ** and doclist.nList are both zeroed.
   130842 **
   130843 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   130844 */
   130845 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
   130846   int iToken;                     /* Used to iterate through phrase tokens */
   130847   char *aPoslist = 0;             /* Position list for deferred tokens */
   130848   int nPoslist = 0;               /* Number of bytes in aPoslist */
   130849   int iPrev = -1;                 /* Token number of previous deferred token */
   130850 
   130851   assert( pPhrase->doclist.bFreeList==0 );
   130852 
   130853   for(iToken=0; iToken<pPhrase->nToken; iToken++){
   130854     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
   130855     Fts3DeferredToken *pDeferred = pToken->pDeferred;
   130856 
   130857     if( pDeferred ){
   130858       char *pList;
   130859       int nList;
   130860       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
   130861       if( rc!=SQLITE_OK ) return rc;
   130862 
   130863       if( pList==0 ){
   130864         sqlite3_free(aPoslist);
   130865         pPhrase->doclist.pList = 0;
   130866         pPhrase->doclist.nList = 0;
   130867         return SQLITE_OK;
   130868 
   130869       }else if( aPoslist==0 ){
   130870         aPoslist = pList;
   130871         nPoslist = nList;
   130872 
   130873       }else{
   130874         char *aOut = pList;
   130875         char *p1 = aPoslist;
   130876         char *p2 = aOut;
   130877 
   130878         assert( iPrev>=0 );
   130879         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
   130880         sqlite3_free(aPoslist);
   130881         aPoslist = pList;
   130882         nPoslist = (int)(aOut - aPoslist);
   130883         if( nPoslist==0 ){
   130884           sqlite3_free(aPoslist);
   130885           pPhrase->doclist.pList = 0;
   130886           pPhrase->doclist.nList = 0;
   130887           return SQLITE_OK;
   130888         }
   130889       }
   130890       iPrev = iToken;
   130891     }
   130892   }
   130893 
   130894   if( iPrev>=0 ){
   130895     int nMaxUndeferred = pPhrase->iDoclistToken;
   130896     if( nMaxUndeferred<0 ){
   130897       pPhrase->doclist.pList = aPoslist;
   130898       pPhrase->doclist.nList = nPoslist;
   130899       pPhrase->doclist.iDocid = pCsr->iPrevId;
   130900       pPhrase->doclist.bFreeList = 1;
   130901     }else{
   130902       int nDistance;
   130903       char *p1;
   130904       char *p2;
   130905       char *aOut;
   130906 
   130907       if( nMaxUndeferred>iPrev ){
   130908         p1 = aPoslist;
   130909         p2 = pPhrase->doclist.pList;
   130910         nDistance = nMaxUndeferred - iPrev;
   130911       }else{
   130912         p1 = pPhrase->doclist.pList;
   130913         p2 = aPoslist;
   130914         nDistance = iPrev - nMaxUndeferred;
   130915       }
   130916 
   130917       aOut = (char *)sqlite3_malloc(nPoslist+8);
   130918       if( !aOut ){
   130919         sqlite3_free(aPoslist);
   130920         return SQLITE_NOMEM;
   130921       }
   130922 
   130923       pPhrase->doclist.pList = aOut;
   130924       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
   130925         pPhrase->doclist.bFreeList = 1;
   130926         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
   130927       }else{
   130928         sqlite3_free(aOut);
   130929         pPhrase->doclist.pList = 0;
   130930         pPhrase->doclist.nList = 0;
   130931       }
   130932       sqlite3_free(aPoslist);
   130933     }
   130934   }
   130935 
   130936   return SQLITE_OK;
   130937 }
   130938 
   130939 /*
   130940 ** Maximum number of tokens a phrase may have to be considered for the
   130941 ** incremental doclists strategy.
   130942 */
   130943 #define MAX_INCR_PHRASE_TOKENS 4
   130944 
   130945 /*
   130946 ** This function is called for each Fts3Phrase in a full-text query
   130947 ** expression to initialize the mechanism for returning rows. Once this
   130948 ** function has been called successfully on an Fts3Phrase, it may be
   130949 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
   130950 **
   130951 ** If parameter bOptOk is true, then the phrase may (or may not) use the
   130952 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
   130953 ** memory within this call.
   130954 **
   130955 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   130956 */
   130957 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
   130958   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   130959   int rc = SQLITE_OK;             /* Error code */
   130960   int i;
   130961 
   130962   /* Determine if doclists may be loaded from disk incrementally. This is
   130963   ** possible if the bOptOk argument is true, the FTS doclists will be
   130964   ** scanned in forward order, and the phrase consists of
   130965   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
   130966   ** tokens or prefix tokens that cannot use a prefix-index.  */
   130967   int bHaveIncr = 0;
   130968   int bIncrOk = (bOptOk
   130969    && pCsr->bDesc==pTab->bDescIdx
   130970    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
   130971    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
   130972 #ifdef SQLITE_TEST
   130973    && pTab->bNoIncrDoclist==0
   130974 #endif
   130975   );
   130976   for(i=0; bIncrOk==1 && i<p->nToken; i++){
   130977     Fts3PhraseToken *pToken = &p->aToken[i];
   130978     if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
   130979       bIncrOk = 0;
   130980     }
   130981     if( pToken->pSegcsr ) bHaveIncr = 1;
   130982   }
   130983 
   130984   if( bIncrOk && bHaveIncr ){
   130985     /* Use the incremental approach. */
   130986     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
   130987     for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
   130988       Fts3PhraseToken *pToken = &p->aToken[i];
   130989       Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
   130990       if( pSegcsr ){
   130991         rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
   130992       }
   130993     }
   130994     p->bIncr = 1;
   130995   }else{
   130996     /* Load the full doclist for the phrase into memory. */
   130997     rc = fts3EvalPhraseLoad(pCsr, p);
   130998     p->bIncr = 0;
   130999   }
   131000 
   131001   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
   131002   return rc;
   131003 }
   131004 
   131005 /*
   131006 ** This function is used to iterate backwards (from the end to start)
   131007 ** through doclists. It is used by this module to iterate through phrase
   131008 ** doclists in reverse and by the fts3_write.c module to iterate through
   131009 ** pending-terms lists when writing to databases with "order=desc".
   131010 **
   131011 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
   131012 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
   131013 ** function iterates from the end of the doclist to the beginning.
   131014 */
   131015 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
   131016   int bDescIdx,                   /* True if the doclist is desc */
   131017   char *aDoclist,                 /* Pointer to entire doclist */
   131018   int nDoclist,                   /* Length of aDoclist in bytes */
   131019   char **ppIter,                  /* IN/OUT: Iterator pointer */
   131020   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
   131021   int *pnList,                    /* OUT: List length pointer */
   131022   u8 *pbEof                       /* OUT: End-of-file flag */
   131023 ){
   131024   char *p = *ppIter;
   131025 
   131026   assert( nDoclist>0 );
   131027   assert( *pbEof==0 );
   131028   assert( p || *piDocid==0 );
   131029   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
   131030 
   131031   if( p==0 ){
   131032     sqlite3_int64 iDocid = 0;
   131033     char *pNext = 0;
   131034     char *pDocid = aDoclist;
   131035     char *pEnd = &aDoclist[nDoclist];
   131036     int iMul = 1;
   131037 
   131038     while( pDocid<pEnd ){
   131039       sqlite3_int64 iDelta;
   131040       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
   131041       iDocid += (iMul * iDelta);
   131042       pNext = pDocid;
   131043       fts3PoslistCopy(0, &pDocid);
   131044       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
   131045       iMul = (bDescIdx ? -1 : 1);
   131046     }
   131047 
   131048     *pnList = (int)(pEnd - pNext);
   131049     *ppIter = pNext;
   131050     *piDocid = iDocid;
   131051   }else{
   131052     int iMul = (bDescIdx ? -1 : 1);
   131053     sqlite3_int64 iDelta;
   131054     fts3GetReverseVarint(&p, aDoclist, &iDelta);
   131055     *piDocid -= (iMul * iDelta);
   131056 
   131057     if( p==aDoclist ){
   131058       *pbEof = 1;
   131059     }else{
   131060       char *pSave = p;
   131061       fts3ReversePoslist(aDoclist, &p);
   131062       *pnList = (int)(pSave - p);
   131063     }
   131064     *ppIter = p;
   131065   }
   131066 }
   131067 
   131068 /*
   131069 ** Iterate forwards through a doclist.
   131070 */
   131071 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
   131072   int bDescIdx,                   /* True if the doclist is desc */
   131073   char *aDoclist,                 /* Pointer to entire doclist */
   131074   int nDoclist,                   /* Length of aDoclist in bytes */
   131075   char **ppIter,                  /* IN/OUT: Iterator pointer */
   131076   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
   131077   u8 *pbEof                       /* OUT: End-of-file flag */
   131078 ){
   131079   char *p = *ppIter;
   131080 
   131081   assert( nDoclist>0 );
   131082   assert( *pbEof==0 );
   131083   assert( p || *piDocid==0 );
   131084   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
   131085 
   131086   if( p==0 ){
   131087     p = aDoclist;
   131088     p += sqlite3Fts3GetVarint(p, piDocid);
   131089   }else{
   131090     fts3PoslistCopy(0, &p);
   131091     if( p>=&aDoclist[nDoclist] ){
   131092       *pbEof = 1;
   131093     }else{
   131094       sqlite3_int64 iVar;
   131095       p += sqlite3Fts3GetVarint(p, &iVar);
   131096       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
   131097     }
   131098   }
   131099 
   131100   *ppIter = p;
   131101 }
   131102 
   131103 /*
   131104 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
   131105 ** to true if EOF is reached.
   131106 */
   131107 static void fts3EvalDlPhraseNext(
   131108   Fts3Table *pTab,
   131109   Fts3Doclist *pDL,
   131110   u8 *pbEof
   131111 ){
   131112   char *pIter;                            /* Used to iterate through aAll */
   131113   char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
   131114 
   131115   if( pDL->pNextDocid ){
   131116     pIter = pDL->pNextDocid;
   131117   }else{
   131118     pIter = pDL->aAll;
   131119   }
   131120 
   131121   if( pIter>=pEnd ){
   131122     /* We have already reached the end of this doclist. EOF. */
   131123     *pbEof = 1;
   131124   }else{
   131125     sqlite3_int64 iDelta;
   131126     pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
   131127     if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
   131128       pDL->iDocid += iDelta;
   131129     }else{
   131130       pDL->iDocid -= iDelta;
   131131     }
   131132     pDL->pList = pIter;
   131133     fts3PoslistCopy(0, &pIter);
   131134     pDL->nList = (int)(pIter - pDL->pList);
   131135 
   131136     /* pIter now points just past the 0x00 that terminates the position-
   131137     ** list for document pDL->iDocid. However, if this position-list was
   131138     ** edited in place by fts3EvalNearTrim(), then pIter may not actually
   131139     ** point to the start of the next docid value. The following line deals
   131140     ** with this case by advancing pIter past the zero-padding added by
   131141     ** fts3EvalNearTrim().  */
   131142     while( pIter<pEnd && *pIter==0 ) pIter++;
   131143 
   131144     pDL->pNextDocid = pIter;
   131145     assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
   131146     *pbEof = 0;
   131147   }
   131148 }
   131149 
   131150 /*
   131151 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
   131152 */
   131153 typedef struct TokenDoclist TokenDoclist;
   131154 struct TokenDoclist {
   131155   int bIgnore;
   131156   sqlite3_int64 iDocid;
   131157   char *pList;
   131158   int nList;
   131159 };
   131160 
   131161 /*
   131162 ** Token pToken is an incrementally loaded token that is part of a
   131163 ** multi-token phrase. Advance it to the next matching document in the
   131164 ** database and populate output variable *p with the details of the new
   131165 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
   131166 **
   131167 ** If an error occurs, return an SQLite error code. Otherwise, return
   131168 ** SQLITE_OK.
   131169 */
   131170 static int incrPhraseTokenNext(
   131171   Fts3Table *pTab,                /* Virtual table handle */
   131172   Fts3Phrase *pPhrase,            /* Phrase to advance token of */
   131173   int iToken,                     /* Specific token to advance */
   131174   TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
   131175   u8 *pbEof                       /* OUT: True if iterator is at EOF */
   131176 ){
   131177   int rc = SQLITE_OK;
   131178 
   131179   if( pPhrase->iDoclistToken==iToken ){
   131180     assert( p->bIgnore==0 );
   131181     assert( pPhrase->aToken[iToken].pSegcsr==0 );
   131182     fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
   131183     p->pList = pPhrase->doclist.pList;
   131184     p->nList = pPhrase->doclist.nList;
   131185     p->iDocid = pPhrase->doclist.iDocid;
   131186   }else{
   131187     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
   131188     assert( pToken->pDeferred==0 );
   131189     assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
   131190     if( pToken->pSegcsr ){
   131191       assert( p->bIgnore==0 );
   131192       rc = sqlite3Fts3MsrIncrNext(
   131193           pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
   131194       );
   131195       if( p->pList==0 ) *pbEof = 1;
   131196     }else{
   131197       p->bIgnore = 1;
   131198     }
   131199   }
   131200 
   131201   return rc;
   131202 }
   131203 
   131204 
   131205 /*
   131206 ** The phrase iterator passed as the second argument:
   131207 **
   131208 **   * features at least one token that uses an incremental doclist, and
   131209 **
   131210 **   * does not contain any deferred tokens.
   131211 **
   131212 ** Advance it to the next matching documnent in the database and populate
   131213 ** the Fts3Doclist.pList and nList fields.
   131214 **
   131215 ** If there is no "next" entry and no error occurs, then *pbEof is set to
   131216 ** 1 before returning. Otherwise, if no error occurs and the iterator is
   131217 ** successfully advanced, *pbEof is set to 0.
   131218 **
   131219 ** If an error occurs, return an SQLite error code. Otherwise, return
   131220 ** SQLITE_OK.
   131221 */
   131222 static int fts3EvalIncrPhraseNext(
   131223   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131224   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
   131225   u8 *pbEof                       /* OUT: Set to 1 if EOF */
   131226 ){
   131227   int rc = SQLITE_OK;
   131228   Fts3Doclist *pDL = &p->doclist;
   131229   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   131230   u8 bEof = 0;
   131231 
   131232   /* This is only called if it is guaranteed that the phrase has at least
   131233   ** one incremental token. In which case the bIncr flag is set. */
   131234   assert( p->bIncr==1 );
   131235 
   131236   if( p->nToken==1 && p->bIncr ){
   131237     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
   131238         &pDL->iDocid, &pDL->pList, &pDL->nList
   131239     );
   131240     if( pDL->pList==0 ) bEof = 1;
   131241   }else{
   131242     int bDescDoclist = pCsr->bDesc;
   131243     struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
   131244 
   131245     memset(a, 0, sizeof(a));
   131246     assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
   131247     assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
   131248 
   131249     while( bEof==0 ){
   131250       int bMaxSet = 0;
   131251       sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
   131252       int i;                      /* Used to iterate through tokens */
   131253 
   131254       /* Advance the iterator for each token in the phrase once. */
   131255       for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
   131256         rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
   131257         if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
   131258           iMax = a[i].iDocid;
   131259           bMaxSet = 1;
   131260         }
   131261       }
   131262       assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
   131263       assert( rc!=SQLITE_OK || bMaxSet );
   131264 
   131265       /* Keep advancing iterators until they all point to the same document */
   131266       for(i=0; i<p->nToken; i++){
   131267         while( rc==SQLITE_OK && bEof==0
   131268             && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
   131269         ){
   131270           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
   131271           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
   131272             iMax = a[i].iDocid;
   131273             i = 0;
   131274           }
   131275         }
   131276       }
   131277 
   131278       /* Check if the current entries really are a phrase match */
   131279       if( bEof==0 ){
   131280         int nList = 0;
   131281         int nByte = a[p->nToken-1].nList;
   131282         char *aDoclist = sqlite3_malloc(nByte+1);
   131283         if( !aDoclist ) return SQLITE_NOMEM;
   131284         memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
   131285 
   131286         for(i=0; i<(p->nToken-1); i++){
   131287           if( a[i].bIgnore==0 ){
   131288             char *pL = a[i].pList;
   131289             char *pR = aDoclist;
   131290             char *pOut = aDoclist;
   131291             int nDist = p->nToken-1-i;
   131292             int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
   131293             if( res==0 ) break;
   131294             nList = (int)(pOut - aDoclist);
   131295           }
   131296         }
   131297         if( i==(p->nToken-1) ){
   131298           pDL->iDocid = iMax;
   131299           pDL->pList = aDoclist;
   131300           pDL->nList = nList;
   131301           pDL->bFreeList = 1;
   131302           break;
   131303         }
   131304         sqlite3_free(aDoclist);
   131305       }
   131306     }
   131307   }
   131308 
   131309   *pbEof = bEof;
   131310   return rc;
   131311 }
   131312 
   131313 /*
   131314 ** Attempt to move the phrase iterator to point to the next matching docid.
   131315 ** If an error occurs, return an SQLite error code. Otherwise, return
   131316 ** SQLITE_OK.
   131317 **
   131318 ** If there is no "next" entry and no error occurs, then *pbEof is set to
   131319 ** 1 before returning. Otherwise, if no error occurs and the iterator is
   131320 ** successfully advanced, *pbEof is set to 0.
   131321 */
   131322 static int fts3EvalPhraseNext(
   131323   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131324   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
   131325   u8 *pbEof                       /* OUT: Set to 1 if EOF */
   131326 ){
   131327   int rc = SQLITE_OK;
   131328   Fts3Doclist *pDL = &p->doclist;
   131329   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   131330 
   131331   if( p->bIncr ){
   131332     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
   131333   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
   131334     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
   131335         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
   131336     );
   131337     pDL->pList = pDL->pNextDocid;
   131338   }else{
   131339     fts3EvalDlPhraseNext(pTab, pDL, pbEof);
   131340   }
   131341 
   131342   return rc;
   131343 }
   131344 
   131345 /*
   131346 **
   131347 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   131348 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
   131349 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
   131350 ** expressions for which all descendent tokens are deferred.
   131351 **
   131352 ** If parameter bOptOk is zero, then it is guaranteed that the
   131353 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
   131354 ** each phrase in the expression (subject to deferred token processing).
   131355 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
   131356 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
   131357 **
   131358 ** If an error occurs within this function, *pRc is set to an SQLite error
   131359 ** code before returning.
   131360 */
   131361 static void fts3EvalStartReaders(
   131362   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131363   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
   131364   int *pRc                        /* IN/OUT: Error code */
   131365 ){
   131366   if( pExpr && SQLITE_OK==*pRc ){
   131367     if( pExpr->eType==FTSQUERY_PHRASE ){
   131368       int i;
   131369       int nToken = pExpr->pPhrase->nToken;
   131370       for(i=0; i<nToken; i++){
   131371         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
   131372       }
   131373       pExpr->bDeferred = (i==nToken);
   131374       *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
   131375     }else{
   131376       fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
   131377       fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
   131378       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
   131379     }
   131380   }
   131381 }
   131382 
   131383 /*
   131384 ** An array of the following structures is assembled as part of the process
   131385 ** of selecting tokens to defer before the query starts executing (as part
   131386 ** of the xFilter() method). There is one element in the array for each
   131387 ** token in the FTS expression.
   131388 **
   131389 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
   131390 ** to phrases that are connected only by AND and NEAR operators (not OR or
   131391 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
   131392 ** separately. The root of a tokens AND/NEAR cluster is stored in
   131393 ** Fts3TokenAndCost.pRoot.
   131394 */
   131395 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
   131396 struct Fts3TokenAndCost {
   131397   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
   131398   int iToken;                     /* Position of token in phrase */
   131399   Fts3PhraseToken *pToken;        /* The token itself */
   131400   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
   131401   int nOvfl;                      /* Number of overflow pages to load doclist */
   131402   int iCol;                       /* The column the token must match */
   131403 };
   131404 
   131405 /*
   131406 ** This function is used to populate an allocated Fts3TokenAndCost array.
   131407 **
   131408 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   131409 ** Otherwise, if an error occurs during execution, *pRc is set to an
   131410 ** SQLite error code.
   131411 */
   131412 static void fts3EvalTokenCosts(
   131413   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131414   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
   131415   Fts3Expr *pExpr,                /* Expression to consider */
   131416   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
   131417   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
   131418   int *pRc                        /* IN/OUT: Error code */
   131419 ){
   131420   if( *pRc==SQLITE_OK ){
   131421     if( pExpr->eType==FTSQUERY_PHRASE ){
   131422       Fts3Phrase *pPhrase = pExpr->pPhrase;
   131423       int i;
   131424       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
   131425         Fts3TokenAndCost *pTC = (*ppTC)++;
   131426         pTC->pPhrase = pPhrase;
   131427         pTC->iToken = i;
   131428         pTC->pRoot = pRoot;
   131429         pTC->pToken = &pPhrase->aToken[i];
   131430         pTC->iCol = pPhrase->iColumn;
   131431         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
   131432       }
   131433     }else if( pExpr->eType!=FTSQUERY_NOT ){
   131434       assert( pExpr->eType==FTSQUERY_OR
   131435            || pExpr->eType==FTSQUERY_AND
   131436            || pExpr->eType==FTSQUERY_NEAR
   131437       );
   131438       assert( pExpr->pLeft && pExpr->pRight );
   131439       if( pExpr->eType==FTSQUERY_OR ){
   131440         pRoot = pExpr->pLeft;
   131441         **ppOr = pRoot;
   131442         (*ppOr)++;
   131443       }
   131444       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
   131445       if( pExpr->eType==FTSQUERY_OR ){
   131446         pRoot = pExpr->pRight;
   131447         **ppOr = pRoot;
   131448         (*ppOr)++;
   131449       }
   131450       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
   131451     }
   131452   }
   131453 }
   131454 
   131455 /*
   131456 ** Determine the average document (row) size in pages. If successful,
   131457 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
   131458 ** an SQLite error code.
   131459 **
   131460 ** The average document size in pages is calculated by first calculating
   131461 ** determining the average size in bytes, B. If B is less than the amount
   131462 ** of data that will fit on a single leaf page of an intkey table in
   131463 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
   131464 ** the number of overflow pages consumed by a record B bytes in size.
   131465 */
   131466 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
   131467   if( pCsr->nRowAvg==0 ){
   131468     /* The average document size, which is required to calculate the cost
   131469     ** of each doclist, has not yet been determined. Read the required
   131470     ** data from the %_stat table to calculate it.
   131471     **
   131472     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
   131473     ** varints, where nCol is the number of columns in the FTS3 table.
   131474     ** The first varint is the number of documents currently stored in
   131475     ** the table. The following nCol varints contain the total amount of
   131476     ** data stored in all rows of each column of the table, from left
   131477     ** to right.
   131478     */
   131479     int rc;
   131480     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   131481     sqlite3_stmt *pStmt;
   131482     sqlite3_int64 nDoc = 0;
   131483     sqlite3_int64 nByte = 0;
   131484     const char *pEnd;
   131485     const char *a;
   131486 
   131487     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
   131488     if( rc!=SQLITE_OK ) return rc;
   131489     a = sqlite3_column_blob(pStmt, 0);
   131490     assert( a );
   131491 
   131492     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
   131493     a += sqlite3Fts3GetVarint(a, &nDoc);
   131494     while( a<pEnd ){
   131495       a += sqlite3Fts3GetVarint(a, &nByte);
   131496     }
   131497     if( nDoc==0 || nByte==0 ){
   131498       sqlite3_reset(pStmt);
   131499       return FTS_CORRUPT_VTAB;
   131500     }
   131501 
   131502     pCsr->nDoc = nDoc;
   131503     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
   131504     assert( pCsr->nRowAvg>0 );
   131505     rc = sqlite3_reset(pStmt);
   131506     if( rc!=SQLITE_OK ) return rc;
   131507   }
   131508 
   131509   *pnPage = pCsr->nRowAvg;
   131510   return SQLITE_OK;
   131511 }
   131512 
   131513 /*
   131514 ** This function is called to select the tokens (if any) that will be
   131515 ** deferred. The array aTC[] has already been populated when this is
   131516 ** called.
   131517 **
   131518 ** This function is called once for each AND/NEAR cluster in the
   131519 ** expression. Each invocation determines which tokens to defer within
   131520 ** the cluster with root node pRoot. See comments above the definition
   131521 ** of struct Fts3TokenAndCost for more details.
   131522 **
   131523 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
   131524 ** called on each token to defer. Otherwise, an SQLite error code is
   131525 ** returned.
   131526 */
   131527 static int fts3EvalSelectDeferred(
   131528   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131529   Fts3Expr *pRoot,                /* Consider tokens with this root node */
   131530   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
   131531   int nTC                         /* Number of entries in aTC[] */
   131532 ){
   131533   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   131534   int nDocSize = 0;               /* Number of pages per doc loaded */
   131535   int rc = SQLITE_OK;             /* Return code */
   131536   int ii;                         /* Iterator variable for various purposes */
   131537   int nOvfl = 0;                  /* Total overflow pages used by doclists */
   131538   int nToken = 0;                 /* Total number of tokens in cluster */
   131539 
   131540   int nMinEst = 0;                /* The minimum count for any phrase so far. */
   131541   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
   131542 
   131543   /* Tokens are never deferred for FTS tables created using the content=xxx
   131544   ** option. The reason being that it is not guaranteed that the content
   131545   ** table actually contains the same data as the index. To prevent this from
   131546   ** causing any problems, the deferred token optimization is completely
   131547   ** disabled for content=xxx tables. */
   131548   if( pTab->zContentTbl ){
   131549     return SQLITE_OK;
   131550   }
   131551 
   131552   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
   131553   ** associated with the tokens spill onto overflow pages, or if there is
   131554   ** only 1 token, exit early. No tokens to defer in this case. */
   131555   for(ii=0; ii<nTC; ii++){
   131556     if( aTC[ii].pRoot==pRoot ){
   131557       nOvfl += aTC[ii].nOvfl;
   131558       nToken++;
   131559     }
   131560   }
   131561   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
   131562 
   131563   /* Obtain the average docsize (in pages). */
   131564   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
   131565   assert( rc!=SQLITE_OK || nDocSize>0 );
   131566 
   131567 
   131568   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
   131569   ** of the number of overflow pages that will be loaded by the pager layer
   131570   ** to retrieve the entire doclist for the token from the full-text index.
   131571   ** Load the doclists for tokens that are either:
   131572   **
   131573   **   a. The cheapest token in the entire query (i.e. the one visited by the
   131574   **      first iteration of this loop), or
   131575   **
   131576   **   b. Part of a multi-token phrase.
   131577   **
   131578   ** After each token doclist is loaded, merge it with the others from the
   131579   ** same phrase and count the number of documents that the merged doclist
   131580   ** contains. Set variable "nMinEst" to the smallest number of documents in
   131581   ** any phrase doclist for which 1 or more token doclists have been loaded.
   131582   ** Let nOther be the number of other phrases for which it is certain that
   131583   ** one or more tokens will not be deferred.
   131584   **
   131585   ** Then, for each token, defer it if loading the doclist would result in
   131586   ** loading N or more overflow pages into memory, where N is computed as:
   131587   **
   131588   **    (nMinEst + 4^nOther - 1) / (4^nOther)
   131589   */
   131590   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
   131591     int iTC;                      /* Used to iterate through aTC[] array. */
   131592     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
   131593 
   131594     /* Set pTC to point to the cheapest remaining token. */
   131595     for(iTC=0; iTC<nTC; iTC++){
   131596       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
   131597        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
   131598       ){
   131599         pTC = &aTC[iTC];
   131600       }
   131601     }
   131602     assert( pTC );
   131603 
   131604     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
   131605       /* The number of overflow pages to load for this (and therefore all
   131606       ** subsequent) tokens is greater than the estimated number of pages
   131607       ** that will be loaded if all subsequent tokens are deferred.
   131608       */
   131609       Fts3PhraseToken *pToken = pTC->pToken;
   131610       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
   131611       fts3SegReaderCursorFree(pToken->pSegcsr);
   131612       pToken->pSegcsr = 0;
   131613     }else{
   131614       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
   131615       ** for-loop. Except, limit the value to 2^24 to prevent it from
   131616       ** overflowing the 32-bit integer it is stored in. */
   131617       if( ii<12 ) nLoad4 = nLoad4*4;
   131618 
   131619       if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
   131620         /* Either this is the cheapest token in the entire query, or it is
   131621         ** part of a multi-token phrase. Either way, the entire doclist will
   131622         ** (eventually) be loaded into memory. It may as well be now. */
   131623         Fts3PhraseToken *pToken = pTC->pToken;
   131624         int nList = 0;
   131625         char *pList = 0;
   131626         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
   131627         assert( rc==SQLITE_OK || pList==0 );
   131628         if( rc==SQLITE_OK ){
   131629           int nCount;
   131630           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
   131631           nCount = fts3DoclistCountDocids(
   131632               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
   131633           );
   131634           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
   131635         }
   131636       }
   131637     }
   131638     pTC->pToken = 0;
   131639   }
   131640 
   131641   return rc;
   131642 }
   131643 
   131644 /*
   131645 ** This function is called from within the xFilter method. It initializes
   131646 ** the full-text query currently stored in pCsr->pExpr. To iterate through
   131647 ** the results of a query, the caller does:
   131648 **
   131649 **    fts3EvalStart(pCsr);
   131650 **    while( 1 ){
   131651 **      fts3EvalNext(pCsr);
   131652 **      if( pCsr->bEof ) break;
   131653 **      ... return row pCsr->iPrevId to the caller ...
   131654 **    }
   131655 */
   131656 static int fts3EvalStart(Fts3Cursor *pCsr){
   131657   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   131658   int rc = SQLITE_OK;
   131659   int nToken = 0;
   131660   int nOr = 0;
   131661 
   131662   /* Allocate a MultiSegReader for each token in the expression. */
   131663   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
   131664 
   131665   /* Determine which, if any, tokens in the expression should be deferred. */
   131666 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   131667   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
   131668     Fts3TokenAndCost *aTC;
   131669     Fts3Expr **apOr;
   131670     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
   131671         sizeof(Fts3TokenAndCost) * nToken
   131672       + sizeof(Fts3Expr *) * nOr * 2
   131673     );
   131674     apOr = (Fts3Expr **)&aTC[nToken];
   131675 
   131676     if( !aTC ){
   131677       rc = SQLITE_NOMEM;
   131678     }else{
   131679       int ii;
   131680       Fts3TokenAndCost *pTC = aTC;
   131681       Fts3Expr **ppOr = apOr;
   131682 
   131683       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
   131684       nToken = (int)(pTC-aTC);
   131685       nOr = (int)(ppOr-apOr);
   131686 
   131687       if( rc==SQLITE_OK ){
   131688         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
   131689         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
   131690           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
   131691         }
   131692       }
   131693 
   131694       sqlite3_free(aTC);
   131695     }
   131696   }
   131697 #endif
   131698 
   131699   fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
   131700   return rc;
   131701 }
   131702 
   131703 /*
   131704 ** Invalidate the current position list for phrase pPhrase.
   131705 */
   131706 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
   131707   if( pPhrase->doclist.bFreeList ){
   131708     sqlite3_free(pPhrase->doclist.pList);
   131709   }
   131710   pPhrase->doclist.pList = 0;
   131711   pPhrase->doclist.nList = 0;
   131712   pPhrase->doclist.bFreeList = 0;
   131713 }
   131714 
   131715 /*
   131716 ** This function is called to edit the position list associated with
   131717 ** the phrase object passed as the fifth argument according to a NEAR
   131718 ** condition. For example:
   131719 **
   131720 **     abc NEAR/5 "def ghi"
   131721 **
   131722 ** Parameter nNear is passed the NEAR distance of the expression (5 in
   131723 ** the example above). When this function is called, *paPoslist points to
   131724 ** the position list, and *pnToken is the number of phrase tokens in, the
   131725 ** phrase on the other side of the NEAR operator to pPhrase. For example,
   131726 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
   131727 ** the position list associated with phrase "abc".
   131728 **
   131729 ** All positions in the pPhrase position list that are not sufficiently
   131730 ** close to a position in the *paPoslist position list are removed. If this
   131731 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
   131732 **
   131733 ** Before returning, *paPoslist is set to point to the position lsit
   131734 ** associated with pPhrase. And *pnToken is set to the number of tokens in
   131735 ** pPhrase.
   131736 */
   131737 static int fts3EvalNearTrim(
   131738   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
   131739   char *aTmp,                     /* Temporary space to use */
   131740   char **paPoslist,               /* IN/OUT: Position list */
   131741   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
   131742   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
   131743 ){
   131744   int nParam1 = nNear + pPhrase->nToken;
   131745   int nParam2 = nNear + *pnToken;
   131746   int nNew;
   131747   char *p2;
   131748   char *pOut;
   131749   int res;
   131750 
   131751   assert( pPhrase->doclist.pList );
   131752 
   131753   p2 = pOut = pPhrase->doclist.pList;
   131754   res = fts3PoslistNearMerge(
   131755     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
   131756   );
   131757   if( res ){
   131758     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
   131759     assert( pPhrase->doclist.pList[nNew]=='\0' );
   131760     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
   131761     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
   131762     pPhrase->doclist.nList = nNew;
   131763     *paPoslist = pPhrase->doclist.pList;
   131764     *pnToken = pPhrase->nToken;
   131765   }
   131766 
   131767   return res;
   131768 }
   131769 
   131770 /*
   131771 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
   131772 ** Otherwise, it advances the expression passed as the second argument to
   131773 ** point to the next matching row in the database. Expressions iterate through
   131774 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
   131775 ** or descending if it is non-zero.
   131776 **
   131777 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
   131778 ** successful, the following variables in pExpr are set:
   131779 **
   131780 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
   131781 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
   131782 **
   131783 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
   131784 ** at EOF, then the following variables are populated with the position list
   131785 ** for the phrase for the visited row:
   131786 **
   131787 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
   131788 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
   131789 **
   131790 ** It says above that this function advances the expression to the next
   131791 ** matching row. This is usually true, but there are the following exceptions:
   131792 **
   131793 **   1. Deferred tokens are not taken into account. If a phrase consists
   131794 **      entirely of deferred tokens, it is assumed to match every row in
   131795 **      the db. In this case the position-list is not populated at all.
   131796 **
   131797 **      Or, if a phrase contains one or more deferred tokens and one or
   131798 **      more non-deferred tokens, then the expression is advanced to the
   131799 **      next possible match, considering only non-deferred tokens. In other
   131800 **      words, if the phrase is "A B C", and "B" is deferred, the expression
   131801 **      is advanced to the next row that contains an instance of "A * C",
   131802 **      where "*" may match any single token. The position list in this case
   131803 **      is populated as for "A * C" before returning.
   131804 **
   131805 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
   131806 **      advanced to point to the next row that matches "x AND y".
   131807 **
   131808 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
   131809 ** really a match, taking into account deferred tokens and NEAR operators.
   131810 */
   131811 static void fts3EvalNextRow(
   131812   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   131813   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
   131814   int *pRc                        /* IN/OUT: Error code */
   131815 ){
   131816   if( *pRc==SQLITE_OK ){
   131817     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
   131818     assert( pExpr->bEof==0 );
   131819     pExpr->bStart = 1;
   131820 
   131821     switch( pExpr->eType ){
   131822       case FTSQUERY_NEAR:
   131823       case FTSQUERY_AND: {
   131824         Fts3Expr *pLeft = pExpr->pLeft;
   131825         Fts3Expr *pRight = pExpr->pRight;
   131826         assert( !pLeft->bDeferred || !pRight->bDeferred );
   131827 
   131828         if( pLeft->bDeferred ){
   131829           /* LHS is entirely deferred. So we assume it matches every row.
   131830           ** Advance the RHS iterator to find the next row visited. */
   131831           fts3EvalNextRow(pCsr, pRight, pRc);
   131832           pExpr->iDocid = pRight->iDocid;
   131833           pExpr->bEof = pRight->bEof;
   131834         }else if( pRight->bDeferred ){
   131835           /* RHS is entirely deferred. So we assume it matches every row.
   131836           ** Advance the LHS iterator to find the next row visited. */
   131837           fts3EvalNextRow(pCsr, pLeft, pRc);
   131838           pExpr->iDocid = pLeft->iDocid;
   131839           pExpr->bEof = pLeft->bEof;
   131840         }else{
   131841           /* Neither the RHS or LHS are deferred. */
   131842           fts3EvalNextRow(pCsr, pLeft, pRc);
   131843           fts3EvalNextRow(pCsr, pRight, pRc);
   131844           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
   131845             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   131846             if( iDiff==0 ) break;
   131847             if( iDiff<0 ){
   131848               fts3EvalNextRow(pCsr, pLeft, pRc);
   131849             }else{
   131850               fts3EvalNextRow(pCsr, pRight, pRc);
   131851             }
   131852           }
   131853           pExpr->iDocid = pLeft->iDocid;
   131854           pExpr->bEof = (pLeft->bEof || pRight->bEof);
   131855         }
   131856         break;
   131857       }
   131858 
   131859       case FTSQUERY_OR: {
   131860         Fts3Expr *pLeft = pExpr->pLeft;
   131861         Fts3Expr *pRight = pExpr->pRight;
   131862         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   131863 
   131864         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
   131865         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
   131866 
   131867         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
   131868           fts3EvalNextRow(pCsr, pLeft, pRc);
   131869         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
   131870           fts3EvalNextRow(pCsr, pRight, pRc);
   131871         }else{
   131872           fts3EvalNextRow(pCsr, pLeft, pRc);
   131873           fts3EvalNextRow(pCsr, pRight, pRc);
   131874         }
   131875 
   131876         pExpr->bEof = (pLeft->bEof && pRight->bEof);
   131877         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   131878         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
   131879           pExpr->iDocid = pLeft->iDocid;
   131880         }else{
   131881           pExpr->iDocid = pRight->iDocid;
   131882         }
   131883 
   131884         break;
   131885       }
   131886 
   131887       case FTSQUERY_NOT: {
   131888         Fts3Expr *pLeft = pExpr->pLeft;
   131889         Fts3Expr *pRight = pExpr->pRight;
   131890 
   131891         if( pRight->bStart==0 ){
   131892           fts3EvalNextRow(pCsr, pRight, pRc);
   131893           assert( *pRc!=SQLITE_OK || pRight->bStart );
   131894         }
   131895 
   131896         fts3EvalNextRow(pCsr, pLeft, pRc);
   131897         if( pLeft->bEof==0 ){
   131898           while( !*pRc
   131899               && !pRight->bEof
   131900               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
   131901           ){
   131902             fts3EvalNextRow(pCsr, pRight, pRc);
   131903           }
   131904         }
   131905         pExpr->iDocid = pLeft->iDocid;
   131906         pExpr->bEof = pLeft->bEof;
   131907         break;
   131908       }
   131909 
   131910       default: {
   131911         Fts3Phrase *pPhrase = pExpr->pPhrase;
   131912         fts3EvalInvalidatePoslist(pPhrase);
   131913         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
   131914         pExpr->iDocid = pPhrase->doclist.iDocid;
   131915         break;
   131916       }
   131917     }
   131918   }
   131919 }
   131920 
   131921 /*
   131922 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
   131923 ** cluster, then this function returns 1 immediately.
   131924 **
   131925 ** Otherwise, it checks if the current row really does match the NEAR
   131926 ** expression, using the data currently stored in the position lists
   131927 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
   131928 **
   131929 ** If the current row is a match, the position list associated with each
   131930 ** phrase in the NEAR expression is edited in place to contain only those
   131931 ** phrase instances sufficiently close to their peers to satisfy all NEAR
   131932 ** constraints. In this case it returns 1. If the NEAR expression does not
   131933 ** match the current row, 0 is returned. The position lists may or may not
   131934 ** be edited if 0 is returned.
   131935 */
   131936 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
   131937   int res = 1;
   131938 
   131939   /* The following block runs if pExpr is the root of a NEAR query.
   131940   ** For example, the query:
   131941   **
   131942   **         "w" NEAR "x" NEAR "y" NEAR "z"
   131943   **
   131944   ** which is represented in tree form as:
   131945   **
   131946   **                               |
   131947   **                          +--NEAR--+      <-- root of NEAR query
   131948   **                          |        |
   131949   **                     +--NEAR--+   "z"
   131950   **                     |        |
   131951   **                +--NEAR--+   "y"
   131952   **                |        |
   131953   **               "w"      "x"
   131954   **
   131955   ** The right-hand child of a NEAR node is always a phrase. The
   131956   ** left-hand child may be either a phrase or a NEAR node. There are
   131957   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
   131958   */
   131959   if( *pRc==SQLITE_OK
   131960    && pExpr->eType==FTSQUERY_NEAR
   131961    && pExpr->bEof==0
   131962    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   131963   ){
   131964     Fts3Expr *p;
   131965     int nTmp = 0;                 /* Bytes of temp space */
   131966     char *aTmp;                   /* Temp space for PoslistNearMerge() */
   131967 
   131968     /* Allocate temporary working space. */
   131969     for(p=pExpr; p->pLeft; p=p->pLeft){
   131970       nTmp += p->pRight->pPhrase->doclist.nList;
   131971     }
   131972     nTmp += p->pPhrase->doclist.nList;
   131973     if( nTmp==0 ){
   131974       res = 0;
   131975     }else{
   131976       aTmp = sqlite3_malloc(nTmp*2);
   131977       if( !aTmp ){
   131978         *pRc = SQLITE_NOMEM;
   131979         res = 0;
   131980       }else{
   131981         char *aPoslist = p->pPhrase->doclist.pList;
   131982         int nToken = p->pPhrase->nToken;
   131983 
   131984         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
   131985           Fts3Phrase *pPhrase = p->pRight->pPhrase;
   131986           int nNear = p->nNear;
   131987           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   131988         }
   131989 
   131990         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
   131991         nToken = pExpr->pRight->pPhrase->nToken;
   131992         for(p=pExpr->pLeft; p && res; p=p->pLeft){
   131993           int nNear;
   131994           Fts3Phrase *pPhrase;
   131995           assert( p->pParent && p->pParent->pLeft==p );
   131996           nNear = p->pParent->nNear;
   131997           pPhrase = (
   131998               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
   131999               );
   132000           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   132001         }
   132002       }
   132003 
   132004       sqlite3_free(aTmp);
   132005     }
   132006   }
   132007 
   132008   return res;
   132009 }
   132010 
   132011 /*
   132012 ** This function is a helper function for fts3EvalTestDeferredAndNear().
   132013 ** Assuming no error occurs or has occurred, It returns non-zero if the
   132014 ** expression passed as the second argument matches the row that pCsr
   132015 ** currently points to, or zero if it does not.
   132016 **
   132017 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   132018 ** If an error occurs during execution of this function, *pRc is set to
   132019 ** the appropriate SQLite error code. In this case the returned value is
   132020 ** undefined.
   132021 */
   132022 static int fts3EvalTestExpr(
   132023   Fts3Cursor *pCsr,               /* FTS cursor handle */
   132024   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
   132025   int *pRc                        /* IN/OUT: Error code */
   132026 ){
   132027   int bHit = 1;                   /* Return value */
   132028   if( *pRc==SQLITE_OK ){
   132029     switch( pExpr->eType ){
   132030       case FTSQUERY_NEAR:
   132031       case FTSQUERY_AND:
   132032         bHit = (
   132033             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   132034          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   132035          && fts3EvalNearTest(pExpr, pRc)
   132036         );
   132037 
   132038         /* If the NEAR expression does not match any rows, zero the doclist for
   132039         ** all phrases involved in the NEAR. This is because the snippet(),
   132040         ** offsets() and matchinfo() functions are not supposed to recognize
   132041         ** any instances of phrases that are part of unmatched NEAR queries.
   132042         ** For example if this expression:
   132043         **
   132044         **    ... MATCH 'a OR (b NEAR c)'
   132045         **
   132046         ** is matched against a row containing:
   132047         **
   132048         **        'a b d e'
   132049         **
   132050         ** then any snippet() should ony highlight the "a" term, not the "b"
   132051         ** (as "b" is part of a non-matching NEAR clause).
   132052         */
   132053         if( bHit==0
   132054          && pExpr->eType==FTSQUERY_NEAR
   132055          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   132056         ){
   132057           Fts3Expr *p;
   132058           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
   132059             if( p->pRight->iDocid==pCsr->iPrevId ){
   132060               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
   132061             }
   132062           }
   132063           if( p->iDocid==pCsr->iPrevId ){
   132064             fts3EvalInvalidatePoslist(p->pPhrase);
   132065           }
   132066         }
   132067 
   132068         break;
   132069 
   132070       case FTSQUERY_OR: {
   132071         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
   132072         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
   132073         bHit = bHit1 || bHit2;
   132074         break;
   132075       }
   132076 
   132077       case FTSQUERY_NOT:
   132078         bHit = (
   132079             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   132080          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   132081         );
   132082         break;
   132083 
   132084       default: {
   132085 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   132086         if( pCsr->pDeferred
   132087          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
   132088         ){
   132089           Fts3Phrase *pPhrase = pExpr->pPhrase;
   132090           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
   132091           if( pExpr->bDeferred ){
   132092             fts3EvalInvalidatePoslist(pPhrase);
   132093           }
   132094           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
   132095           bHit = (pPhrase->doclist.pList!=0);
   132096           pExpr->iDocid = pCsr->iPrevId;
   132097         }else
   132098 #endif
   132099         {
   132100           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
   132101         }
   132102         break;
   132103       }
   132104     }
   132105   }
   132106   return bHit;
   132107 }
   132108 
   132109 /*
   132110 ** This function is called as the second part of each xNext operation when
   132111 ** iterating through the results of a full-text query. At this point the
   132112 ** cursor points to a row that matches the query expression, with the
   132113 ** following caveats:
   132114 **
   132115 **   * Up until this point, "NEAR" operators in the expression have been
   132116 **     treated as "AND".
   132117 **
   132118 **   * Deferred tokens have not yet been considered.
   132119 **
   132120 ** If *pRc is not SQLITE_OK when this function is called, it immediately
   132121 ** returns 0. Otherwise, it tests whether or not after considering NEAR
   132122 ** operators and deferred tokens the current row is still a match for the
   132123 ** expression. It returns 1 if both of the following are true:
   132124 **
   132125 **   1. *pRc is SQLITE_OK when this function returns, and
   132126 **
   132127 **   2. After scanning the current FTS table row for the deferred tokens,
   132128 **      it is determined that the row does *not* match the query.
   132129 **
   132130 ** Or, if no error occurs and it seems the current row does match the FTS
   132131 ** query, return 0.
   132132 */
   132133 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
   132134   int rc = *pRc;
   132135   int bMiss = 0;
   132136   if( rc==SQLITE_OK ){
   132137 
   132138     /* If there are one or more deferred tokens, load the current row into
   132139     ** memory and scan it to determine the position list for each deferred
   132140     ** token. Then, see if this row is really a match, considering deferred
   132141     ** tokens and NEAR operators (neither of which were taken into account
   132142     ** earlier, by fts3EvalNextRow()).
   132143     */
   132144     if( pCsr->pDeferred ){
   132145       rc = fts3CursorSeek(0, pCsr);
   132146       if( rc==SQLITE_OK ){
   132147         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
   132148       }
   132149     }
   132150     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
   132151 
   132152     /* Free the position-lists accumulated for each deferred token above. */
   132153     sqlite3Fts3FreeDeferredDoclists(pCsr);
   132154     *pRc = rc;
   132155   }
   132156   return (rc==SQLITE_OK && bMiss);
   132157 }
   132158 
   132159 /*
   132160 ** Advance to the next document that matches the FTS expression in
   132161 ** Fts3Cursor.pExpr.
   132162 */
   132163 static int fts3EvalNext(Fts3Cursor *pCsr){
   132164   int rc = SQLITE_OK;             /* Return Code */
   132165   Fts3Expr *pExpr = pCsr->pExpr;
   132166   assert( pCsr->isEof==0 );
   132167   if( pExpr==0 ){
   132168     pCsr->isEof = 1;
   132169   }else{
   132170     do {
   132171       if( pCsr->isRequireSeek==0 ){
   132172         sqlite3_reset(pCsr->pStmt);
   132173       }
   132174       assert( sqlite3_data_count(pCsr->pStmt)==0 );
   132175       fts3EvalNextRow(pCsr, pExpr, &rc);
   132176       pCsr->isEof = pExpr->bEof;
   132177       pCsr->isRequireSeek = 1;
   132178       pCsr->isMatchinfoNeeded = 1;
   132179       pCsr->iPrevId = pExpr->iDocid;
   132180     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
   132181   }
   132182 
   132183   /* Check if the cursor is past the end of the docid range specified
   132184   ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
   132185   if( rc==SQLITE_OK && (
   132186         (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
   132187      || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
   132188   )){
   132189     pCsr->isEof = 1;
   132190   }
   132191 
   132192   return rc;
   132193 }
   132194 
   132195 /*
   132196 ** Restart interation for expression pExpr so that the next call to
   132197 ** fts3EvalNext() visits the first row. Do not allow incremental
   132198 ** loading or merging of phrase doclists for this iteration.
   132199 **
   132200 ** If *pRc is other than SQLITE_OK when this function is called, it is
   132201 ** a no-op. If an error occurs within this function, *pRc is set to an
   132202 ** SQLite error code before returning.
   132203 */
   132204 static void fts3EvalRestart(
   132205   Fts3Cursor *pCsr,
   132206   Fts3Expr *pExpr,
   132207   int *pRc
   132208 ){
   132209   if( pExpr && *pRc==SQLITE_OK ){
   132210     Fts3Phrase *pPhrase = pExpr->pPhrase;
   132211 
   132212     if( pPhrase ){
   132213       fts3EvalInvalidatePoslist(pPhrase);
   132214       if( pPhrase->bIncr ){
   132215         int i;
   132216         for(i=0; i<pPhrase->nToken; i++){
   132217           Fts3PhraseToken *pToken = &pPhrase->aToken[i];
   132218           assert( pToken->pDeferred==0 );
   132219           if( pToken->pSegcsr ){
   132220             sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
   132221           }
   132222         }
   132223         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
   132224       }
   132225       pPhrase->doclist.pNextDocid = 0;
   132226       pPhrase->doclist.iDocid = 0;
   132227     }
   132228 
   132229     pExpr->iDocid = 0;
   132230     pExpr->bEof = 0;
   132231     pExpr->bStart = 0;
   132232 
   132233     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
   132234     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
   132235   }
   132236 }
   132237 
   132238 /*
   132239 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
   132240 ** expression rooted at pExpr, the cursor iterates through all rows matched
   132241 ** by pExpr, calling this function for each row. This function increments
   132242 ** the values in Fts3Expr.aMI[] according to the position-list currently
   132243 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
   132244 ** expression nodes.
   132245 */
   132246 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
   132247   if( pExpr ){
   132248     Fts3Phrase *pPhrase = pExpr->pPhrase;
   132249     if( pPhrase && pPhrase->doclist.pList ){
   132250       int iCol = 0;
   132251       char *p = pPhrase->doclist.pList;
   132252 
   132253       assert( *p );
   132254       while( 1 ){
   132255         u8 c = 0;
   132256         int iCnt = 0;
   132257         while( 0xFE & (*p | c) ){
   132258           if( (c&0x80)==0 ) iCnt++;
   132259           c = *p++ & 0x80;
   132260         }
   132261 
   132262         /* aMI[iCol*3 + 1] = Number of occurrences
   132263         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
   132264         */
   132265         pExpr->aMI[iCol*3 + 1] += iCnt;
   132266         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
   132267         if( *p==0x00 ) break;
   132268         p++;
   132269         p += fts3GetVarint32(p, &iCol);
   132270       }
   132271     }
   132272 
   132273     fts3EvalUpdateCounts(pExpr->pLeft);
   132274     fts3EvalUpdateCounts(pExpr->pRight);
   132275   }
   132276 }
   132277 
   132278 /*
   132279 ** Expression pExpr must be of type FTSQUERY_PHRASE.
   132280 **
   132281 ** If it is not already allocated and populated, this function allocates and
   132282 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
   132283 ** of a NEAR expression, then it also allocates and populates the same array
   132284 ** for all other phrases that are part of the NEAR expression.
   132285 **
   132286 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
   132287 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
   132288 */
   132289 static int fts3EvalGatherStats(
   132290   Fts3Cursor *pCsr,               /* Cursor object */
   132291   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
   132292 ){
   132293   int rc = SQLITE_OK;             /* Return code */
   132294 
   132295   assert( pExpr->eType==FTSQUERY_PHRASE );
   132296   if( pExpr->aMI==0 ){
   132297     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   132298     Fts3Expr *pRoot;                /* Root of NEAR expression */
   132299     Fts3Expr *p;                    /* Iterator used for several purposes */
   132300 
   132301     sqlite3_int64 iPrevId = pCsr->iPrevId;
   132302     sqlite3_int64 iDocid;
   132303     u8 bEof;
   132304 
   132305     /* Find the root of the NEAR expression */
   132306     pRoot = pExpr;
   132307     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
   132308       pRoot = pRoot->pParent;
   132309     }
   132310     iDocid = pRoot->iDocid;
   132311     bEof = pRoot->bEof;
   132312     assert( pRoot->bStart );
   132313 
   132314     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
   132315     for(p=pRoot; p; p=p->pLeft){
   132316       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
   132317       assert( pE->aMI==0 );
   132318       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
   132319       if( !pE->aMI ) return SQLITE_NOMEM;
   132320       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
   132321     }
   132322 
   132323     fts3EvalRestart(pCsr, pRoot, &rc);
   132324 
   132325     while( pCsr->isEof==0 && rc==SQLITE_OK ){
   132326 
   132327       do {
   132328         /* Ensure the %_content statement is reset. */
   132329         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
   132330         assert( sqlite3_data_count(pCsr->pStmt)==0 );
   132331 
   132332         /* Advance to the next document */
   132333         fts3EvalNextRow(pCsr, pRoot, &rc);
   132334         pCsr->isEof = pRoot->bEof;
   132335         pCsr->isRequireSeek = 1;
   132336         pCsr->isMatchinfoNeeded = 1;
   132337         pCsr->iPrevId = pRoot->iDocid;
   132338       }while( pCsr->isEof==0
   132339            && pRoot->eType==FTSQUERY_NEAR
   132340            && fts3EvalTestDeferredAndNear(pCsr, &rc)
   132341       );
   132342 
   132343       if( rc==SQLITE_OK && pCsr->isEof==0 ){
   132344         fts3EvalUpdateCounts(pRoot);
   132345       }
   132346     }
   132347 
   132348     pCsr->isEof = 0;
   132349     pCsr->iPrevId = iPrevId;
   132350 
   132351     if( bEof ){
   132352       pRoot->bEof = bEof;
   132353     }else{
   132354       /* Caution: pRoot may iterate through docids in ascending or descending
   132355       ** order. For this reason, even though it seems more defensive, the
   132356       ** do loop can not be written:
   132357       **
   132358       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
   132359       */
   132360       fts3EvalRestart(pCsr, pRoot, &rc);
   132361       do {
   132362         fts3EvalNextRow(pCsr, pRoot, &rc);
   132363         assert( pRoot->bEof==0 );
   132364       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
   132365       fts3EvalTestDeferredAndNear(pCsr, &rc);
   132366     }
   132367   }
   132368   return rc;
   132369 }
   132370 
   132371 /*
   132372 ** This function is used by the matchinfo() module to query a phrase
   132373 ** expression node for the following information:
   132374 **
   132375 **   1. The total number of occurrences of the phrase in each column of
   132376 **      the FTS table (considering all rows), and
   132377 **
   132378 **   2. For each column, the number of rows in the table for which the
   132379 **      column contains at least one instance of the phrase.
   132380 **
   132381 ** If no error occurs, SQLITE_OK is returned and the values for each column
   132382 ** written into the array aiOut as follows:
   132383 **
   132384 **   aiOut[iCol*3 + 1] = Number of occurrences
   132385 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
   132386 **
   132387 ** Caveats:
   132388 **
   132389 **   * If a phrase consists entirely of deferred tokens, then all output
   132390 **     values are set to the number of documents in the table. In other
   132391 **     words we assume that very common tokens occur exactly once in each
   132392 **     column of each row of the table.
   132393 **
   132394 **   * If a phrase contains some deferred tokens (and some non-deferred
   132395 **     tokens), count the potential occurrence identified by considering
   132396 **     the non-deferred tokens instead of actual phrase occurrences.
   132397 **
   132398 **   * If the phrase is part of a NEAR expression, then only phrase instances
   132399 **     that meet the NEAR constraint are included in the counts.
   132400 */
   132401 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
   132402   Fts3Cursor *pCsr,               /* FTS cursor handle */
   132403   Fts3Expr *pExpr,                /* Phrase expression */
   132404   u32 *aiOut                      /* Array to write results into (see above) */
   132405 ){
   132406   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   132407   int rc = SQLITE_OK;
   132408   int iCol;
   132409 
   132410   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
   132411     assert( pCsr->nDoc>0 );
   132412     for(iCol=0; iCol<pTab->nColumn; iCol++){
   132413       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
   132414       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
   132415     }
   132416   }else{
   132417     rc = fts3EvalGatherStats(pCsr, pExpr);
   132418     if( rc==SQLITE_OK ){
   132419       assert( pExpr->aMI );
   132420       for(iCol=0; iCol<pTab->nColumn; iCol++){
   132421         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
   132422         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
   132423       }
   132424     }
   132425   }
   132426 
   132427   return rc;
   132428 }
   132429 
   132430 /*
   132431 ** The expression pExpr passed as the second argument to this function
   132432 ** must be of type FTSQUERY_PHRASE.
   132433 **
   132434 ** The returned value is either NULL or a pointer to a buffer containing
   132435 ** a position-list indicating the occurrences of the phrase in column iCol
   132436 ** of the current row.
   132437 **
   132438 ** More specifically, the returned buffer contains 1 varint for each
   132439 ** occurrence of the phrase in the column, stored using the normal (delta+2)
   132440 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
   132441 ** if the requested column contains "a b X c d X X" and the position-list
   132442 ** for 'X' is requested, the buffer returned may contain:
   132443 **
   132444 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
   132445 **
   132446 ** This function works regardless of whether or not the phrase is deferred,
   132447 ** incremental, or neither.
   132448 */
   132449 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
   132450   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   132451   Fts3Expr *pExpr,                /* Phrase to return doclist for */
   132452   int iCol,                       /* Column to return position list for */
   132453   char **ppOut                    /* OUT: Pointer to position list */
   132454 ){
   132455   Fts3Phrase *pPhrase = pExpr->pPhrase;
   132456   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   132457   char *pIter;
   132458   int iThis;
   132459   sqlite3_int64 iDocid;
   132460 
   132461   /* If this phrase is applies specifically to some column other than
   132462   ** column iCol, return a NULL pointer.  */
   132463   *ppOut = 0;
   132464   assert( iCol>=0 && iCol<pTab->nColumn );
   132465   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
   132466     return SQLITE_OK;
   132467   }
   132468 
   132469   iDocid = pExpr->iDocid;
   132470   pIter = pPhrase->doclist.pList;
   132471   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
   132472     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
   132473     int iMul;                     /* +1 if csr dir matches index dir, else -1 */
   132474     int bOr = 0;
   132475     u8 bEof = 0;
   132476     u8 bTreeEof = 0;
   132477     Fts3Expr *p;                  /* Used to iterate from pExpr to root */
   132478     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
   132479 
   132480     /* Check if this phrase descends from an OR expression node. If not,
   132481     ** return NULL. Otherwise, the entry that corresponds to docid
   132482     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
   132483     ** tree that the node is part of has been marked as EOF, but the node
   132484     ** itself is not EOF, then it may point to an earlier entry. */
   132485     pNear = pExpr;
   132486     for(p=pExpr->pParent; p; p=p->pParent){
   132487       if( p->eType==FTSQUERY_OR ) bOr = 1;
   132488       if( p->eType==FTSQUERY_NEAR ) pNear = p;
   132489       if( p->bEof ) bTreeEof = 1;
   132490     }
   132491     if( bOr==0 ) return SQLITE_OK;
   132492 
   132493     /* This is the descendent of an OR node. In this case we cannot use
   132494     ** an incremental phrase. Load the entire doclist for the phrase
   132495     ** into memory in this case.  */
   132496     if( pPhrase->bIncr ){
   132497       int rc = SQLITE_OK;
   132498       int bEofSave = pExpr->bEof;
   132499       fts3EvalRestart(pCsr, pExpr, &rc);
   132500       while( rc==SQLITE_OK && !pExpr->bEof ){
   132501         fts3EvalNextRow(pCsr, pExpr, &rc);
   132502         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
   132503       }
   132504       pIter = pPhrase->doclist.pList;
   132505       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
   132506       if( rc!=SQLITE_OK ) return rc;
   132507     }
   132508 
   132509     iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
   132510     while( bTreeEof==1
   132511         && pNear->bEof==0
   132512         && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
   132513     ){
   132514       int rc = SQLITE_OK;
   132515       fts3EvalNextRow(pCsr, pExpr, &rc);
   132516       if( rc!=SQLITE_OK ) return rc;
   132517       iDocid = pExpr->iDocid;
   132518       pIter = pPhrase->doclist.pList;
   132519     }
   132520 
   132521     bEof = (pPhrase->doclist.nAll==0);
   132522     assert( bDescDoclist==0 || bDescDoclist==1 );
   132523     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
   132524 
   132525     if( bEof==0 ){
   132526       if( pCsr->bDesc==bDescDoclist ){
   132527         int dummy;
   132528         if( pNear->bEof ){
   132529           /* This expression is already at EOF. So position it to point to the
   132530           ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
   132531           ** iDocid is already set for this entry, so all that is required is
   132532           ** to set pIter to point to the first byte of the last position-list
   132533           ** in the doclist.
   132534           **
   132535           ** It would also be correct to set pIter and iDocid to zero. In
   132536           ** this case, the first call to sqltie3Fts4DoclistPrev() below
   132537           ** would also move the iterator to point to the last entry in the
   132538           ** doclist. However, this is expensive, as to do so it has to
   132539           ** iterate through the entire doclist from start to finish (since
   132540           ** it does not know the docid for the last entry).  */
   132541           pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
   132542           fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
   132543         }
   132544         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
   132545           sqlite3Fts3DoclistPrev(
   132546               bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
   132547               &pIter, &iDocid, &dummy, &bEof
   132548           );
   132549         }
   132550       }else{
   132551         if( pNear->bEof ){
   132552           pIter = 0;
   132553           iDocid = 0;
   132554         }
   132555         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
   132556           sqlite3Fts3DoclistNext(
   132557               bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
   132558               &pIter, &iDocid, &bEof
   132559           );
   132560         }
   132561       }
   132562     }
   132563 
   132564     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
   132565   }
   132566   if( pIter==0 ) return SQLITE_OK;
   132567 
   132568   if( *pIter==0x01 ){
   132569     pIter++;
   132570     pIter += fts3GetVarint32(pIter, &iThis);
   132571   }else{
   132572     iThis = 0;
   132573   }
   132574   while( iThis<iCol ){
   132575     fts3ColumnlistCopy(0, &pIter);
   132576     if( *pIter==0x00 ) return 0;
   132577     pIter++;
   132578     pIter += fts3GetVarint32(pIter, &iThis);
   132579   }
   132580 
   132581   *ppOut = ((iCol==iThis)?pIter:0);
   132582   return SQLITE_OK;
   132583 }
   132584 
   132585 /*
   132586 ** Free all components of the Fts3Phrase structure that were allocated by
   132587 ** the eval module. Specifically, this means to free:
   132588 **
   132589 **   * the contents of pPhrase->doclist, and
   132590 **   * any Fts3MultiSegReader objects held by phrase tokens.
   132591 */
   132592 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
   132593   if( pPhrase ){
   132594     int i;
   132595     sqlite3_free(pPhrase->doclist.aAll);
   132596     fts3EvalInvalidatePoslist(pPhrase);
   132597     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
   132598     for(i=0; i<pPhrase->nToken; i++){
   132599       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
   132600       pPhrase->aToken[i].pSegcsr = 0;
   132601     }
   132602   }
   132603 }
   132604 
   132605 
   132606 /*
   132607 ** Return SQLITE_CORRUPT_VTAB.
   132608 */
   132609 #ifdef SQLITE_DEBUG
   132610 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
   132611   return SQLITE_CORRUPT_VTAB;
   132612 }
   132613 #endif
   132614 
   132615 #if !SQLITE_CORE
   132616 /*
   132617 ** Initialize API pointer table, if required.
   132618 */
   132619 #ifdef _WIN32
   132620 __declspec(dllexport)
   132621 #endif
   132622 SQLITE_API int sqlite3_fts3_init(
   132623   sqlite3 *db,
   132624   char **pzErrMsg,
   132625   const sqlite3_api_routines *pApi
   132626 ){
   132627   SQLITE_EXTENSION_INIT2(pApi)
   132628   return sqlite3Fts3Init(db);
   132629 }
   132630 #endif
   132631 
   132632 #endif
   132633 
   132634 /************** End of fts3.c ************************************************/
   132635 /************** Begin file fts3_aux.c ****************************************/
   132636 /*
   132637 ** 2011 Jan 27
   132638 **
   132639 ** The author disclaims copyright to this source code.  In place of
   132640 ** a legal notice, here is a blessing:
   132641 **
   132642 **    May you do good and not evil.
   132643 **    May you find forgiveness for yourself and forgive others.
   132644 **    May you share freely, never taking more than you give.
   132645 **
   132646 ******************************************************************************
   132647 **
   132648 */
   132649 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   132650 
   132651 /* #include <string.h> */
   132652 /* #include <assert.h> */
   132653 
   132654 typedef struct Fts3auxTable Fts3auxTable;
   132655 typedef struct Fts3auxCursor Fts3auxCursor;
   132656 
   132657 struct Fts3auxTable {
   132658   sqlite3_vtab base;              /* Base class used by SQLite core */
   132659   Fts3Table *pFts3Tab;
   132660 };
   132661 
   132662 struct Fts3auxCursor {
   132663   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   132664   Fts3MultiSegReader csr;        /* Must be right after "base" */
   132665   Fts3SegFilter filter;
   132666   char *zStop;
   132667   int nStop;                      /* Byte-length of string zStop */
   132668   int iLangid;                    /* Language id to query */
   132669   int isEof;                      /* True if cursor is at EOF */
   132670   sqlite3_int64 iRowid;           /* Current rowid */
   132671 
   132672   int iCol;                       /* Current value of 'col' column */
   132673   int nStat;                      /* Size of aStat[] array */
   132674   struct Fts3auxColstats {
   132675     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
   132676     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
   132677   } *aStat;
   132678 };
   132679 
   132680 /*
   132681 ** Schema of the terms table.
   132682 */
   132683 #define FTS3_AUX_SCHEMA \
   132684   "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
   132685 
   132686 /*
   132687 ** This function does all the work for both the xConnect and xCreate methods.
   132688 ** These tables have no persistent representation of their own, so xConnect
   132689 ** and xCreate are identical operations.
   132690 */
   132691 static int fts3auxConnectMethod(
   132692   sqlite3 *db,                    /* Database connection */
   132693   void *pUnused,                  /* Unused */
   132694   int argc,                       /* Number of elements in argv array */
   132695   const char * const *argv,       /* xCreate/xConnect argument array */
   132696   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   132697   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   132698 ){
   132699   char const *zDb;                /* Name of database (e.g. "main") */
   132700   char const *zFts3;              /* Name of fts3 table */
   132701   int nDb;                        /* Result of strlen(zDb) */
   132702   int nFts3;                      /* Result of strlen(zFts3) */
   132703   int nByte;                      /* Bytes of space to allocate here */
   132704   int rc;                         /* value returned by declare_vtab() */
   132705   Fts3auxTable *p;                /* Virtual table object to return */
   132706 
   132707   UNUSED_PARAMETER(pUnused);
   132708 
   132709   /* The user should invoke this in one of two forms:
   132710   **
   132711   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
   132712   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
   132713   */
   132714   if( argc!=4 && argc!=5 ) goto bad_args;
   132715 
   132716   zDb = argv[1];
   132717   nDb = (int)strlen(zDb);
   132718   if( argc==5 ){
   132719     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
   132720       zDb = argv[3];
   132721       nDb = (int)strlen(zDb);
   132722       zFts3 = argv[4];
   132723     }else{
   132724       goto bad_args;
   132725     }
   132726   }else{
   132727     zFts3 = argv[3];
   132728   }
   132729   nFts3 = (int)strlen(zFts3);
   132730 
   132731   rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
   132732   if( rc!=SQLITE_OK ) return rc;
   132733 
   132734   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
   132735   p = (Fts3auxTable *)sqlite3_malloc(nByte);
   132736   if( !p ) return SQLITE_NOMEM;
   132737   memset(p, 0, nByte);
   132738 
   132739   p->pFts3Tab = (Fts3Table *)&p[1];
   132740   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
   132741   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
   132742   p->pFts3Tab->db = db;
   132743   p->pFts3Tab->nIndex = 1;
   132744 
   132745   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
   132746   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
   132747   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
   132748 
   132749   *ppVtab = (sqlite3_vtab *)p;
   132750   return SQLITE_OK;
   132751 
   132752  bad_args:
   132753   *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
   132754   return SQLITE_ERROR;
   132755 }
   132756 
   132757 /*
   132758 ** This function does the work for both the xDisconnect and xDestroy methods.
   132759 ** These tables have no persistent representation of their own, so xDisconnect
   132760 ** and xDestroy are identical operations.
   132761 */
   132762 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
   132763   Fts3auxTable *p = (Fts3auxTable *)pVtab;
   132764   Fts3Table *pFts3 = p->pFts3Tab;
   132765   int i;
   132766 
   132767   /* Free any prepared statements held */
   132768   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
   132769     sqlite3_finalize(pFts3->aStmt[i]);
   132770   }
   132771   sqlite3_free(pFts3->zSegmentsTbl);
   132772   sqlite3_free(p);
   132773   return SQLITE_OK;
   132774 }
   132775 
   132776 #define FTS4AUX_EQ_CONSTRAINT 1
   132777 #define FTS4AUX_GE_CONSTRAINT 2
   132778 #define FTS4AUX_LE_CONSTRAINT 4
   132779 
   132780 /*
   132781 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
   132782 */
   132783 static int fts3auxBestIndexMethod(
   132784   sqlite3_vtab *pVTab,
   132785   sqlite3_index_info *pInfo
   132786 ){
   132787   int i;
   132788   int iEq = -1;
   132789   int iGe = -1;
   132790   int iLe = -1;
   132791   int iLangid = -1;
   132792   int iNext = 1;                  /* Next free argvIndex value */
   132793 
   132794   UNUSED_PARAMETER(pVTab);
   132795 
   132796   /* This vtab delivers always results in "ORDER BY term ASC" order. */
   132797   if( pInfo->nOrderBy==1
   132798    && pInfo->aOrderBy[0].iColumn==0
   132799    && pInfo->aOrderBy[0].desc==0
   132800   ){
   132801     pInfo->orderByConsumed = 1;
   132802   }
   132803 
   132804   /* Search for equality and range constraints on the "term" column.
   132805   ** And equality constraints on the hidden "languageid" column. */
   132806   for(i=0; i<pInfo->nConstraint; i++){
   132807     if( pInfo->aConstraint[i].usable ){
   132808       int op = pInfo->aConstraint[i].op;
   132809       int iCol = pInfo->aConstraint[i].iColumn;
   132810 
   132811       if( iCol==0 ){
   132812         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
   132813         if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
   132814         if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
   132815         if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
   132816         if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
   132817       }
   132818       if( iCol==4 ){
   132819         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
   132820       }
   132821     }
   132822   }
   132823 
   132824   if( iEq>=0 ){
   132825     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
   132826     pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
   132827     pInfo->estimatedCost = 5;
   132828   }else{
   132829     pInfo->idxNum = 0;
   132830     pInfo->estimatedCost = 20000;
   132831     if( iGe>=0 ){
   132832       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
   132833       pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
   132834       pInfo->estimatedCost /= 2;
   132835     }
   132836     if( iLe>=0 ){
   132837       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
   132838       pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
   132839       pInfo->estimatedCost /= 2;
   132840     }
   132841   }
   132842   if( iLangid>=0 ){
   132843     pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
   132844     pInfo->estimatedCost--;
   132845   }
   132846 
   132847   return SQLITE_OK;
   132848 }
   132849 
   132850 /*
   132851 ** xOpen - Open a cursor.
   132852 */
   132853 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   132854   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
   132855 
   132856   UNUSED_PARAMETER(pVTab);
   132857 
   132858   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
   132859   if( !pCsr ) return SQLITE_NOMEM;
   132860   memset(pCsr, 0, sizeof(Fts3auxCursor));
   132861 
   132862   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
   132863   return SQLITE_OK;
   132864 }
   132865 
   132866 /*
   132867 ** xClose - Close a cursor.
   132868 */
   132869 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
   132870   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   132871   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   132872 
   132873   sqlite3Fts3SegmentsClose(pFts3);
   132874   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   132875   sqlite3_free((void *)pCsr->filter.zTerm);
   132876   sqlite3_free(pCsr->zStop);
   132877   sqlite3_free(pCsr->aStat);
   132878   sqlite3_free(pCsr);
   132879   return SQLITE_OK;
   132880 }
   132881 
   132882 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
   132883   if( nSize>pCsr->nStat ){
   132884     struct Fts3auxColstats *aNew;
   132885     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
   132886         sizeof(struct Fts3auxColstats) * nSize
   132887     );
   132888     if( aNew==0 ) return SQLITE_NOMEM;
   132889     memset(&aNew[pCsr->nStat], 0,
   132890         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
   132891     );
   132892     pCsr->aStat = aNew;
   132893     pCsr->nStat = nSize;
   132894   }
   132895   return SQLITE_OK;
   132896 }
   132897 
   132898 /*
   132899 ** xNext - Advance the cursor to the next row, if any.
   132900 */
   132901 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
   132902   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   132903   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   132904   int rc;
   132905 
   132906   /* Increment our pretend rowid value. */
   132907   pCsr->iRowid++;
   132908 
   132909   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
   132910     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
   132911   }
   132912 
   132913   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
   132914   if( rc==SQLITE_ROW ){
   132915     int i = 0;
   132916     int nDoclist = pCsr->csr.nDoclist;
   132917     char *aDoclist = pCsr->csr.aDoclist;
   132918     int iCol;
   132919 
   132920     int eState = 0;
   132921 
   132922     if( pCsr->zStop ){
   132923       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
   132924       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
   132925       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
   132926         pCsr->isEof = 1;
   132927         return SQLITE_OK;
   132928       }
   132929     }
   132930 
   132931     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
   132932     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
   132933     iCol = 0;
   132934 
   132935     while( i<nDoclist ){
   132936       sqlite3_int64 v = 0;
   132937 
   132938       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
   132939       switch( eState ){
   132940         /* State 0. In this state the integer just read was a docid. */
   132941         case 0:
   132942           pCsr->aStat[0].nDoc++;
   132943           eState = 1;
   132944           iCol = 0;
   132945           break;
   132946 
   132947         /* State 1. In this state we are expecting either a 1, indicating
   132948         ** that the following integer will be a column number, or the
   132949         ** start of a position list for column 0.
   132950         **
   132951         ** The only difference between state 1 and state 2 is that if the
   132952         ** integer encountered in state 1 is not 0 or 1, then we need to
   132953         ** increment the column 0 "nDoc" count for this term.
   132954         */
   132955         case 1:
   132956           assert( iCol==0 );
   132957           if( v>1 ){
   132958             pCsr->aStat[1].nDoc++;
   132959           }
   132960           eState = 2;
   132961           /* fall through */
   132962 
   132963         case 2:
   132964           if( v==0 ){       /* 0x00. Next integer will be a docid. */
   132965             eState = 0;
   132966           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
   132967             eState = 3;
   132968           }else{            /* 2 or greater. A position. */
   132969             pCsr->aStat[iCol+1].nOcc++;
   132970             pCsr->aStat[0].nOcc++;
   132971           }
   132972           break;
   132973 
   132974         /* State 3. The integer just read is a column number. */
   132975         default: assert( eState==3 );
   132976           iCol = (int)v;
   132977           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
   132978           pCsr->aStat[iCol+1].nDoc++;
   132979           eState = 2;
   132980           break;
   132981       }
   132982     }
   132983 
   132984     pCsr->iCol = 0;
   132985     rc = SQLITE_OK;
   132986   }else{
   132987     pCsr->isEof = 1;
   132988   }
   132989   return rc;
   132990 }
   132991 
   132992 /*
   132993 ** xFilter - Initialize a cursor to point at the start of its data.
   132994 */
   132995 static int fts3auxFilterMethod(
   132996   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   132997   int idxNum,                     /* Strategy index */
   132998   const char *idxStr,             /* Unused */
   132999   int nVal,                       /* Number of elements in apVal */
   133000   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   133001 ){
   133002   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   133003   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   133004   int rc;
   133005   int isScan = 0;
   133006   int iLangVal = 0;               /* Language id to query */
   133007 
   133008   int iEq = -1;                   /* Index of term=? value in apVal */
   133009   int iGe = -1;                   /* Index of term>=? value in apVal */
   133010   int iLe = -1;                   /* Index of term<=? value in apVal */
   133011   int iLangid = -1;               /* Index of languageid=? value in apVal */
   133012   int iNext = 0;
   133013 
   133014   UNUSED_PARAMETER(nVal);
   133015   UNUSED_PARAMETER(idxStr);
   133016 
   133017   assert( idxStr==0 );
   133018   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
   133019        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
   133020        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
   133021   );
   133022 
   133023   if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
   133024     iEq = iNext++;
   133025   }else{
   133026     isScan = 1;
   133027     if( idxNum & FTS4AUX_GE_CONSTRAINT ){
   133028       iGe = iNext++;
   133029     }
   133030     if( idxNum & FTS4AUX_LE_CONSTRAINT ){
   133031       iLe = iNext++;
   133032     }
   133033   }
   133034   if( iNext<nVal ){
   133035     iLangid = iNext++;
   133036   }
   133037 
   133038   /* In case this cursor is being reused, close and zero it. */
   133039   testcase(pCsr->filter.zTerm);
   133040   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   133041   sqlite3_free((void *)pCsr->filter.zTerm);
   133042   sqlite3_free(pCsr->aStat);
   133043   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
   133044 
   133045   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
   133046   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
   133047 
   133048   if( iEq>=0 || iGe>=0 ){
   133049     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
   133050     assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
   133051     if( zStr ){
   133052       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
   133053       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
   133054       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
   133055     }
   133056   }
   133057 
   133058   if( iLe>=0 ){
   133059     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
   133060     pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
   133061     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
   133062   }
   133063 
   133064   if( iLangid>=0 ){
   133065     iLangVal = sqlite3_value_int(apVal[iLangid]);
   133066 
   133067     /* If the user specified a negative value for the languageid, use zero
   133068     ** instead. This works, as the "languageid=?" constraint will also
   133069     ** be tested by the VDBE layer. The test will always be false (since
   133070     ** this module will not return a row with a negative languageid), and
   133071     ** so the overall query will return zero rows.  */
   133072     if( iLangVal<0 ) iLangVal = 0;
   133073   }
   133074   pCsr->iLangid = iLangVal;
   133075 
   133076   rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
   133077       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
   133078   );
   133079   if( rc==SQLITE_OK ){
   133080     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
   133081   }
   133082 
   133083   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
   133084   return rc;
   133085 }
   133086 
   133087 /*
   133088 ** xEof - Return true if the cursor is at EOF, or false otherwise.
   133089 */
   133090 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
   133091   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   133092   return pCsr->isEof;
   133093 }
   133094 
   133095 /*
   133096 ** xColumn - Return a column value.
   133097 */
   133098 static int fts3auxColumnMethod(
   133099   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   133100   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   133101   int iCol                        /* Index of column to read value from */
   133102 ){
   133103   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
   133104 
   133105   assert( p->isEof==0 );
   133106   switch( iCol ){
   133107     case 0: /* term */
   133108       sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
   133109       break;
   133110 
   133111     case 1: /* col */
   133112       if( p->iCol ){
   133113         sqlite3_result_int(pCtx, p->iCol-1);
   133114       }else{
   133115         sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
   133116       }
   133117       break;
   133118 
   133119     case 2: /* documents */
   133120       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
   133121       break;
   133122 
   133123     case 3: /* occurrences */
   133124       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
   133125       break;
   133126 
   133127     default: /* languageid */
   133128       assert( iCol==4 );
   133129       sqlite3_result_int(pCtx, p->iLangid);
   133130       break;
   133131   }
   133132 
   133133   return SQLITE_OK;
   133134 }
   133135 
   133136 /*
   133137 ** xRowid - Return the current rowid for the cursor.
   133138 */
   133139 static int fts3auxRowidMethod(
   133140   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   133141   sqlite_int64 *pRowid            /* OUT: Rowid value */
   133142 ){
   133143   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   133144   *pRowid = pCsr->iRowid;
   133145   return SQLITE_OK;
   133146 }
   133147 
   133148 /*
   133149 ** Register the fts3aux module with database connection db. Return SQLITE_OK
   133150 ** if successful or an error code if sqlite3_create_module() fails.
   133151 */
   133152 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
   133153   static const sqlite3_module fts3aux_module = {
   133154      0,                           /* iVersion      */
   133155      fts3auxConnectMethod,        /* xCreate       */
   133156      fts3auxConnectMethod,        /* xConnect      */
   133157      fts3auxBestIndexMethod,      /* xBestIndex    */
   133158      fts3auxDisconnectMethod,     /* xDisconnect   */
   133159      fts3auxDisconnectMethod,     /* xDestroy      */
   133160      fts3auxOpenMethod,           /* xOpen         */
   133161      fts3auxCloseMethod,          /* xClose        */
   133162      fts3auxFilterMethod,         /* xFilter       */
   133163      fts3auxNextMethod,           /* xNext         */
   133164      fts3auxEofMethod,            /* xEof          */
   133165      fts3auxColumnMethod,         /* xColumn       */
   133166      fts3auxRowidMethod,          /* xRowid        */
   133167      0,                           /* xUpdate       */
   133168      0,                           /* xBegin        */
   133169      0,                           /* xSync         */
   133170      0,                           /* xCommit       */
   133171      0,                           /* xRollback     */
   133172      0,                           /* xFindFunction */
   133173      0,                           /* xRename       */
   133174      0,                           /* xSavepoint    */
   133175      0,                           /* xRelease      */
   133176      0                            /* xRollbackTo   */
   133177   };
   133178   int rc;                         /* Return code */
   133179 
   133180   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
   133181   return rc;
   133182 }
   133183 
   133184 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   133185 
   133186 /************** End of fts3_aux.c ********************************************/
   133187 /************** Begin file fts3_expr.c ***************************************/
   133188 /*
   133189 ** 2008 Nov 28
   133190 **
   133191 ** The author disclaims copyright to this source code.  In place of
   133192 ** a legal notice, here is a blessing:
   133193 **
   133194 **    May you do good and not evil.
   133195 **    May you find forgiveness for yourself and forgive others.
   133196 **    May you share freely, never taking more than you give.
   133197 **
   133198 ******************************************************************************
   133199 **
   133200 ** This module contains code that implements a parser for fts3 query strings
   133201 ** (the right-hand argument to the MATCH operator). Because the supported
   133202 ** syntax is relatively simple, the whole tokenizer/parser system is
   133203 ** hand-coded.
   133204 */
   133205 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   133206 
   133207 /*
   133208 ** By default, this module parses the legacy syntax that has been
   133209 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
   133210 ** is defined, then it uses the new syntax. The differences between
   133211 ** the new and the old syntaxes are:
   133212 **
   133213 **  a) The new syntax supports parenthesis. The old does not.
   133214 **
   133215 **  b) The new syntax supports the AND and NOT operators. The old does not.
   133216 **
   133217 **  c) The old syntax supports the "-" token qualifier. This is not
   133218 **     supported by the new syntax (it is replaced by the NOT operator).
   133219 **
   133220 **  d) When using the old syntax, the OR operator has a greater precedence
   133221 **     than an implicit AND. When using the new, both implicity and explicit
   133222 **     AND operators have a higher precedence than OR.
   133223 **
   133224 ** If compiled with SQLITE_TEST defined, then this module exports the
   133225 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
   133226 ** to zero causes the module to use the old syntax. If it is set to
   133227 ** non-zero the new syntax is activated. This is so both syntaxes can
   133228 ** be tested using a single build of testfixture.
   133229 **
   133230 ** The following describes the syntax supported by the fts3 MATCH
   133231 ** operator in a similar format to that used by the lemon parser
   133232 ** generator. This module does not use actually lemon, it uses a
   133233 ** custom parser.
   133234 **
   133235 **   query ::= andexpr (OR andexpr)*.
   133236 **
   133237 **   andexpr ::= notexpr (AND? notexpr)*.
   133238 **
   133239 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
   133240 **   notexpr ::= LP query RP.
   133241 **
   133242 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
   133243 **
   133244 **   distance_opt ::= .
   133245 **   distance_opt ::= / INTEGER.
   133246 **
   133247 **   phrase ::= TOKEN.
   133248 **   phrase ::= COLUMN:TOKEN.
   133249 **   phrase ::= "TOKEN TOKEN TOKEN...".
   133250 */
   133251 
   133252 #ifdef SQLITE_TEST
   133253 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
   133254 #else
   133255 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   133256 #  define sqlite3_fts3_enable_parentheses 1
   133257 # else
   133258 #  define sqlite3_fts3_enable_parentheses 0
   133259 # endif
   133260 #endif
   133261 
   133262 /*
   133263 ** Default span for NEAR operators.
   133264 */
   133265 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
   133266 
   133267 /* #include <string.h> */
   133268 /* #include <assert.h> */
   133269 
   133270 /*
   133271 ** isNot:
   133272 **   This variable is used by function getNextNode(). When getNextNode() is
   133273 **   called, it sets ParseContext.isNot to true if the 'next node' is a
   133274 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
   133275 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
   133276 **   zero.
   133277 */
   133278 typedef struct ParseContext ParseContext;
   133279 struct ParseContext {
   133280   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
   133281   int iLangid;                        /* Language id used with tokenizer */
   133282   const char **azCol;                 /* Array of column names for fts3 table */
   133283   int bFts4;                          /* True to allow FTS4-only syntax */
   133284   int nCol;                           /* Number of entries in azCol[] */
   133285   int iDefaultCol;                    /* Default column to query */
   133286   int isNot;                          /* True if getNextNode() sees a unary - */
   133287   sqlite3_context *pCtx;              /* Write error message here */
   133288   int nNest;                          /* Number of nested brackets */
   133289 };
   133290 
   133291 /*
   133292 ** This function is equivalent to the standard isspace() function.
   133293 **
   133294 ** The standard isspace() can be awkward to use safely, because although it
   133295 ** is defined to accept an argument of type int, its behavior when passed
   133296 ** an integer that falls outside of the range of the unsigned char type
   133297 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
   133298 ** is defined to accept an argument of type char, and always returns 0 for
   133299 ** any values that fall outside of the range of the unsigned char type (i.e.
   133300 ** negative values).
   133301 */
   133302 static int fts3isspace(char c){
   133303   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
   133304 }
   133305 
   133306 /*
   133307 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
   133308 ** zero the memory before returning a pointer to it. If unsuccessful,
   133309 ** return NULL.
   133310 */
   133311 static void *fts3MallocZero(int nByte){
   133312   void *pRet = sqlite3_malloc(nByte);
   133313   if( pRet ) memset(pRet, 0, nByte);
   133314   return pRet;
   133315 }
   133316 
   133317 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
   133318   sqlite3_tokenizer *pTokenizer,
   133319   int iLangid,
   133320   const char *z,
   133321   int n,
   133322   sqlite3_tokenizer_cursor **ppCsr
   133323 ){
   133324   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   133325   sqlite3_tokenizer_cursor *pCsr = 0;
   133326   int rc;
   133327 
   133328   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
   133329   assert( rc==SQLITE_OK || pCsr==0 );
   133330   if( rc==SQLITE_OK ){
   133331     pCsr->pTokenizer = pTokenizer;
   133332     if( pModule->iVersion>=1 ){
   133333       rc = pModule->xLanguageid(pCsr, iLangid);
   133334       if( rc!=SQLITE_OK ){
   133335         pModule->xClose(pCsr);
   133336         pCsr = 0;
   133337       }
   133338     }
   133339   }
   133340   *ppCsr = pCsr;
   133341   return rc;
   133342 }
   133343 
   133344 /*
   133345 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
   133346 ** call fts3ExprParse(). So this forward declaration is required.
   133347 */
   133348 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
   133349 
   133350 /*
   133351 ** Extract the next token from buffer z (length n) using the tokenizer
   133352 ** and other information (column names etc.) in pParse. Create an Fts3Expr
   133353 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
   133354 ** single token and set *ppExpr to point to it. If the end of the buffer is
   133355 ** reached before a token is found, set *ppExpr to zero. It is the
   133356 ** responsibility of the caller to eventually deallocate the allocated
   133357 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
   133358 **
   133359 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
   133360 ** fails.
   133361 */
   133362 static int getNextToken(
   133363   ParseContext *pParse,                   /* fts3 query parse context */
   133364   int iCol,                               /* Value for Fts3Phrase.iColumn */
   133365   const char *z, int n,                   /* Input string */
   133366   Fts3Expr **ppExpr,                      /* OUT: expression */
   133367   int *pnConsumed                         /* OUT: Number of bytes consumed */
   133368 ){
   133369   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   133370   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   133371   int rc;
   133372   sqlite3_tokenizer_cursor *pCursor;
   133373   Fts3Expr *pRet = 0;
   133374   int i = 0;
   133375 
   133376   /* Set variable i to the maximum number of bytes of input to tokenize. */
   133377   for(i=0; i<n; i++){
   133378     if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
   133379     if( z[i]=='*' || z[i]=='"' ) break;
   133380   }
   133381 
   133382   *pnConsumed = i;
   133383   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
   133384   if( rc==SQLITE_OK ){
   133385     const char *zToken;
   133386     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
   133387     int nByte;                               /* total space to allocate */
   133388 
   133389     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
   133390     if( rc==SQLITE_OK ){
   133391       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
   133392       pRet = (Fts3Expr *)fts3MallocZero(nByte);
   133393       if( !pRet ){
   133394         rc = SQLITE_NOMEM;
   133395       }else{
   133396         pRet->eType = FTSQUERY_PHRASE;
   133397         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
   133398         pRet->pPhrase->nToken = 1;
   133399         pRet->pPhrase->iColumn = iCol;
   133400         pRet->pPhrase->aToken[0].n = nToken;
   133401         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
   133402         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
   133403 
   133404         if( iEnd<n && z[iEnd]=='*' ){
   133405           pRet->pPhrase->aToken[0].isPrefix = 1;
   133406           iEnd++;
   133407         }
   133408 
   133409         while( 1 ){
   133410           if( !sqlite3_fts3_enable_parentheses
   133411            && iStart>0 && z[iStart-1]=='-'
   133412           ){
   133413             pParse->isNot = 1;
   133414             iStart--;
   133415           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
   133416             pRet->pPhrase->aToken[0].bFirst = 1;
   133417             iStart--;
   133418           }else{
   133419             break;
   133420           }
   133421         }
   133422 
   133423       }
   133424       *pnConsumed = iEnd;
   133425     }else if( i && rc==SQLITE_DONE ){
   133426       rc = SQLITE_OK;
   133427     }
   133428 
   133429     pModule->xClose(pCursor);
   133430   }
   133431 
   133432   *ppExpr = pRet;
   133433   return rc;
   133434 }
   133435 
   133436 
   133437 /*
   133438 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
   133439 ** then free the old allocation.
   133440 */
   133441 static void *fts3ReallocOrFree(void *pOrig, int nNew){
   133442   void *pRet = sqlite3_realloc(pOrig, nNew);
   133443   if( !pRet ){
   133444     sqlite3_free(pOrig);
   133445   }
   133446   return pRet;
   133447 }
   133448 
   133449 /*
   133450 ** Buffer zInput, length nInput, contains the contents of a quoted string
   133451 ** that appeared as part of an fts3 query expression. Neither quote character
   133452 ** is included in the buffer. This function attempts to tokenize the entire
   133453 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
   133454 ** containing the results.
   133455 **
   133456 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
   133457 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
   133458 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
   133459 ** to 0.
   133460 */
   133461 static int getNextString(
   133462   ParseContext *pParse,                   /* fts3 query parse context */
   133463   const char *zInput, int nInput,         /* Input string */
   133464   Fts3Expr **ppExpr                       /* OUT: expression */
   133465 ){
   133466   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   133467   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   133468   int rc;
   133469   Fts3Expr *p = 0;
   133470   sqlite3_tokenizer_cursor *pCursor = 0;
   133471   char *zTemp = 0;
   133472   int nTemp = 0;
   133473 
   133474   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   133475   int nToken = 0;
   133476 
   133477   /* The final Fts3Expr data structure, including the Fts3Phrase,
   133478   ** Fts3PhraseToken structures token buffers are all stored as a single
   133479   ** allocation so that the expression can be freed with a single call to
   133480   ** sqlite3_free(). Setting this up requires a two pass approach.
   133481   **
   133482   ** The first pass, in the block below, uses a tokenizer cursor to iterate
   133483   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
   133484   ** to assemble data in two dynamic buffers:
   133485   **
   133486   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
   133487   **             structure, followed by the array of Fts3PhraseToken
   133488   **             structures. This pass only populates the Fts3PhraseToken array.
   133489   **
   133490   **   Buffer zTemp: Contains copies of all tokens.
   133491   **
   133492   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
   133493   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
   133494   ** structures.
   133495   */
   133496   rc = sqlite3Fts3OpenTokenizer(
   133497       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
   133498   if( rc==SQLITE_OK ){
   133499     int ii;
   133500     for(ii=0; rc==SQLITE_OK; ii++){
   133501       const char *zByte;
   133502       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
   133503       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
   133504       if( rc==SQLITE_OK ){
   133505         Fts3PhraseToken *pToken;
   133506 
   133507         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
   133508         if( !p ) goto no_mem;
   133509 
   133510         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
   133511         if( !zTemp ) goto no_mem;
   133512 
   133513         assert( nToken==ii );
   133514         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
   133515         memset(pToken, 0, sizeof(Fts3PhraseToken));
   133516 
   133517         memcpy(&zTemp[nTemp], zByte, nByte);
   133518         nTemp += nByte;
   133519 
   133520         pToken->n = nByte;
   133521         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
   133522         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
   133523         nToken = ii+1;
   133524       }
   133525     }
   133526 
   133527     pModule->xClose(pCursor);
   133528     pCursor = 0;
   133529   }
   133530 
   133531   if( rc==SQLITE_DONE ){
   133532     int jj;
   133533     char *zBuf = 0;
   133534 
   133535     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
   133536     if( !p ) goto no_mem;
   133537     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
   133538     p->eType = FTSQUERY_PHRASE;
   133539     p->pPhrase = (Fts3Phrase *)&p[1];
   133540     p->pPhrase->iColumn = pParse->iDefaultCol;
   133541     p->pPhrase->nToken = nToken;
   133542 
   133543     zBuf = (char *)&p->pPhrase->aToken[nToken];
   133544     if( zTemp ){
   133545       memcpy(zBuf, zTemp, nTemp);
   133546       sqlite3_free(zTemp);
   133547     }else{
   133548       assert( nTemp==0 );
   133549     }
   133550 
   133551     for(jj=0; jj<p->pPhrase->nToken; jj++){
   133552       p->pPhrase->aToken[jj].z = zBuf;
   133553       zBuf += p->pPhrase->aToken[jj].n;
   133554     }
   133555     rc = SQLITE_OK;
   133556   }
   133557 
   133558   *ppExpr = p;
   133559   return rc;
   133560 no_mem:
   133561 
   133562   if( pCursor ){
   133563     pModule->xClose(pCursor);
   133564   }
   133565   sqlite3_free(zTemp);
   133566   sqlite3_free(p);
   133567   *ppExpr = 0;
   133568   return SQLITE_NOMEM;
   133569 }
   133570 
   133571 /*
   133572 ** The output variable *ppExpr is populated with an allocated Fts3Expr
   133573 ** structure, or set to 0 if the end of the input buffer is reached.
   133574 **
   133575 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
   133576 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
   133577 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
   133578 */
   133579 static int getNextNode(
   133580   ParseContext *pParse,                   /* fts3 query parse context */
   133581   const char *z, int n,                   /* Input string */
   133582   Fts3Expr **ppExpr,                      /* OUT: expression */
   133583   int *pnConsumed                         /* OUT: Number of bytes consumed */
   133584 ){
   133585   static const struct Fts3Keyword {
   133586     char *z;                              /* Keyword text */
   133587     unsigned char n;                      /* Length of the keyword */
   133588     unsigned char parenOnly;              /* Only valid in paren mode */
   133589     unsigned char eType;                  /* Keyword code */
   133590   } aKeyword[] = {
   133591     { "OR" ,  2, 0, FTSQUERY_OR   },
   133592     { "AND",  3, 1, FTSQUERY_AND  },
   133593     { "NOT",  3, 1, FTSQUERY_NOT  },
   133594     { "NEAR", 4, 0, FTSQUERY_NEAR }
   133595   };
   133596   int ii;
   133597   int iCol;
   133598   int iColLen;
   133599   int rc;
   133600   Fts3Expr *pRet = 0;
   133601 
   133602   const char *zInput = z;
   133603   int nInput = n;
   133604 
   133605   pParse->isNot = 0;
   133606 
   133607   /* Skip over any whitespace before checking for a keyword, an open or
   133608   ** close bracket, or a quoted string.
   133609   */
   133610   while( nInput>0 && fts3isspace(*zInput) ){
   133611     nInput--;
   133612     zInput++;
   133613   }
   133614   if( nInput==0 ){
   133615     return SQLITE_DONE;
   133616   }
   133617 
   133618   /* See if we are dealing with a keyword. */
   133619   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
   133620     const struct Fts3Keyword *pKey = &aKeyword[ii];
   133621 
   133622     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
   133623       continue;
   133624     }
   133625 
   133626     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
   133627       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
   133628       int nKey = pKey->n;
   133629       char cNext;
   133630 
   133631       /* If this is a "NEAR" keyword, check for an explicit nearness. */
   133632       if( pKey->eType==FTSQUERY_NEAR ){
   133633         assert( nKey==4 );
   133634         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
   133635           nNear = 0;
   133636           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
   133637             nNear = nNear * 10 + (zInput[nKey] - '0');
   133638           }
   133639         }
   133640       }
   133641 
   133642       /* At this point this is probably a keyword. But for that to be true,
   133643       ** the next byte must contain either whitespace, an open or close
   133644       ** parenthesis, a quote character, or EOF.
   133645       */
   133646       cNext = zInput[nKey];
   133647       if( fts3isspace(cNext)
   133648        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
   133649       ){
   133650         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
   133651         if( !pRet ){
   133652           return SQLITE_NOMEM;
   133653         }
   133654         pRet->eType = pKey->eType;
   133655         pRet->nNear = nNear;
   133656         *ppExpr = pRet;
   133657         *pnConsumed = (int)((zInput - z) + nKey);
   133658         return SQLITE_OK;
   133659       }
   133660 
   133661       /* Turns out that wasn't a keyword after all. This happens if the
   133662       ** user has supplied a token such as "ORacle". Continue.
   133663       */
   133664     }
   133665   }
   133666 
   133667   /* See if we are dealing with a quoted phrase. If this is the case, then
   133668   ** search for the closing quote and pass the whole string to getNextString()
   133669   ** for processing. This is easy to do, as fts3 has no syntax for escaping
   133670   ** a quote character embedded in a string.
   133671   */
   133672   if( *zInput=='"' ){
   133673     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
   133674     *pnConsumed = (int)((zInput - z) + ii + 1);
   133675     if( ii==nInput ){
   133676       return SQLITE_ERROR;
   133677     }
   133678     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
   133679   }
   133680 
   133681   if( sqlite3_fts3_enable_parentheses ){
   133682     if( *zInput=='(' ){
   133683       int nConsumed = 0;
   133684       pParse->nNest++;
   133685       rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
   133686       if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
   133687       *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
   133688       return rc;
   133689     }else if( *zInput==')' ){
   133690       pParse->nNest--;
   133691       *pnConsumed = (int)((zInput - z) + 1);
   133692       *ppExpr = 0;
   133693       return SQLITE_DONE;
   133694     }
   133695   }
   133696 
   133697   /* If control flows to this point, this must be a regular token, or
   133698   ** the end of the input. Read a regular token using the sqlite3_tokenizer
   133699   ** interface. Before doing so, figure out if there is an explicit
   133700   ** column specifier for the token.
   133701   **
   133702   ** TODO: Strangely, it is not possible to associate a column specifier
   133703   ** with a quoted phrase, only with a single token. Not sure if this was
   133704   ** an implementation artifact or an intentional decision when fts3 was
   133705   ** first implemented. Whichever it was, this module duplicates the
   133706   ** limitation.
   133707   */
   133708   iCol = pParse->iDefaultCol;
   133709   iColLen = 0;
   133710   for(ii=0; ii<pParse->nCol; ii++){
   133711     const char *zStr = pParse->azCol[ii];
   133712     int nStr = (int)strlen(zStr);
   133713     if( nInput>nStr && zInput[nStr]==':'
   133714      && sqlite3_strnicmp(zStr, zInput, nStr)==0
   133715     ){
   133716       iCol = ii;
   133717       iColLen = (int)((zInput - z) + nStr + 1);
   133718       break;
   133719     }
   133720   }
   133721   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
   133722   *pnConsumed += iColLen;
   133723   return rc;
   133724 }
   133725 
   133726 /*
   133727 ** The argument is an Fts3Expr structure for a binary operator (any type
   133728 ** except an FTSQUERY_PHRASE). Return an integer value representing the
   133729 ** precedence of the operator. Lower values have a higher precedence (i.e.
   133730 ** group more tightly). For example, in the C language, the == operator
   133731 ** groups more tightly than ||, and would therefore have a higher precedence.
   133732 **
   133733 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
   133734 ** is defined), the order of the operators in precedence from highest to
   133735 ** lowest is:
   133736 **
   133737 **   NEAR
   133738 **   NOT
   133739 **   AND (including implicit ANDs)
   133740 **   OR
   133741 **
   133742 ** Note that when using the old query syntax, the OR operator has a higher
   133743 ** precedence than the AND operator.
   133744 */
   133745 static int opPrecedence(Fts3Expr *p){
   133746   assert( p->eType!=FTSQUERY_PHRASE );
   133747   if( sqlite3_fts3_enable_parentheses ){
   133748     return p->eType;
   133749   }else if( p->eType==FTSQUERY_NEAR ){
   133750     return 1;
   133751   }else if( p->eType==FTSQUERY_OR ){
   133752     return 2;
   133753   }
   133754   assert( p->eType==FTSQUERY_AND );
   133755   return 3;
   133756 }
   133757 
   133758 /*
   133759 ** Argument ppHead contains a pointer to the current head of a query
   133760 ** expression tree being parsed. pPrev is the expression node most recently
   133761 ** inserted into the tree. This function adds pNew, which is always a binary
   133762 ** operator node, into the expression tree based on the relative precedence
   133763 ** of pNew and the existing nodes of the tree. This may result in the head
   133764 ** of the tree changing, in which case *ppHead is set to the new root node.
   133765 */
   133766 static void insertBinaryOperator(
   133767   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
   133768   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
   133769   Fts3Expr *pNew           /* New binary node to insert into expression tree */
   133770 ){
   133771   Fts3Expr *pSplit = pPrev;
   133772   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
   133773     pSplit = pSplit->pParent;
   133774   }
   133775 
   133776   if( pSplit->pParent ){
   133777     assert( pSplit->pParent->pRight==pSplit );
   133778     pSplit->pParent->pRight = pNew;
   133779     pNew->pParent = pSplit->pParent;
   133780   }else{
   133781     *ppHead = pNew;
   133782   }
   133783   pNew->pLeft = pSplit;
   133784   pSplit->pParent = pNew;
   133785 }
   133786 
   133787 /*
   133788 ** Parse the fts3 query expression found in buffer z, length n. This function
   133789 ** returns either when the end of the buffer is reached or an unmatched
   133790 ** closing bracket - ')' - is encountered.
   133791 **
   133792 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
   133793 ** parsed form of the expression and *pnConsumed is set to the number of
   133794 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
   133795 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
   133796 */
   133797 static int fts3ExprParse(
   133798   ParseContext *pParse,                   /* fts3 query parse context */
   133799   const char *z, int n,                   /* Text of MATCH query */
   133800   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
   133801   int *pnConsumed                         /* OUT: Number of bytes consumed */
   133802 ){
   133803   Fts3Expr *pRet = 0;
   133804   Fts3Expr *pPrev = 0;
   133805   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
   133806   int nIn = n;
   133807   const char *zIn = z;
   133808   int rc = SQLITE_OK;
   133809   int isRequirePhrase = 1;
   133810 
   133811   while( rc==SQLITE_OK ){
   133812     Fts3Expr *p = 0;
   133813     int nByte = 0;
   133814 
   133815     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
   133816     assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
   133817     if( rc==SQLITE_OK ){
   133818       if( p ){
   133819         int isPhrase;
   133820 
   133821         if( !sqlite3_fts3_enable_parentheses
   133822             && p->eType==FTSQUERY_PHRASE && pParse->isNot
   133823         ){
   133824           /* Create an implicit NOT operator. */
   133825           Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
   133826           if( !pNot ){
   133827             sqlite3Fts3ExprFree(p);
   133828             rc = SQLITE_NOMEM;
   133829             goto exprparse_out;
   133830           }
   133831           pNot->eType = FTSQUERY_NOT;
   133832           pNot->pRight = p;
   133833           p->pParent = pNot;
   133834           if( pNotBranch ){
   133835             pNot->pLeft = pNotBranch;
   133836             pNotBranch->pParent = pNot;
   133837           }
   133838           pNotBranch = pNot;
   133839           p = pPrev;
   133840         }else{
   133841           int eType = p->eType;
   133842           isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
   133843 
   133844           /* The isRequirePhrase variable is set to true if a phrase or
   133845           ** an expression contained in parenthesis is required. If a
   133846           ** binary operator (AND, OR, NOT or NEAR) is encounted when
   133847           ** isRequirePhrase is set, this is a syntax error.
   133848           */
   133849           if( !isPhrase && isRequirePhrase ){
   133850             sqlite3Fts3ExprFree(p);
   133851             rc = SQLITE_ERROR;
   133852             goto exprparse_out;
   133853           }
   133854 
   133855           if( isPhrase && !isRequirePhrase ){
   133856             /* Insert an implicit AND operator. */
   133857             Fts3Expr *pAnd;
   133858             assert( pRet && pPrev );
   133859             pAnd = fts3MallocZero(sizeof(Fts3Expr));
   133860             if( !pAnd ){
   133861               sqlite3Fts3ExprFree(p);
   133862               rc = SQLITE_NOMEM;
   133863               goto exprparse_out;
   133864             }
   133865             pAnd->eType = FTSQUERY_AND;
   133866             insertBinaryOperator(&pRet, pPrev, pAnd);
   133867             pPrev = pAnd;
   133868           }
   133869 
   133870           /* This test catches attempts to make either operand of a NEAR
   133871            ** operator something other than a phrase. For example, either of
   133872            ** the following:
   133873            **
   133874            **    (bracketed expression) NEAR phrase
   133875            **    phrase NEAR (bracketed expression)
   133876            **
   133877            ** Return an error in either case.
   133878            */
   133879           if( pPrev && (
   133880             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
   133881          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
   133882           )){
   133883             sqlite3Fts3ExprFree(p);
   133884             rc = SQLITE_ERROR;
   133885             goto exprparse_out;
   133886           }
   133887 
   133888           if( isPhrase ){
   133889             if( pRet ){
   133890               assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
   133891               pPrev->pRight = p;
   133892               p->pParent = pPrev;
   133893             }else{
   133894               pRet = p;
   133895             }
   133896           }else{
   133897             insertBinaryOperator(&pRet, pPrev, p);
   133898           }
   133899           isRequirePhrase = !isPhrase;
   133900         }
   133901         pPrev = p;
   133902       }
   133903       assert( nByte>0 );
   133904     }
   133905     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
   133906     nIn -= nByte;
   133907     zIn += nByte;
   133908   }
   133909 
   133910   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
   133911     rc = SQLITE_ERROR;
   133912   }
   133913 
   133914   if( rc==SQLITE_DONE ){
   133915     rc = SQLITE_OK;
   133916     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
   133917       if( !pRet ){
   133918         rc = SQLITE_ERROR;
   133919       }else{
   133920         Fts3Expr *pIter = pNotBranch;
   133921         while( pIter->pLeft ){
   133922           pIter = pIter->pLeft;
   133923         }
   133924         pIter->pLeft = pRet;
   133925         pRet->pParent = pIter;
   133926         pRet = pNotBranch;
   133927       }
   133928     }
   133929   }
   133930   *pnConsumed = n - nIn;
   133931 
   133932 exprparse_out:
   133933   if( rc!=SQLITE_OK ){
   133934     sqlite3Fts3ExprFree(pRet);
   133935     sqlite3Fts3ExprFree(pNotBranch);
   133936     pRet = 0;
   133937   }
   133938   *ppExpr = pRet;
   133939   return rc;
   133940 }
   133941 
   133942 /*
   133943 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
   133944 ** as the only argument is more than nMaxDepth.
   133945 */
   133946 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
   133947   int rc = SQLITE_OK;
   133948   if( p ){
   133949     if( nMaxDepth<0 ){
   133950       rc = SQLITE_TOOBIG;
   133951     }else{
   133952       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
   133953       if( rc==SQLITE_OK ){
   133954         rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
   133955       }
   133956     }
   133957   }
   133958   return rc;
   133959 }
   133960 
   133961 /*
   133962 ** This function attempts to transform the expression tree at (*pp) to
   133963 ** an equivalent but more balanced form. The tree is modified in place.
   133964 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
   133965 ** new root expression node.
   133966 **
   133967 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
   133968 **
   133969 ** Otherwise, if an error occurs, an SQLite error code is returned and
   133970 ** expression (*pp) freed.
   133971 */
   133972 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
   133973   int rc = SQLITE_OK;             /* Return code */
   133974   Fts3Expr *pRoot = *pp;          /* Initial root node */
   133975   Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
   133976   int eType = pRoot->eType;       /* Type of node in this tree */
   133977 
   133978   if( nMaxDepth==0 ){
   133979     rc = SQLITE_ERROR;
   133980   }
   133981 
   133982   if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
   133983     Fts3Expr **apLeaf;
   133984     apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
   133985     if( 0==apLeaf ){
   133986       rc = SQLITE_NOMEM;
   133987     }else{
   133988       memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
   133989     }
   133990 
   133991     if( rc==SQLITE_OK ){
   133992       int i;
   133993       Fts3Expr *p;
   133994 
   133995       /* Set $p to point to the left-most leaf in the tree of eType nodes. */
   133996       for(p=pRoot; p->eType==eType; p=p->pLeft){
   133997         assert( p->pParent==0 || p->pParent->pLeft==p );
   133998         assert( p->pLeft && p->pRight );
   133999       }
   134000 
   134001       /* This loop runs once for each leaf in the tree of eType nodes. */
   134002       while( 1 ){
   134003         int iLvl;
   134004         Fts3Expr *pParent = p->pParent;     /* Current parent of p */
   134005 
   134006         assert( pParent==0 || pParent->pLeft==p );
   134007         p->pParent = 0;
   134008         if( pParent ){
   134009           pParent->pLeft = 0;
   134010         }else{
   134011           pRoot = 0;
   134012         }
   134013         rc = fts3ExprBalance(&p, nMaxDepth-1);
   134014         if( rc!=SQLITE_OK ) break;
   134015 
   134016         for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
   134017           if( apLeaf[iLvl]==0 ){
   134018             apLeaf[iLvl] = p;
   134019             p = 0;
   134020           }else{
   134021             assert( pFree );
   134022             pFree->pLeft = apLeaf[iLvl];
   134023             pFree->pRight = p;
   134024             pFree->pLeft->pParent = pFree;
   134025             pFree->pRight->pParent = pFree;
   134026 
   134027             p = pFree;
   134028             pFree = pFree->pParent;
   134029             p->pParent = 0;
   134030             apLeaf[iLvl] = 0;
   134031           }
   134032         }
   134033         if( p ){
   134034           sqlite3Fts3ExprFree(p);
   134035           rc = SQLITE_TOOBIG;
   134036           break;
   134037         }
   134038 
   134039         /* If that was the last leaf node, break out of the loop */
   134040         if( pParent==0 ) break;
   134041 
   134042         /* Set $p to point to the next leaf in the tree of eType nodes */
   134043         for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
   134044 
   134045         /* Remove pParent from the original tree. */
   134046         assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
   134047         pParent->pRight->pParent = pParent->pParent;
   134048         if( pParent->pParent ){
   134049           pParent->pParent->pLeft = pParent->pRight;
   134050         }else{
   134051           assert( pParent==pRoot );
   134052           pRoot = pParent->pRight;
   134053         }
   134054 
   134055         /* Link pParent into the free node list. It will be used as an
   134056         ** internal node of the new tree.  */
   134057         pParent->pParent = pFree;
   134058         pFree = pParent;
   134059       }
   134060 
   134061       if( rc==SQLITE_OK ){
   134062         p = 0;
   134063         for(i=0; i<nMaxDepth; i++){
   134064           if( apLeaf[i] ){
   134065             if( p==0 ){
   134066               p = apLeaf[i];
   134067               p->pParent = 0;
   134068             }else{
   134069               assert( pFree!=0 );
   134070               pFree->pRight = p;
   134071               pFree->pLeft = apLeaf[i];
   134072               pFree->pLeft->pParent = pFree;
   134073               pFree->pRight->pParent = pFree;
   134074 
   134075               p = pFree;
   134076               pFree = pFree->pParent;
   134077               p->pParent = 0;
   134078             }
   134079           }
   134080         }
   134081         pRoot = p;
   134082       }else{
   134083         /* An error occurred. Delete the contents of the apLeaf[] array
   134084         ** and pFree list. Everything else is cleaned up by the call to
   134085         ** sqlite3Fts3ExprFree(pRoot) below.  */
   134086         Fts3Expr *pDel;
   134087         for(i=0; i<nMaxDepth; i++){
   134088           sqlite3Fts3ExprFree(apLeaf[i]);
   134089         }
   134090         while( (pDel=pFree)!=0 ){
   134091           pFree = pDel->pParent;
   134092           sqlite3_free(pDel);
   134093         }
   134094       }
   134095 
   134096       assert( pFree==0 );
   134097       sqlite3_free( apLeaf );
   134098     }
   134099   }
   134100 
   134101   if( rc!=SQLITE_OK ){
   134102     sqlite3Fts3ExprFree(pRoot);
   134103     pRoot = 0;
   134104   }
   134105   *pp = pRoot;
   134106   return rc;
   134107 }
   134108 
   134109 /*
   134110 ** This function is similar to sqlite3Fts3ExprParse(), with the following
   134111 ** differences:
   134112 **
   134113 **   1. It does not do expression rebalancing.
   134114 **   2. It does not check that the expression does not exceed the
   134115 **      maximum allowable depth.
   134116 **   3. Even if it fails, *ppExpr may still be set to point to an
   134117 **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
   134118 **      in this case.
   134119 */
   134120 static int fts3ExprParseUnbalanced(
   134121   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   134122   int iLangid,                        /* Language id for tokenizer */
   134123   char **azCol,                       /* Array of column names for fts3 table */
   134124   int bFts4,                          /* True to allow FTS4-only syntax */
   134125   int nCol,                           /* Number of entries in azCol[] */
   134126   int iDefaultCol,                    /* Default column to query */
   134127   const char *z, int n,               /* Text of MATCH query */
   134128   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
   134129 ){
   134130   int nParsed;
   134131   int rc;
   134132   ParseContext sParse;
   134133 
   134134   memset(&sParse, 0, sizeof(ParseContext));
   134135   sParse.pTokenizer = pTokenizer;
   134136   sParse.iLangid = iLangid;
   134137   sParse.azCol = (const char **)azCol;
   134138   sParse.nCol = nCol;
   134139   sParse.iDefaultCol = iDefaultCol;
   134140   sParse.bFts4 = bFts4;
   134141   if( z==0 ){
   134142     *ppExpr = 0;
   134143     return SQLITE_OK;
   134144   }
   134145   if( n<0 ){
   134146     n = (int)strlen(z);
   134147   }
   134148   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
   134149   assert( rc==SQLITE_OK || *ppExpr==0 );
   134150 
   134151   /* Check for mismatched parenthesis */
   134152   if( rc==SQLITE_OK && sParse.nNest ){
   134153     rc = SQLITE_ERROR;
   134154   }
   134155 
   134156   return rc;
   134157 }
   134158 
   134159 /*
   134160 ** Parameters z and n contain a pointer to and length of a buffer containing
   134161 ** an fts3 query expression, respectively. This function attempts to parse the
   134162 ** query expression and create a tree of Fts3Expr structures representing the
   134163 ** parsed expression. If successful, *ppExpr is set to point to the head
   134164 ** of the parsed expression tree and SQLITE_OK is returned. If an error
   134165 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
   134166 ** error) is returned and *ppExpr is set to 0.
   134167 **
   134168 ** If parameter n is a negative number, then z is assumed to point to a
   134169 ** nul-terminated string and the length is determined using strlen().
   134170 **
   134171 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
   134172 ** use to normalize query tokens while parsing the expression. The azCol[]
   134173 ** array, which is assumed to contain nCol entries, should contain the names
   134174 ** of each column in the target fts3 table, in order from left to right.
   134175 ** Column names must be nul-terminated strings.
   134176 **
   134177 ** The iDefaultCol parameter should be passed the index of the table column
   134178 ** that appears on the left-hand-side of the MATCH operator (the default
   134179 ** column to match against for tokens for which a column name is not explicitly
   134180 ** specified as part of the query string), or -1 if tokens may by default
   134181 ** match any table column.
   134182 */
   134183 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
   134184   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   134185   int iLangid,                        /* Language id for tokenizer */
   134186   char **azCol,                       /* Array of column names for fts3 table */
   134187   int bFts4,                          /* True to allow FTS4-only syntax */
   134188   int nCol,                           /* Number of entries in azCol[] */
   134189   int iDefaultCol,                    /* Default column to query */
   134190   const char *z, int n,               /* Text of MATCH query */
   134191   Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
   134192   char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
   134193 ){
   134194   int rc = fts3ExprParseUnbalanced(
   134195       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
   134196   );
   134197 
   134198   /* Rebalance the expression. And check that its depth does not exceed
   134199   ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
   134200   if( rc==SQLITE_OK && *ppExpr ){
   134201     rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
   134202     if( rc==SQLITE_OK ){
   134203       rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
   134204     }
   134205   }
   134206 
   134207   if( rc!=SQLITE_OK ){
   134208     sqlite3Fts3ExprFree(*ppExpr);
   134209     *ppExpr = 0;
   134210     if( rc==SQLITE_TOOBIG ){
   134211       *pzErr = sqlite3_mprintf(
   134212           "FTS expression tree is too large (maximum depth %d)",
   134213           SQLITE_FTS3_MAX_EXPR_DEPTH
   134214       );
   134215       rc = SQLITE_ERROR;
   134216     }else if( rc==SQLITE_ERROR ){
   134217       *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
   134218     }
   134219   }
   134220 
   134221   return rc;
   134222 }
   134223 
   134224 /*
   134225 ** Free a single node of an expression tree.
   134226 */
   134227 static void fts3FreeExprNode(Fts3Expr *p){
   134228   assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
   134229   sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
   134230   sqlite3_free(p->aMI);
   134231   sqlite3_free(p);
   134232 }
   134233 
   134234 /*
   134235 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
   134236 **
   134237 ** This function would be simpler if it recursively called itself. But
   134238 ** that would mean passing a sufficiently large expression to ExprParse()
   134239 ** could cause a stack overflow.
   134240 */
   134241 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
   134242   Fts3Expr *p;
   134243   assert( pDel==0 || pDel->pParent==0 );
   134244   for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
   134245     assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
   134246   }
   134247   while( p ){
   134248     Fts3Expr *pParent = p->pParent;
   134249     fts3FreeExprNode(p);
   134250     if( pParent && p==pParent->pLeft && pParent->pRight ){
   134251       p = pParent->pRight;
   134252       while( p && (p->pLeft || p->pRight) ){
   134253         assert( p==p->pParent->pRight || p==p->pParent->pLeft );
   134254         p = (p->pLeft ? p->pLeft : p->pRight);
   134255       }
   134256     }else{
   134257       p = pParent;
   134258     }
   134259   }
   134260 }
   134261 
   134262 /****************************************************************************
   134263 *****************************************************************************
   134264 ** Everything after this point is just test code.
   134265 */
   134266 
   134267 #ifdef SQLITE_TEST
   134268 
   134269 /* #include <stdio.h> */
   134270 
   134271 /*
   134272 ** Function to query the hash-table of tokenizers (see README.tokenizers).
   134273 */
   134274 static int queryTestTokenizer(
   134275   sqlite3 *db,
   134276   const char *zName,
   134277   const sqlite3_tokenizer_module **pp
   134278 ){
   134279   int rc;
   134280   sqlite3_stmt *pStmt;
   134281   const char zSql[] = "SELECT fts3_tokenizer(?)";
   134282 
   134283   *pp = 0;
   134284   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   134285   if( rc!=SQLITE_OK ){
   134286     return rc;
   134287   }
   134288 
   134289   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   134290   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   134291     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   134292       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   134293     }
   134294   }
   134295 
   134296   return sqlite3_finalize(pStmt);
   134297 }
   134298 
   134299 /*
   134300 ** Return a pointer to a buffer containing a text representation of the
   134301 ** expression passed as the first argument. The buffer is obtained from
   134302 ** sqlite3_malloc(). It is the responsibility of the caller to use
   134303 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
   134304 ** NULL is returned.
   134305 **
   134306 ** If the second argument is not NULL, then its contents are prepended to
   134307 ** the returned expression text and then freed using sqlite3_free().
   134308 */
   134309 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
   134310   if( pExpr==0 ){
   134311     return sqlite3_mprintf("");
   134312   }
   134313   switch( pExpr->eType ){
   134314     case FTSQUERY_PHRASE: {
   134315       Fts3Phrase *pPhrase = pExpr->pPhrase;
   134316       int i;
   134317       zBuf = sqlite3_mprintf(
   134318           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
   134319       for(i=0; zBuf && i<pPhrase->nToken; i++){
   134320         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
   134321             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
   134322             (pPhrase->aToken[i].isPrefix?"+":"")
   134323         );
   134324       }
   134325       return zBuf;
   134326     }
   134327 
   134328     case FTSQUERY_NEAR:
   134329       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
   134330       break;
   134331     case FTSQUERY_NOT:
   134332       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
   134333       break;
   134334     case FTSQUERY_AND:
   134335       zBuf = sqlite3_mprintf("%zAND ", zBuf);
   134336       break;
   134337     case FTSQUERY_OR:
   134338       zBuf = sqlite3_mprintf("%zOR ", zBuf);
   134339       break;
   134340   }
   134341 
   134342   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
   134343   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
   134344   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
   134345 
   134346   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
   134347   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
   134348 
   134349   return zBuf;
   134350 }
   134351 
   134352 /*
   134353 ** This is the implementation of a scalar SQL function used to test the
   134354 ** expression parser. It should be called as follows:
   134355 **
   134356 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
   134357 **
   134358 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
   134359 ** to parse the query expression (see README.tokenizers). The second argument
   134360 ** is the query expression to parse. Each subsequent argument is the name
   134361 ** of a column of the fts3 table that the query expression may refer to.
   134362 ** For example:
   134363 **
   134364 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
   134365 */
   134366 static void fts3ExprTest(
   134367   sqlite3_context *context,
   134368   int argc,
   134369   sqlite3_value **argv
   134370 ){
   134371   sqlite3_tokenizer_module const *pModule = 0;
   134372   sqlite3_tokenizer *pTokenizer = 0;
   134373   int rc;
   134374   char **azCol = 0;
   134375   const char *zExpr;
   134376   int nExpr;
   134377   int nCol;
   134378   int ii;
   134379   Fts3Expr *pExpr;
   134380   char *zBuf = 0;
   134381   sqlite3 *db = sqlite3_context_db_handle(context);
   134382 
   134383   if( argc<3 ){
   134384     sqlite3_result_error(context,
   134385         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
   134386     );
   134387     return;
   134388   }
   134389 
   134390   rc = queryTestTokenizer(db,
   134391                           (const char *)sqlite3_value_text(argv[0]), &pModule);
   134392   if( rc==SQLITE_NOMEM ){
   134393     sqlite3_result_error_nomem(context);
   134394     goto exprtest_out;
   134395   }else if( !pModule ){
   134396     sqlite3_result_error(context, "No such tokenizer module", -1);
   134397     goto exprtest_out;
   134398   }
   134399 
   134400   rc = pModule->xCreate(0, 0, &pTokenizer);
   134401   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   134402   if( rc==SQLITE_NOMEM ){
   134403     sqlite3_result_error_nomem(context);
   134404     goto exprtest_out;
   134405   }
   134406   pTokenizer->pModule = pModule;
   134407 
   134408   zExpr = (const char *)sqlite3_value_text(argv[1]);
   134409   nExpr = sqlite3_value_bytes(argv[1]);
   134410   nCol = argc-2;
   134411   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
   134412   if( !azCol ){
   134413     sqlite3_result_error_nomem(context);
   134414     goto exprtest_out;
   134415   }
   134416   for(ii=0; ii<nCol; ii++){
   134417     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
   134418   }
   134419 
   134420   if( sqlite3_user_data(context) ){
   134421     char *zDummy = 0;
   134422     rc = sqlite3Fts3ExprParse(
   134423         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
   134424     );
   134425     assert( rc==SQLITE_OK || pExpr==0 );
   134426     sqlite3_free(zDummy);
   134427   }else{
   134428     rc = fts3ExprParseUnbalanced(
   134429         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
   134430     );
   134431   }
   134432 
   134433   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
   134434     sqlite3Fts3ExprFree(pExpr);
   134435     sqlite3_result_error(context, "Error parsing expression", -1);
   134436   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
   134437     sqlite3_result_error_nomem(context);
   134438   }else{
   134439     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   134440     sqlite3_free(zBuf);
   134441   }
   134442 
   134443   sqlite3Fts3ExprFree(pExpr);
   134444 
   134445 exprtest_out:
   134446   if( pModule && pTokenizer ){
   134447     rc = pModule->xDestroy(pTokenizer);
   134448   }
   134449   sqlite3_free(azCol);
   134450 }
   134451 
   134452 /*
   134453 ** Register the query expression parser test function fts3_exprtest()
   134454 ** with database connection db.
   134455 */
   134456 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
   134457   int rc = sqlite3_create_function(
   134458       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
   134459   );
   134460   if( rc==SQLITE_OK ){
   134461     rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
   134462         -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
   134463     );
   134464   }
   134465   return rc;
   134466 }
   134467 
   134468 #endif
   134469 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   134470 
   134471 /************** End of fts3_expr.c *******************************************/
   134472 /************** Begin file fts3_hash.c ***************************************/
   134473 /*
   134474 ** 2001 September 22
   134475 **
   134476 ** The author disclaims copyright to this source code.  In place of
   134477 ** a legal notice, here is a blessing:
   134478 **
   134479 **    May you do good and not evil.
   134480 **    May you find forgiveness for yourself and forgive others.
   134481 **    May you share freely, never taking more than you give.
   134482 **
   134483 *************************************************************************
   134484 ** This is the implementation of generic hash-tables used in SQLite.
   134485 ** We've modified it slightly to serve as a standalone hash table
   134486 ** implementation for the full-text indexing module.
   134487 */
   134488 
   134489 /*
   134490 ** The code in this file is only compiled if:
   134491 **
   134492 **     * The FTS3 module is being built as an extension
   134493 **       (in which case SQLITE_CORE is not defined), or
   134494 **
   134495 **     * The FTS3 module is being built into the core of
   134496 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   134497 */
   134498 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   134499 
   134500 /* #include <assert.h> */
   134501 /* #include <stdlib.h> */
   134502 /* #include <string.h> */
   134503 
   134504 
   134505 /*
   134506 ** Malloc and Free functions
   134507 */
   134508 static void *fts3HashMalloc(int n){
   134509   void *p = sqlite3_malloc(n);
   134510   if( p ){
   134511     memset(p, 0, n);
   134512   }
   134513   return p;
   134514 }
   134515 static void fts3HashFree(void *p){
   134516   sqlite3_free(p);
   134517 }
   134518 
   134519 /* Turn bulk memory into a hash table object by initializing the
   134520 ** fields of the Hash structure.
   134521 **
   134522 ** "pNew" is a pointer to the hash table that is to be initialized.
   134523 ** keyClass is one of the constants
   134524 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
   134525 ** determines what kind of key the hash table will use.  "copyKey" is
   134526 ** true if the hash table should make its own private copy of keys and
   134527 ** false if it should just use the supplied pointer.
   134528 */
   134529 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
   134530   assert( pNew!=0 );
   134531   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
   134532   pNew->keyClass = keyClass;
   134533   pNew->copyKey = copyKey;
   134534   pNew->first = 0;
   134535   pNew->count = 0;
   134536   pNew->htsize = 0;
   134537   pNew->ht = 0;
   134538 }
   134539 
   134540 /* Remove all entries from a hash table.  Reclaim all memory.
   134541 ** Call this routine to delete a hash table or to reset a hash table
   134542 ** to the empty state.
   134543 */
   134544 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
   134545   Fts3HashElem *elem;         /* For looping over all elements of the table */
   134546 
   134547   assert( pH!=0 );
   134548   elem = pH->first;
   134549   pH->first = 0;
   134550   fts3HashFree(pH->ht);
   134551   pH->ht = 0;
   134552   pH->htsize = 0;
   134553   while( elem ){
   134554     Fts3HashElem *next_elem = elem->next;
   134555     if( pH->copyKey && elem->pKey ){
   134556       fts3HashFree(elem->pKey);
   134557     }
   134558     fts3HashFree(elem);
   134559     elem = next_elem;
   134560   }
   134561   pH->count = 0;
   134562 }
   134563 
   134564 /*
   134565 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
   134566 */
   134567 static int fts3StrHash(const void *pKey, int nKey){
   134568   const char *z = (const char *)pKey;
   134569   unsigned h = 0;
   134570   if( nKey<=0 ) nKey = (int) strlen(z);
   134571   while( nKey > 0  ){
   134572     h = (h<<3) ^ h ^ *z++;
   134573     nKey--;
   134574   }
   134575   return (int)(h & 0x7fffffff);
   134576 }
   134577 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   134578   if( n1!=n2 ) return 1;
   134579   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
   134580 }
   134581 
   134582 /*
   134583 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
   134584 */
   134585 static int fts3BinHash(const void *pKey, int nKey){
   134586   int h = 0;
   134587   const char *z = (const char *)pKey;
   134588   while( nKey-- > 0 ){
   134589     h = (h<<3) ^ h ^ *(z++);
   134590   }
   134591   return h & 0x7fffffff;
   134592 }
   134593 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   134594   if( n1!=n2 ) return 1;
   134595   return memcmp(pKey1,pKey2,n1);
   134596 }
   134597 
   134598 /*
   134599 ** Return a pointer to the appropriate hash function given the key class.
   134600 **
   134601 ** The C syntax in this function definition may be unfamilar to some
   134602 ** programmers, so we provide the following additional explanation:
   134603 **
   134604 ** The name of the function is "ftsHashFunction".  The function takes a
   134605 ** single parameter "keyClass".  The return value of ftsHashFunction()
   134606 ** is a pointer to another function.  Specifically, the return value
   134607 ** of ftsHashFunction() is a pointer to a function that takes two parameters
   134608 ** with types "const void*" and "int" and returns an "int".
   134609 */
   134610 static int (*ftsHashFunction(int keyClass))(const void*,int){
   134611   if( keyClass==FTS3_HASH_STRING ){
   134612     return &fts3StrHash;
   134613   }else{
   134614     assert( keyClass==FTS3_HASH_BINARY );
   134615     return &fts3BinHash;
   134616   }
   134617 }
   134618 
   134619 /*
   134620 ** Return a pointer to the appropriate hash function given the key class.
   134621 **
   134622 ** For help in interpreted the obscure C code in the function definition,
   134623 ** see the header comment on the previous function.
   134624 */
   134625 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
   134626   if( keyClass==FTS3_HASH_STRING ){
   134627     return &fts3StrCompare;
   134628   }else{
   134629     assert( keyClass==FTS3_HASH_BINARY );
   134630     return &fts3BinCompare;
   134631   }
   134632 }
   134633 
   134634 /* Link an element into the hash table
   134635 */
   134636 static void fts3HashInsertElement(
   134637   Fts3Hash *pH,            /* The complete hash table */
   134638   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
   134639   Fts3HashElem *pNew       /* The element to be inserted */
   134640 ){
   134641   Fts3HashElem *pHead;     /* First element already in pEntry */
   134642   pHead = pEntry->chain;
   134643   if( pHead ){
   134644     pNew->next = pHead;
   134645     pNew->prev = pHead->prev;
   134646     if( pHead->prev ){ pHead->prev->next = pNew; }
   134647     else             { pH->first = pNew; }
   134648     pHead->prev = pNew;
   134649   }else{
   134650     pNew->next = pH->first;
   134651     if( pH->first ){ pH->first->prev = pNew; }
   134652     pNew->prev = 0;
   134653     pH->first = pNew;
   134654   }
   134655   pEntry->count++;
   134656   pEntry->chain = pNew;
   134657 }
   134658 
   134659 
   134660 /* Resize the hash table so that it cantains "new_size" buckets.
   134661 ** "new_size" must be a power of 2.  The hash table might fail
   134662 ** to resize if sqliteMalloc() fails.
   134663 **
   134664 ** Return non-zero if a memory allocation error occurs.
   134665 */
   134666 static int fts3Rehash(Fts3Hash *pH, int new_size){
   134667   struct _fts3ht *new_ht;          /* The new hash table */
   134668   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
   134669   int (*xHash)(const void*,int);   /* The hash function */
   134670 
   134671   assert( (new_size & (new_size-1))==0 );
   134672   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
   134673   if( new_ht==0 ) return 1;
   134674   fts3HashFree(pH->ht);
   134675   pH->ht = new_ht;
   134676   pH->htsize = new_size;
   134677   xHash = ftsHashFunction(pH->keyClass);
   134678   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   134679     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
   134680     next_elem = elem->next;
   134681     fts3HashInsertElement(pH, &new_ht[h], elem);
   134682   }
   134683   return 0;
   134684 }
   134685 
   134686 /* This function (for internal use only) locates an element in an
   134687 ** hash table that matches the given key.  The hash for this key has
   134688 ** already been computed and is passed as the 4th parameter.
   134689 */
   134690 static Fts3HashElem *fts3FindElementByHash(
   134691   const Fts3Hash *pH, /* The pH to be searched */
   134692   const void *pKey,   /* The key we are searching for */
   134693   int nKey,
   134694   int h               /* The hash for this key. */
   134695 ){
   134696   Fts3HashElem *elem;            /* Used to loop thru the element list */
   134697   int count;                     /* Number of elements left to test */
   134698   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
   134699 
   134700   if( pH->ht ){
   134701     struct _fts3ht *pEntry = &pH->ht[h];
   134702     elem = pEntry->chain;
   134703     count = pEntry->count;
   134704     xCompare = ftsCompareFunction(pH->keyClass);
   134705     while( count-- && elem ){
   134706       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
   134707         return elem;
   134708       }
   134709       elem = elem->next;
   134710     }
   134711   }
   134712   return 0;
   134713 }
   134714 
   134715 /* Remove a single entry from the hash table given a pointer to that
   134716 ** element and a hash on the element's key.
   134717 */
   134718 static void fts3RemoveElementByHash(
   134719   Fts3Hash *pH,         /* The pH containing "elem" */
   134720   Fts3HashElem* elem,   /* The element to be removed from the pH */
   134721   int h                 /* Hash value for the element */
   134722 ){
   134723   struct _fts3ht *pEntry;
   134724   if( elem->prev ){
   134725     elem->prev->next = elem->next;
   134726   }else{
   134727     pH->first = elem->next;
   134728   }
   134729   if( elem->next ){
   134730     elem->next->prev = elem->prev;
   134731   }
   134732   pEntry = &pH->ht[h];
   134733   if( pEntry->chain==elem ){
   134734     pEntry->chain = elem->next;
   134735   }
   134736   pEntry->count--;
   134737   if( pEntry->count<=0 ){
   134738     pEntry->chain = 0;
   134739   }
   134740   if( pH->copyKey && elem->pKey ){
   134741     fts3HashFree(elem->pKey);
   134742   }
   134743   fts3HashFree( elem );
   134744   pH->count--;
   134745   if( pH->count<=0 ){
   134746     assert( pH->first==0 );
   134747     assert( pH->count==0 );
   134748     fts3HashClear(pH);
   134749   }
   134750 }
   134751 
   134752 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
   134753   const Fts3Hash *pH,
   134754   const void *pKey,
   134755   int nKey
   134756 ){
   134757   int h;                          /* A hash on key */
   134758   int (*xHash)(const void*,int);  /* The hash function */
   134759 
   134760   if( pH==0 || pH->ht==0 ) return 0;
   134761   xHash = ftsHashFunction(pH->keyClass);
   134762   assert( xHash!=0 );
   134763   h = (*xHash)(pKey,nKey);
   134764   assert( (pH->htsize & (pH->htsize-1))==0 );
   134765   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
   134766 }
   134767 
   134768 /*
   134769 ** Attempt to locate an element of the hash table pH with a key
   134770 ** that matches pKey,nKey.  Return the data for this element if it is
   134771 ** found, or NULL if there is no match.
   134772 */
   134773 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
   134774   Fts3HashElem *pElem;            /* The element that matches key (if any) */
   134775 
   134776   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
   134777   return pElem ? pElem->data : 0;
   134778 }
   134779 
   134780 /* Insert an element into the hash table pH.  The key is pKey,nKey
   134781 ** and the data is "data".
   134782 **
   134783 ** If no element exists with a matching key, then a new
   134784 ** element is created.  A copy of the key is made if the copyKey
   134785 ** flag is set.  NULL is returned.
   134786 **
   134787 ** If another element already exists with the same key, then the
   134788 ** new data replaces the old data and the old data is returned.
   134789 ** The key is not copied in this instance.  If a malloc fails, then
   134790 ** the new data is returned and the hash table is unchanged.
   134791 **
   134792 ** If the "data" parameter to this function is NULL, then the
   134793 ** element corresponding to "key" is removed from the hash table.
   134794 */
   134795 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
   134796   Fts3Hash *pH,        /* The hash table to insert into */
   134797   const void *pKey,    /* The key */
   134798   int nKey,            /* Number of bytes in the key */
   134799   void *data           /* The data */
   134800 ){
   134801   int hraw;                 /* Raw hash value of the key */
   134802   int h;                    /* the hash of the key modulo hash table size */
   134803   Fts3HashElem *elem;       /* Used to loop thru the element list */
   134804   Fts3HashElem *new_elem;   /* New element added to the pH */
   134805   int (*xHash)(const void*,int);  /* The hash function */
   134806 
   134807   assert( pH!=0 );
   134808   xHash = ftsHashFunction(pH->keyClass);
   134809   assert( xHash!=0 );
   134810   hraw = (*xHash)(pKey, nKey);
   134811   assert( (pH->htsize & (pH->htsize-1))==0 );
   134812   h = hraw & (pH->htsize-1);
   134813   elem = fts3FindElementByHash(pH,pKey,nKey,h);
   134814   if( elem ){
   134815     void *old_data = elem->data;
   134816     if( data==0 ){
   134817       fts3RemoveElementByHash(pH,elem,h);
   134818     }else{
   134819       elem->data = data;
   134820     }
   134821     return old_data;
   134822   }
   134823   if( data==0 ) return 0;
   134824   if( (pH->htsize==0 && fts3Rehash(pH,8))
   134825    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
   134826   ){
   134827     pH->count = 0;
   134828     return data;
   134829   }
   134830   assert( pH->htsize>0 );
   134831   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
   134832   if( new_elem==0 ) return data;
   134833   if( pH->copyKey && pKey!=0 ){
   134834     new_elem->pKey = fts3HashMalloc( nKey );
   134835     if( new_elem->pKey==0 ){
   134836       fts3HashFree(new_elem);
   134837       return data;
   134838     }
   134839     memcpy((void*)new_elem->pKey, pKey, nKey);
   134840   }else{
   134841     new_elem->pKey = (void*)pKey;
   134842   }
   134843   new_elem->nKey = nKey;
   134844   pH->count++;
   134845   assert( pH->htsize>0 );
   134846   assert( (pH->htsize & (pH->htsize-1))==0 );
   134847   h = hraw & (pH->htsize-1);
   134848   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
   134849   new_elem->data = data;
   134850   return 0;
   134851 }
   134852 
   134853 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   134854 
   134855 /************** End of fts3_hash.c *******************************************/
   134856 /************** Begin file fts3_porter.c *************************************/
   134857 /*
   134858 ** 2006 September 30
   134859 **
   134860 ** The author disclaims copyright to this source code.  In place of
   134861 ** a legal notice, here is a blessing:
   134862 **
   134863 **    May you do good and not evil.
   134864 **    May you find forgiveness for yourself and forgive others.
   134865 **    May you share freely, never taking more than you give.
   134866 **
   134867 *************************************************************************
   134868 ** Implementation of the full-text-search tokenizer that implements
   134869 ** a Porter stemmer.
   134870 */
   134871 
   134872 /*
   134873 ** The code in this file is only compiled if:
   134874 **
   134875 **     * The FTS3 module is being built as an extension
   134876 **       (in which case SQLITE_CORE is not defined), or
   134877 **
   134878 **     * The FTS3 module is being built into the core of
   134879 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   134880 */
   134881 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   134882 
   134883 /* #include <assert.h> */
   134884 /* #include <stdlib.h> */
   134885 /* #include <stdio.h> */
   134886 /* #include <string.h> */
   134887 
   134888 
   134889 /*
   134890 ** Class derived from sqlite3_tokenizer
   134891 */
   134892 typedef struct porter_tokenizer {
   134893   sqlite3_tokenizer base;      /* Base class */
   134894 } porter_tokenizer;
   134895 
   134896 /*
   134897 ** Class derived from sqlite3_tokenizer_cursor
   134898 */
   134899 typedef struct porter_tokenizer_cursor {
   134900   sqlite3_tokenizer_cursor base;
   134901   const char *zInput;          /* input we are tokenizing */
   134902   int nInput;                  /* size of the input */
   134903   int iOffset;                 /* current position in zInput */
   134904   int iToken;                  /* index of next token to be returned */
   134905   char *zToken;                /* storage for current token */
   134906   int nAllocated;              /* space allocated to zToken buffer */
   134907 } porter_tokenizer_cursor;
   134908 
   134909 
   134910 /*
   134911 ** Create a new tokenizer instance.
   134912 */
   134913 static int porterCreate(
   134914   int argc, const char * const *argv,
   134915   sqlite3_tokenizer **ppTokenizer
   134916 ){
   134917   porter_tokenizer *t;
   134918 
   134919   UNUSED_PARAMETER(argc);
   134920   UNUSED_PARAMETER(argv);
   134921 
   134922   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
   134923   if( t==NULL ) return SQLITE_NOMEM;
   134924   memset(t, 0, sizeof(*t));
   134925   *ppTokenizer = &t->base;
   134926   return SQLITE_OK;
   134927 }
   134928 
   134929 /*
   134930 ** Destroy a tokenizer
   134931 */
   134932 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
   134933   sqlite3_free(pTokenizer);
   134934   return SQLITE_OK;
   134935 }
   134936 
   134937 /*
   134938 ** Prepare to begin tokenizing a particular string.  The input
   134939 ** string to be tokenized is zInput[0..nInput-1].  A cursor
   134940 ** used to incrementally tokenize this string is returned in
   134941 ** *ppCursor.
   134942 */
   134943 static int porterOpen(
   134944   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   134945   const char *zInput, int nInput,        /* String to be tokenized */
   134946   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   134947 ){
   134948   porter_tokenizer_cursor *c;
   134949 
   134950   UNUSED_PARAMETER(pTokenizer);
   134951 
   134952   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   134953   if( c==NULL ) return SQLITE_NOMEM;
   134954 
   134955   c->zInput = zInput;
   134956   if( zInput==0 ){
   134957     c->nInput = 0;
   134958   }else if( nInput<0 ){
   134959     c->nInput = (int)strlen(zInput);
   134960   }else{
   134961     c->nInput = nInput;
   134962   }
   134963   c->iOffset = 0;                 /* start tokenizing at the beginning */
   134964   c->iToken = 0;
   134965   c->zToken = NULL;               /* no space allocated, yet. */
   134966   c->nAllocated = 0;
   134967 
   134968   *ppCursor = &c->base;
   134969   return SQLITE_OK;
   134970 }
   134971 
   134972 /*
   134973 ** Close a tokenization cursor previously opened by a call to
   134974 ** porterOpen() above.
   134975 */
   134976 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
   134977   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   134978   sqlite3_free(c->zToken);
   134979   sqlite3_free(c);
   134980   return SQLITE_OK;
   134981 }
   134982 /*
   134983 ** Vowel or consonant
   134984 */
   134985 static const char cType[] = {
   134986    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   134987    1, 1, 1, 2, 1
   134988 };
   134989 
   134990 /*
   134991 ** isConsonant() and isVowel() determine if their first character in
   134992 ** the string they point to is a consonant or a vowel, according
   134993 ** to Porter ruls.
   134994 **
   134995 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
   134996 ** 'Y' is a consonant unless it follows another consonant,
   134997 ** in which case it is a vowel.
   134998 **
   134999 ** In these routine, the letters are in reverse order.  So the 'y' rule
   135000 ** is that 'y' is a consonant unless it is followed by another
   135001 ** consonent.
   135002 */
   135003 static int isVowel(const char*);
   135004 static int isConsonant(const char *z){
   135005   int j;
   135006   char x = *z;
   135007   if( x==0 ) return 0;
   135008   assert( x>='a' && x<='z' );
   135009   j = cType[x-'a'];
   135010   if( j<2 ) return j;
   135011   return z[1]==0 || isVowel(z + 1);
   135012 }
   135013 static int isVowel(const char *z){
   135014   int j;
   135015   char x = *z;
   135016   if( x==0 ) return 0;
   135017   assert( x>='a' && x<='z' );
   135018   j = cType[x-'a'];
   135019   if( j<2 ) return 1-j;
   135020   return isConsonant(z + 1);
   135021 }
   135022 
   135023 /*
   135024 ** Let any sequence of one or more vowels be represented by V and let
   135025 ** C be sequence of one or more consonants.  Then every word can be
   135026 ** represented as:
   135027 **
   135028 **           [C] (VC){m} [V]
   135029 **
   135030 ** In prose:  A word is an optional consonant followed by zero or
   135031 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
   135032 ** number of vowel consonant pairs.  This routine computes the value
   135033 ** of m for the first i bytes of a word.
   135034 **
   135035 ** Return true if the m-value for z is 1 or more.  In other words,
   135036 ** return true if z contains at least one vowel that is followed
   135037 ** by a consonant.
   135038 **
   135039 ** In this routine z[] is in reverse order.  So we are really looking
   135040 ** for an instance of of a consonant followed by a vowel.
   135041 */
   135042 static int m_gt_0(const char *z){
   135043   while( isVowel(z) ){ z++; }
   135044   if( *z==0 ) return 0;
   135045   while( isConsonant(z) ){ z++; }
   135046   return *z!=0;
   135047 }
   135048 
   135049 /* Like mgt0 above except we are looking for a value of m which is
   135050 ** exactly 1
   135051 */
   135052 static int m_eq_1(const char *z){
   135053   while( isVowel(z) ){ z++; }
   135054   if( *z==0 ) return 0;
   135055   while( isConsonant(z) ){ z++; }
   135056   if( *z==0 ) return 0;
   135057   while( isVowel(z) ){ z++; }
   135058   if( *z==0 ) return 1;
   135059   while( isConsonant(z) ){ z++; }
   135060   return *z==0;
   135061 }
   135062 
   135063 /* Like mgt0 above except we are looking for a value of m>1 instead
   135064 ** or m>0
   135065 */
   135066 static int m_gt_1(const char *z){
   135067   while( isVowel(z) ){ z++; }
   135068   if( *z==0 ) return 0;
   135069   while( isConsonant(z) ){ z++; }
   135070   if( *z==0 ) return 0;
   135071   while( isVowel(z) ){ z++; }
   135072   if( *z==0 ) return 0;
   135073   while( isConsonant(z) ){ z++; }
   135074   return *z!=0;
   135075 }
   135076 
   135077 /*
   135078 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
   135079 */
   135080 static int hasVowel(const char *z){
   135081   while( isConsonant(z) ){ z++; }
   135082   return *z!=0;
   135083 }
   135084 
   135085 /*
   135086 ** Return TRUE if the word ends in a double consonant.
   135087 **
   135088 ** The text is reversed here. So we are really looking at
   135089 ** the first two characters of z[].
   135090 */
   135091 static int doubleConsonant(const char *z){
   135092   return isConsonant(z) && z[0]==z[1];
   135093 }
   135094 
   135095 /*
   135096 ** Return TRUE if the word ends with three letters which
   135097 ** are consonant-vowel-consonent and where the final consonant
   135098 ** is not 'w', 'x', or 'y'.
   135099 **
   135100 ** The word is reversed here.  So we are really checking the
   135101 ** first three letters and the first one cannot be in [wxy].
   135102 */
   135103 static int star_oh(const char *z){
   135104   return
   135105     isConsonant(z) &&
   135106     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
   135107     isVowel(z+1) &&
   135108     isConsonant(z+2);
   135109 }
   135110 
   135111 /*
   135112 ** If the word ends with zFrom and xCond() is true for the stem
   135113 ** of the word that preceeds the zFrom ending, then change the
   135114 ** ending to zTo.
   135115 **
   135116 ** The input word *pz and zFrom are both in reverse order.  zTo
   135117 ** is in normal order.
   135118 **
   135119 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
   135120 ** match.  Not that TRUE is returned even if xCond() fails and
   135121 ** no substitution occurs.
   135122 */
   135123 static int stem(
   135124   char **pz,             /* The word being stemmed (Reversed) */
   135125   const char *zFrom,     /* If the ending matches this... (Reversed) */
   135126   const char *zTo,       /* ... change the ending to this (not reversed) */
   135127   int (*xCond)(const char*)   /* Condition that must be true */
   135128 ){
   135129   char *z = *pz;
   135130   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
   135131   if( *zFrom!=0 ) return 0;
   135132   if( xCond && !xCond(z) ) return 1;
   135133   while( *zTo ){
   135134     *(--z) = *(zTo++);
   135135   }
   135136   *pz = z;
   135137   return 1;
   135138 }
   135139 
   135140 /*
   135141 ** This is the fallback stemmer used when the porter stemmer is
   135142 ** inappropriate.  The input word is copied into the output with
   135143 ** US-ASCII case folding.  If the input word is too long (more
   135144 ** than 20 bytes if it contains no digits or more than 6 bytes if
   135145 ** it contains digits) then word is truncated to 20 or 6 bytes
   135146 ** by taking 10 or 3 bytes from the beginning and end.
   135147 */
   135148 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   135149   int i, mx, j;
   135150   int hasDigit = 0;
   135151   for(i=0; i<nIn; i++){
   135152     char c = zIn[i];
   135153     if( c>='A' && c<='Z' ){
   135154       zOut[i] = c - 'A' + 'a';
   135155     }else{
   135156       if( c>='0' && c<='9' ) hasDigit = 1;
   135157       zOut[i] = c;
   135158     }
   135159   }
   135160   mx = hasDigit ? 3 : 10;
   135161   if( nIn>mx*2 ){
   135162     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
   135163       zOut[j] = zOut[i];
   135164     }
   135165     i = j;
   135166   }
   135167   zOut[i] = 0;
   135168   *pnOut = i;
   135169 }
   135170 
   135171 
   135172 /*
   135173 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
   135174 ** zOut is at least big enough to hold nIn bytes.  Write the actual
   135175 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
   135176 **
   135177 ** Any upper-case characters in the US-ASCII character set ([A-Z])
   135178 ** are converted to lower case.  Upper-case UTF characters are
   135179 ** unchanged.
   135180 **
   135181 ** Words that are longer than about 20 bytes are stemmed by retaining
   135182 ** a few bytes from the beginning and the end of the word.  If the
   135183 ** word contains digits, 3 bytes are taken from the beginning and
   135184 ** 3 bytes from the end.  For long words without digits, 10 bytes
   135185 ** are taken from each end.  US-ASCII case folding still applies.
   135186 **
   135187 ** If the input word contains not digits but does characters not
   135188 ** in [a-zA-Z] then no stemming is attempted and this routine just
   135189 ** copies the input into the input into the output with US-ASCII
   135190 ** case folding.
   135191 **
   135192 ** Stemming never increases the length of the word.  So there is
   135193 ** no chance of overflowing the zOut buffer.
   135194 */
   135195 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   135196   int i, j;
   135197   char zReverse[28];
   135198   char *z, *z2;
   135199   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
   135200     /* The word is too big or too small for the porter stemmer.
   135201     ** Fallback to the copy stemmer */
   135202     copy_stemmer(zIn, nIn, zOut, pnOut);
   135203     return;
   135204   }
   135205   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
   135206     char c = zIn[i];
   135207     if( c>='A' && c<='Z' ){
   135208       zReverse[j] = c + 'a' - 'A';
   135209     }else if( c>='a' && c<='z' ){
   135210       zReverse[j] = c;
   135211     }else{
   135212       /* The use of a character not in [a-zA-Z] means that we fallback
   135213       ** to the copy stemmer */
   135214       copy_stemmer(zIn, nIn, zOut, pnOut);
   135215       return;
   135216     }
   135217   }
   135218   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
   135219   z = &zReverse[j+1];
   135220 
   135221 
   135222   /* Step 1a */
   135223   if( z[0]=='s' ){
   135224     if(
   135225      !stem(&z, "sess", "ss", 0) &&
   135226      !stem(&z, "sei", "i", 0)  &&
   135227      !stem(&z, "ss", "ss", 0)
   135228     ){
   135229       z++;
   135230     }
   135231   }
   135232 
   135233   /* Step 1b */
   135234   z2 = z;
   135235   if( stem(&z, "dee", "ee", m_gt_0) ){
   135236     /* Do nothing.  The work was all in the test */
   135237   }else if(
   135238      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
   135239       && z!=z2
   135240   ){
   135241      if( stem(&z, "ta", "ate", 0) ||
   135242          stem(&z, "lb", "ble", 0) ||
   135243          stem(&z, "zi", "ize", 0) ){
   135244        /* Do nothing.  The work was all in the test */
   135245      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
   135246        z++;
   135247      }else if( m_eq_1(z) && star_oh(z) ){
   135248        *(--z) = 'e';
   135249      }
   135250   }
   135251 
   135252   /* Step 1c */
   135253   if( z[0]=='y' && hasVowel(z+1) ){
   135254     z[0] = 'i';
   135255   }
   135256 
   135257   /* Step 2 */
   135258   switch( z[1] ){
   135259    case 'a':
   135260      if( !stem(&z, "lanoita", "ate", m_gt_0) ){
   135261        stem(&z, "lanoit", "tion", m_gt_0);
   135262      }
   135263      break;
   135264    case 'c':
   135265      if( !stem(&z, "icne", "ence", m_gt_0) ){
   135266        stem(&z, "icna", "ance", m_gt_0);
   135267      }
   135268      break;
   135269    case 'e':
   135270      stem(&z, "rezi", "ize", m_gt_0);
   135271      break;
   135272    case 'g':
   135273      stem(&z, "igol", "log", m_gt_0);
   135274      break;
   135275    case 'l':
   135276      if( !stem(&z, "ilb", "ble", m_gt_0)
   135277       && !stem(&z, "illa", "al", m_gt_0)
   135278       && !stem(&z, "iltne", "ent", m_gt_0)
   135279       && !stem(&z, "ile", "e", m_gt_0)
   135280      ){
   135281        stem(&z, "ilsuo", "ous", m_gt_0);
   135282      }
   135283      break;
   135284    case 'o':
   135285      if( !stem(&z, "noitazi", "ize", m_gt_0)
   135286       && !stem(&z, "noita", "ate", m_gt_0)
   135287      ){
   135288        stem(&z, "rota", "ate", m_gt_0);
   135289      }
   135290      break;
   135291    case 's':
   135292      if( !stem(&z, "msila", "al", m_gt_0)
   135293       && !stem(&z, "ssenevi", "ive", m_gt_0)
   135294       && !stem(&z, "ssenluf", "ful", m_gt_0)
   135295      ){
   135296        stem(&z, "ssensuo", "ous", m_gt_0);
   135297      }
   135298      break;
   135299    case 't':
   135300      if( !stem(&z, "itila", "al", m_gt_0)
   135301       && !stem(&z, "itivi", "ive", m_gt_0)
   135302      ){
   135303        stem(&z, "itilib", "ble", m_gt_0);
   135304      }
   135305      break;
   135306   }
   135307 
   135308   /* Step 3 */
   135309   switch( z[0] ){
   135310    case 'e':
   135311      if( !stem(&z, "etaci", "ic", m_gt_0)
   135312       && !stem(&z, "evita", "", m_gt_0)
   135313      ){
   135314        stem(&z, "ezila", "al", m_gt_0);
   135315      }
   135316      break;
   135317    case 'i':
   135318      stem(&z, "itici", "ic", m_gt_0);
   135319      break;
   135320    case 'l':
   135321      if( !stem(&z, "laci", "ic", m_gt_0) ){
   135322        stem(&z, "luf", "", m_gt_0);
   135323      }
   135324      break;
   135325    case 's':
   135326      stem(&z, "ssen", "", m_gt_0);
   135327      break;
   135328   }
   135329 
   135330   /* Step 4 */
   135331   switch( z[1] ){
   135332    case 'a':
   135333      if( z[0]=='l' && m_gt_1(z+2) ){
   135334        z += 2;
   135335      }
   135336      break;
   135337    case 'c':
   135338      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
   135339        z += 4;
   135340      }
   135341      break;
   135342    case 'e':
   135343      if( z[0]=='r' && m_gt_1(z+2) ){
   135344        z += 2;
   135345      }
   135346      break;
   135347    case 'i':
   135348      if( z[0]=='c' && m_gt_1(z+2) ){
   135349        z += 2;
   135350      }
   135351      break;
   135352    case 'l':
   135353      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
   135354        z += 4;
   135355      }
   135356      break;
   135357    case 'n':
   135358      if( z[0]=='t' ){
   135359        if( z[2]=='a' ){
   135360          if( m_gt_1(z+3) ){
   135361            z += 3;
   135362          }
   135363        }else if( z[2]=='e' ){
   135364          if( !stem(&z, "tneme", "", m_gt_1)
   135365           && !stem(&z, "tnem", "", m_gt_1)
   135366          ){
   135367            stem(&z, "tne", "", m_gt_1);
   135368          }
   135369        }
   135370      }
   135371      break;
   135372    case 'o':
   135373      if( z[0]=='u' ){
   135374        if( m_gt_1(z+2) ){
   135375          z += 2;
   135376        }
   135377      }else if( z[3]=='s' || z[3]=='t' ){
   135378        stem(&z, "noi", "", m_gt_1);
   135379      }
   135380      break;
   135381    case 's':
   135382      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
   135383        z += 3;
   135384      }
   135385      break;
   135386    case 't':
   135387      if( !stem(&z, "eta", "", m_gt_1) ){
   135388        stem(&z, "iti", "", m_gt_1);
   135389      }
   135390      break;
   135391    case 'u':
   135392      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
   135393        z += 3;
   135394      }
   135395      break;
   135396    case 'v':
   135397    case 'z':
   135398      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
   135399        z += 3;
   135400      }
   135401      break;
   135402   }
   135403 
   135404   /* Step 5a */
   135405   if( z[0]=='e' ){
   135406     if( m_gt_1(z+1) ){
   135407       z++;
   135408     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
   135409       z++;
   135410     }
   135411   }
   135412 
   135413   /* Step 5b */
   135414   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
   135415     z++;
   135416   }
   135417 
   135418   /* z[] is now the stemmed word in reverse order.  Flip it back
   135419   ** around into forward order and return.
   135420   */
   135421   *pnOut = i = (int)strlen(z);
   135422   zOut[i] = 0;
   135423   while( *z ){
   135424     zOut[--i] = *(z++);
   135425   }
   135426 }
   135427 
   135428 /*
   135429 ** Characters that can be part of a token.  We assume any character
   135430 ** whose value is greater than 0x80 (any UTF character) can be
   135431 ** part of a token.  In other words, delimiters all must have
   135432 ** values of 0x7f or lower.
   135433 */
   135434 static const char porterIdChar[] = {
   135435 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   135436     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   135437     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   135438     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   135439     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   135440     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   135441 };
   135442 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
   135443 
   135444 /*
   135445 ** Extract the next token from a tokenization cursor.  The cursor must
   135446 ** have been opened by a prior call to porterOpen().
   135447 */
   135448 static int porterNext(
   135449   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
   135450   const char **pzToken,               /* OUT: *pzToken is the token text */
   135451   int *pnBytes,                       /* OUT: Number of bytes in token */
   135452   int *piStartOffset,                 /* OUT: Starting offset of token */
   135453   int *piEndOffset,                   /* OUT: Ending offset of token */
   135454   int *piPosition                     /* OUT: Position integer of token */
   135455 ){
   135456   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   135457   const char *z = c->zInput;
   135458 
   135459   while( c->iOffset<c->nInput ){
   135460     int iStartOffset, ch;
   135461 
   135462     /* Scan past delimiter characters */
   135463     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
   135464       c->iOffset++;
   135465     }
   135466 
   135467     /* Count non-delimiter characters. */
   135468     iStartOffset = c->iOffset;
   135469     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
   135470       c->iOffset++;
   135471     }
   135472 
   135473     if( c->iOffset>iStartOffset ){
   135474       int n = c->iOffset-iStartOffset;
   135475       if( n>c->nAllocated ){
   135476         char *pNew;
   135477         c->nAllocated = n+20;
   135478         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
   135479         if( !pNew ) return SQLITE_NOMEM;
   135480         c->zToken = pNew;
   135481       }
   135482       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
   135483       *pzToken = c->zToken;
   135484       *piStartOffset = iStartOffset;
   135485       *piEndOffset = c->iOffset;
   135486       *piPosition = c->iToken++;
   135487       return SQLITE_OK;
   135488     }
   135489   }
   135490   return SQLITE_DONE;
   135491 }
   135492 
   135493 /*
   135494 ** The set of routines that implement the porter-stemmer tokenizer
   135495 */
   135496 static const sqlite3_tokenizer_module porterTokenizerModule = {
   135497   0,
   135498   porterCreate,
   135499   porterDestroy,
   135500   porterOpen,
   135501   porterClose,
   135502   porterNext,
   135503   0
   135504 };
   135505 
   135506 /*
   135507 ** Allocate a new porter tokenizer.  Return a pointer to the new
   135508 ** tokenizer in *ppModule
   135509 */
   135510 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
   135511   sqlite3_tokenizer_module const**ppModule
   135512 ){
   135513   *ppModule = &porterTokenizerModule;
   135514 }
   135515 
   135516 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   135517 
   135518 /************** End of fts3_porter.c *****************************************/
   135519 /************** Begin file fts3_tokenizer.c **********************************/
   135520 /*
   135521 ** 2007 June 22
   135522 **
   135523 ** The author disclaims copyright to this source code.  In place of
   135524 ** a legal notice, here is a blessing:
   135525 **
   135526 **    May you do good and not evil.
   135527 **    May you find forgiveness for yourself and forgive others.
   135528 **    May you share freely, never taking more than you give.
   135529 **
   135530 ******************************************************************************
   135531 **
   135532 ** This is part of an SQLite module implementing full-text search.
   135533 ** This particular file implements the generic tokenizer interface.
   135534 */
   135535 
   135536 /*
   135537 ** The code in this file is only compiled if:
   135538 **
   135539 **     * The FTS3 module is being built as an extension
   135540 **       (in which case SQLITE_CORE is not defined), or
   135541 **
   135542 **     * The FTS3 module is being built into the core of
   135543 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   135544 */
   135545 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   135546 
   135547 /* #include <assert.h> */
   135548 /* #include <string.h> */
   135549 
   135550 /*
   135551 ** Implementation of the SQL scalar function for accessing the underlying
   135552 ** hash table. This function may be called as follows:
   135553 **
   135554 **   SELECT <function-name>(<key-name>);
   135555 **   SELECT <function-name>(<key-name>, <pointer>);
   135556 **
   135557 ** where <function-name> is the name passed as the second argument
   135558 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
   135559 **
   135560 ** If the <pointer> argument is specified, it must be a blob value
   135561 ** containing a pointer to be stored as the hash data corresponding
   135562 ** to the string <key-name>. If <pointer> is not specified, then
   135563 ** the string <key-name> must already exist in the has table. Otherwise,
   135564 ** an error is returned.
   135565 **
   135566 ** Whether or not the <pointer> argument is specified, the value returned
   135567 ** is a blob containing the pointer stored as the hash data corresponding
   135568 ** to string <key-name> (after the hash-table is updated, if applicable).
   135569 */
   135570 static void scalarFunc(
   135571   sqlite3_context *context,
   135572   int argc,
   135573   sqlite3_value **argv
   135574 ){
   135575   Fts3Hash *pHash;
   135576   void *pPtr = 0;
   135577   const unsigned char *zName;
   135578   int nName;
   135579 
   135580   assert( argc==1 || argc==2 );
   135581 
   135582   pHash = (Fts3Hash *)sqlite3_user_data(context);
   135583 
   135584   zName = sqlite3_value_text(argv[0]);
   135585   nName = sqlite3_value_bytes(argv[0])+1;
   135586 
   135587   if( argc==2 ){
   135588     void *pOld;
   135589     int n = sqlite3_value_bytes(argv[1]);
   135590     if( n!=sizeof(pPtr) ){
   135591       sqlite3_result_error(context, "argument type mismatch", -1);
   135592       return;
   135593     }
   135594     pPtr = *(void **)sqlite3_value_blob(argv[1]);
   135595     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
   135596     if( pOld==pPtr ){
   135597       sqlite3_result_error(context, "out of memory", -1);
   135598       return;
   135599     }
   135600   }else{
   135601     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
   135602     if( !pPtr ){
   135603       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   135604       sqlite3_result_error(context, zErr, -1);
   135605       sqlite3_free(zErr);
   135606       return;
   135607     }
   135608   }
   135609 
   135610   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
   135611 }
   135612 
   135613 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
   135614   static const char isFtsIdChar[] = {
   135615       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
   135616       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
   135617       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
   135618       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   135619       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   135620       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   135621       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   135622       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   135623   };
   135624   return (c&0x80 || isFtsIdChar[(int)(c)]);
   135625 }
   135626 
   135627 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
   135628   const char *z1;
   135629   const char *z2 = 0;
   135630 
   135631   /* Find the start of the next token. */
   135632   z1 = zStr;
   135633   while( z2==0 ){
   135634     char c = *z1;
   135635     switch( c ){
   135636       case '\0': return 0;        /* No more tokens here */
   135637       case '\'':
   135638       case '"':
   135639       case '`': {
   135640         z2 = z1;
   135641         while( *++z2 && (*z2!=c || *++z2==c) );
   135642         break;
   135643       }
   135644       case '[':
   135645         z2 = &z1[1];
   135646         while( *z2 && z2[0]!=']' ) z2++;
   135647         if( *z2 ) z2++;
   135648         break;
   135649 
   135650       default:
   135651         if( sqlite3Fts3IsIdChar(*z1) ){
   135652           z2 = &z1[1];
   135653           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
   135654         }else{
   135655           z1++;
   135656         }
   135657     }
   135658   }
   135659 
   135660   *pn = (int)(z2-z1);
   135661   return z1;
   135662 }
   135663 
   135664 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
   135665   Fts3Hash *pHash,                /* Tokenizer hash table */
   135666   const char *zArg,               /* Tokenizer name */
   135667   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
   135668   char **pzErr                    /* OUT: Set to malloced error message */
   135669 ){
   135670   int rc;
   135671   char *z = (char *)zArg;
   135672   int n = 0;
   135673   char *zCopy;
   135674   char *zEnd;                     /* Pointer to nul-term of zCopy */
   135675   sqlite3_tokenizer_module *m;
   135676 
   135677   zCopy = sqlite3_mprintf("%s", zArg);
   135678   if( !zCopy ) return SQLITE_NOMEM;
   135679   zEnd = &zCopy[strlen(zCopy)];
   135680 
   135681   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
   135682   z[n] = '\0';
   135683   sqlite3Fts3Dequote(z);
   135684 
   135685   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
   135686   if( !m ){
   135687     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
   135688     rc = SQLITE_ERROR;
   135689   }else{
   135690     char const **aArg = 0;
   135691     int iArg = 0;
   135692     z = &z[n+1];
   135693     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
   135694       int nNew = sizeof(char *)*(iArg+1);
   135695       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
   135696       if( !aNew ){
   135697         sqlite3_free(zCopy);
   135698         sqlite3_free((void *)aArg);
   135699         return SQLITE_NOMEM;
   135700       }
   135701       aArg = aNew;
   135702       aArg[iArg++] = z;
   135703       z[n] = '\0';
   135704       sqlite3Fts3Dequote(z);
   135705       z = &z[n+1];
   135706     }
   135707     rc = m->xCreate(iArg, aArg, ppTok);
   135708     assert( rc!=SQLITE_OK || *ppTok );
   135709     if( rc!=SQLITE_OK ){
   135710       *pzErr = sqlite3_mprintf("unknown tokenizer");
   135711     }else{
   135712       (*ppTok)->pModule = m;
   135713     }
   135714     sqlite3_free((void *)aArg);
   135715   }
   135716 
   135717   sqlite3_free(zCopy);
   135718   return rc;
   135719 }
   135720 
   135721 
   135722 #ifdef SQLITE_TEST
   135723 
   135724 #include <tcl.h>
   135725 /* #include <string.h> */
   135726 
   135727 /*
   135728 ** Implementation of a special SQL scalar function for testing tokenizers
   135729 ** designed to be used in concert with the Tcl testing framework. This
   135730 ** function must be called with two or more arguments:
   135731 **
   135732 **   SELECT <function-name>(<key-name>, ..., <input-string>);
   135733 **
   135734 ** where <function-name> is the name passed as the second argument
   135735 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
   135736 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
   135737 **
   135738 ** The return value is a string that may be interpreted as a Tcl
   135739 ** list. For each token in the <input-string>, three elements are
   135740 ** added to the returned list. The first is the token position, the
   135741 ** second is the token text (folded, stemmed, etc.) and the third is the
   135742 ** substring of <input-string> associated with the token. For example,
   135743 ** using the built-in "simple" tokenizer:
   135744 **
   135745 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
   135746 **
   135747 ** will return the string:
   135748 **
   135749 **   "{0 i I 1 dont don't 2 see see 3 how how}"
   135750 **
   135751 */
   135752 static void testFunc(
   135753   sqlite3_context *context,
   135754   int argc,
   135755   sqlite3_value **argv
   135756 ){
   135757   Fts3Hash *pHash;
   135758   sqlite3_tokenizer_module *p;
   135759   sqlite3_tokenizer *pTokenizer = 0;
   135760   sqlite3_tokenizer_cursor *pCsr = 0;
   135761 
   135762   const char *zErr = 0;
   135763 
   135764   const char *zName;
   135765   int nName;
   135766   const char *zInput;
   135767   int nInput;
   135768 
   135769   const char *azArg[64];
   135770 
   135771   const char *zToken;
   135772   int nToken = 0;
   135773   int iStart = 0;
   135774   int iEnd = 0;
   135775   int iPos = 0;
   135776   int i;
   135777 
   135778   Tcl_Obj *pRet;
   135779 
   135780   if( argc<2 ){
   135781     sqlite3_result_error(context, "insufficient arguments", -1);
   135782     return;
   135783   }
   135784 
   135785   nName = sqlite3_value_bytes(argv[0]);
   135786   zName = (const char *)sqlite3_value_text(argv[0]);
   135787   nInput = sqlite3_value_bytes(argv[argc-1]);
   135788   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
   135789 
   135790   pHash = (Fts3Hash *)sqlite3_user_data(context);
   135791   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   135792 
   135793   if( !p ){
   135794     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   135795     sqlite3_result_error(context, zErr, -1);
   135796     sqlite3_free(zErr);
   135797     return;
   135798   }
   135799 
   135800   pRet = Tcl_NewObj();
   135801   Tcl_IncrRefCount(pRet);
   135802 
   135803   for(i=1; i<argc-1; i++){
   135804     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
   135805   }
   135806 
   135807   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
   135808     zErr = "error in xCreate()";
   135809     goto finish;
   135810   }
   135811   pTokenizer->pModule = p;
   135812   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
   135813     zErr = "error in xOpen()";
   135814     goto finish;
   135815   }
   135816 
   135817   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
   135818     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
   135819     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   135820     zToken = &zInput[iStart];
   135821     nToken = iEnd-iStart;
   135822     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   135823   }
   135824 
   135825   if( SQLITE_OK!=p->xClose(pCsr) ){
   135826     zErr = "error in xClose()";
   135827     goto finish;
   135828   }
   135829   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
   135830     zErr = "error in xDestroy()";
   135831     goto finish;
   135832   }
   135833 
   135834 finish:
   135835   if( zErr ){
   135836     sqlite3_result_error(context, zErr, -1);
   135837   }else{
   135838     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
   135839   }
   135840   Tcl_DecrRefCount(pRet);
   135841 }
   135842 
   135843 static
   135844 int registerTokenizer(
   135845   sqlite3 *db,
   135846   char *zName,
   135847   const sqlite3_tokenizer_module *p
   135848 ){
   135849   int rc;
   135850   sqlite3_stmt *pStmt;
   135851   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
   135852 
   135853   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   135854   if( rc!=SQLITE_OK ){
   135855     return rc;
   135856   }
   135857 
   135858   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   135859   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
   135860   sqlite3_step(pStmt);
   135861 
   135862   return sqlite3_finalize(pStmt);
   135863 }
   135864 
   135865 static
   135866 int queryTokenizer(
   135867   sqlite3 *db,
   135868   char *zName,
   135869   const sqlite3_tokenizer_module **pp
   135870 ){
   135871   int rc;
   135872   sqlite3_stmt *pStmt;
   135873   const char zSql[] = "SELECT fts3_tokenizer(?)";
   135874 
   135875   *pp = 0;
   135876   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   135877   if( rc!=SQLITE_OK ){
   135878     return rc;
   135879   }
   135880 
   135881   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   135882   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   135883     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   135884       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   135885     }
   135886   }
   135887 
   135888   return sqlite3_finalize(pStmt);
   135889 }
   135890 
   135891 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   135892 
   135893 /*
   135894 ** Implementation of the scalar function fts3_tokenizer_internal_test().
   135895 ** This function is used for testing only, it is not included in the
   135896 ** build unless SQLITE_TEST is defined.
   135897 **
   135898 ** The purpose of this is to test that the fts3_tokenizer() function
   135899 ** can be used as designed by the C-code in the queryTokenizer and
   135900 ** registerTokenizer() functions above. These two functions are repeated
   135901 ** in the README.tokenizer file as an example, so it is important to
   135902 ** test them.
   135903 **
   135904 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
   135905 ** function with no arguments. An assert() will fail if a problem is
   135906 ** detected. i.e.:
   135907 **
   135908 **     SELECT fts3_tokenizer_internal_test();
   135909 **
   135910 */
   135911 static void intTestFunc(
   135912   sqlite3_context *context,
   135913   int argc,
   135914   sqlite3_value **argv
   135915 ){
   135916   int rc;
   135917   const sqlite3_tokenizer_module *p1;
   135918   const sqlite3_tokenizer_module *p2;
   135919   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
   135920 
   135921   UNUSED_PARAMETER(argc);
   135922   UNUSED_PARAMETER(argv);
   135923 
   135924   /* Test the query function */
   135925   sqlite3Fts3SimpleTokenizerModule(&p1);
   135926   rc = queryTokenizer(db, "simple", &p2);
   135927   assert( rc==SQLITE_OK );
   135928   assert( p1==p2 );
   135929   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   135930   assert( rc==SQLITE_ERROR );
   135931   assert( p2==0 );
   135932   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
   135933 
   135934   /* Test the storage function */
   135935   rc = registerTokenizer(db, "nosuchtokenizer", p1);
   135936   assert( rc==SQLITE_OK );
   135937   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   135938   assert( rc==SQLITE_OK );
   135939   assert( p2==p1 );
   135940 
   135941   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
   135942 }
   135943 
   135944 #endif
   135945 
   135946 /*
   135947 ** Set up SQL objects in database db used to access the contents of
   135948 ** the hash table pointed to by argument pHash. The hash table must
   135949 ** been initialized to use string keys, and to take a private copy
   135950 ** of the key when a value is inserted. i.e. by a call similar to:
   135951 **
   135952 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   135953 **
   135954 ** This function adds a scalar function (see header comment above
   135955 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
   135956 ** defined at compilation time, a temporary virtual table (see header
   135957 ** comment above struct HashTableVtab) to the database schema. Both
   135958 ** provide read/write access to the contents of *pHash.
   135959 **
   135960 ** The third argument to this function, zName, is used as the name
   135961 ** of both the scalar and, if created, the virtual table.
   135962 */
   135963 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
   135964   sqlite3 *db,
   135965   Fts3Hash *pHash,
   135966   const char *zName
   135967 ){
   135968   int rc = SQLITE_OK;
   135969   void *p = (void *)pHash;
   135970   const int any = SQLITE_ANY;
   135971 
   135972 #ifdef SQLITE_TEST
   135973   char *zTest = 0;
   135974   char *zTest2 = 0;
   135975   void *pdb = (void *)db;
   135976   zTest = sqlite3_mprintf("%s_test", zName);
   135977   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
   135978   if( !zTest || !zTest2 ){
   135979     rc = SQLITE_NOMEM;
   135980   }
   135981 #endif
   135982 
   135983   if( SQLITE_OK==rc ){
   135984     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
   135985   }
   135986   if( SQLITE_OK==rc ){
   135987     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
   135988   }
   135989 #ifdef SQLITE_TEST
   135990   if( SQLITE_OK==rc ){
   135991     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
   135992   }
   135993   if( SQLITE_OK==rc ){
   135994     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
   135995   }
   135996 #endif
   135997 
   135998 #ifdef SQLITE_TEST
   135999   sqlite3_free(zTest);
   136000   sqlite3_free(zTest2);
   136001 #endif
   136002 
   136003   return rc;
   136004 }
   136005 
   136006 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   136007 
   136008 /************** End of fts3_tokenizer.c **************************************/
   136009 /************** Begin file fts3_tokenizer1.c *********************************/
   136010 /*
   136011 ** 2006 Oct 10
   136012 **
   136013 ** The author disclaims copyright to this source code.  In place of
   136014 ** a legal notice, here is a blessing:
   136015 **
   136016 **    May you do good and not evil.
   136017 **    May you find forgiveness for yourself and forgive others.
   136018 **    May you share freely, never taking more than you give.
   136019 **
   136020 ******************************************************************************
   136021 **
   136022 ** Implementation of the "simple" full-text-search tokenizer.
   136023 */
   136024 
   136025 /*
   136026 ** The code in this file is only compiled if:
   136027 **
   136028 **     * The FTS3 module is being built as an extension
   136029 **       (in which case SQLITE_CORE is not defined), or
   136030 **
   136031 **     * The FTS3 module is being built into the core of
   136032 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   136033 */
   136034 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   136035 
   136036 /* #include <assert.h> */
   136037 /* #include <stdlib.h> */
   136038 /* #include <stdio.h> */
   136039 /* #include <string.h> */
   136040 
   136041 
   136042 typedef struct simple_tokenizer {
   136043   sqlite3_tokenizer base;
   136044   char delim[128];             /* flag ASCII delimiters */
   136045 } simple_tokenizer;
   136046 
   136047 typedef struct simple_tokenizer_cursor {
   136048   sqlite3_tokenizer_cursor base;
   136049   const char *pInput;          /* input we are tokenizing */
   136050   int nBytes;                  /* size of the input */
   136051   int iOffset;                 /* current position in pInput */
   136052   int iToken;                  /* index of next token to be returned */
   136053   char *pToken;                /* storage for current token */
   136054   int nTokenAllocated;         /* space allocated to zToken buffer */
   136055 } simple_tokenizer_cursor;
   136056 
   136057 
   136058 static int simpleDelim(simple_tokenizer *t, unsigned char c){
   136059   return c<0x80 && t->delim[c];
   136060 }
   136061 static int fts3_isalnum(int x){
   136062   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
   136063 }
   136064 
   136065 /*
   136066 ** Create a new tokenizer instance.
   136067 */
   136068 static int simpleCreate(
   136069   int argc, const char * const *argv,
   136070   sqlite3_tokenizer **ppTokenizer
   136071 ){
   136072   simple_tokenizer *t;
   136073 
   136074   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
   136075   if( t==NULL ) return SQLITE_NOMEM;
   136076   memset(t, 0, sizeof(*t));
   136077 
   136078   /* TODO(shess) Delimiters need to remain the same from run to run,
   136079   ** else we need to reindex.  One solution would be a meta-table to
   136080   ** track such information in the database, then we'd only want this
   136081   ** information on the initial create.
   136082   */
   136083   if( argc>1 ){
   136084     int i, n = (int)strlen(argv[1]);
   136085     for(i=0; i<n; i++){
   136086       unsigned char ch = argv[1][i];
   136087       /* We explicitly don't support UTF-8 delimiters for now. */
   136088       if( ch>=0x80 ){
   136089         sqlite3_free(t);
   136090         return SQLITE_ERROR;
   136091       }
   136092       t->delim[ch] = 1;
   136093     }
   136094   } else {
   136095     /* Mark non-alphanumeric ASCII characters as delimiters */
   136096     int i;
   136097     for(i=1; i<0x80; i++){
   136098       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
   136099     }
   136100   }
   136101 
   136102   *ppTokenizer = &t->base;
   136103   return SQLITE_OK;
   136104 }
   136105 
   136106 /*
   136107 ** Destroy a tokenizer
   136108 */
   136109 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
   136110   sqlite3_free(pTokenizer);
   136111   return SQLITE_OK;
   136112 }
   136113 
   136114 /*
   136115 ** Prepare to begin tokenizing a particular string.  The input
   136116 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   136117 ** used to incrementally tokenize this string is returned in
   136118 ** *ppCursor.
   136119 */
   136120 static int simpleOpen(
   136121   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   136122   const char *pInput, int nBytes,        /* String to be tokenized */
   136123   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   136124 ){
   136125   simple_tokenizer_cursor *c;
   136126 
   136127   UNUSED_PARAMETER(pTokenizer);
   136128 
   136129   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   136130   if( c==NULL ) return SQLITE_NOMEM;
   136131 
   136132   c->pInput = pInput;
   136133   if( pInput==0 ){
   136134     c->nBytes = 0;
   136135   }else if( nBytes<0 ){
   136136     c->nBytes = (int)strlen(pInput);
   136137   }else{
   136138     c->nBytes = nBytes;
   136139   }
   136140   c->iOffset = 0;                 /* start tokenizing at the beginning */
   136141   c->iToken = 0;
   136142   c->pToken = NULL;               /* no space allocated, yet. */
   136143   c->nTokenAllocated = 0;
   136144 
   136145   *ppCursor = &c->base;
   136146   return SQLITE_OK;
   136147 }
   136148 
   136149 /*
   136150 ** Close a tokenization cursor previously opened by a call to
   136151 ** simpleOpen() above.
   136152 */
   136153 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
   136154   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   136155   sqlite3_free(c->pToken);
   136156   sqlite3_free(c);
   136157   return SQLITE_OK;
   136158 }
   136159 
   136160 /*
   136161 ** Extract the next token from a tokenization cursor.  The cursor must
   136162 ** have been opened by a prior call to simpleOpen().
   136163 */
   136164 static int simpleNext(
   136165   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   136166   const char **ppToken,               /* OUT: *ppToken is the token text */
   136167   int *pnBytes,                       /* OUT: Number of bytes in token */
   136168   int *piStartOffset,                 /* OUT: Starting offset of token */
   136169   int *piEndOffset,                   /* OUT: Ending offset of token */
   136170   int *piPosition                     /* OUT: Position integer of token */
   136171 ){
   136172   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   136173   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
   136174   unsigned char *p = (unsigned char *)c->pInput;
   136175 
   136176   while( c->iOffset<c->nBytes ){
   136177     int iStartOffset;
   136178 
   136179     /* Scan past delimiter characters */
   136180     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
   136181       c->iOffset++;
   136182     }
   136183 
   136184     /* Count non-delimiter characters. */
   136185     iStartOffset = c->iOffset;
   136186     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
   136187       c->iOffset++;
   136188     }
   136189 
   136190     if( c->iOffset>iStartOffset ){
   136191       int i, n = c->iOffset-iStartOffset;
   136192       if( n>c->nTokenAllocated ){
   136193         char *pNew;
   136194         c->nTokenAllocated = n+20;
   136195         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
   136196         if( !pNew ) return SQLITE_NOMEM;
   136197         c->pToken = pNew;
   136198       }
   136199       for(i=0; i<n; i++){
   136200         /* TODO(shess) This needs expansion to handle UTF-8
   136201         ** case-insensitivity.
   136202         */
   136203         unsigned char ch = p[iStartOffset+i];
   136204         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
   136205       }
   136206       *ppToken = c->pToken;
   136207       *pnBytes = n;
   136208       *piStartOffset = iStartOffset;
   136209       *piEndOffset = c->iOffset;
   136210       *piPosition = c->iToken++;
   136211 
   136212       return SQLITE_OK;
   136213     }
   136214   }
   136215   return SQLITE_DONE;
   136216 }
   136217 
   136218 /*
   136219 ** The set of routines that implement the simple tokenizer
   136220 */
   136221 static const sqlite3_tokenizer_module simpleTokenizerModule = {
   136222   0,
   136223   simpleCreate,
   136224   simpleDestroy,
   136225   simpleOpen,
   136226   simpleClose,
   136227   simpleNext,
   136228   0,
   136229 };
   136230 
   136231 /*
   136232 ** Allocate a new simple tokenizer.  Return a pointer to the new
   136233 ** tokenizer in *ppModule
   136234 */
   136235 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
   136236   sqlite3_tokenizer_module const**ppModule
   136237 ){
   136238   *ppModule = &simpleTokenizerModule;
   136239 }
   136240 
   136241 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   136242 
   136243 /************** End of fts3_tokenizer1.c *************************************/
   136244 /************** Begin file fts3_tokenize_vtab.c ******************************/
   136245 /*
   136246 ** 2013 Apr 22
   136247 **
   136248 ** The author disclaims copyright to this source code.  In place of
   136249 ** a legal notice, here is a blessing:
   136250 **
   136251 **    May you do good and not evil.
   136252 **    May you find forgiveness for yourself and forgive others.
   136253 **    May you share freely, never taking more than you give.
   136254 **
   136255 ******************************************************************************
   136256 **
   136257 ** This file contains code for the "fts3tokenize" virtual table module.
   136258 ** An fts3tokenize virtual table is created as follows:
   136259 **
   136260 **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
   136261 **       <tokenizer-name>, <arg-1>, ...
   136262 **   );
   136263 **
   136264 ** The table created has the following schema:
   136265 **
   136266 **   CREATE TABLE <tbl>(input, token, start, end, position)
   136267 **
   136268 ** When queried, the query must include a WHERE clause of type:
   136269 **
   136270 **   input = <string>
   136271 **
   136272 ** The virtual table module tokenizes this <string>, using the FTS3
   136273 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
   136274 ** statement and returns one row for each token in the result. With
   136275 ** fields set as follows:
   136276 **
   136277 **   input:   Always set to a copy of <string>
   136278 **   token:   A token from the input.
   136279 **   start:   Byte offset of the token within the input <string>.
   136280 **   end:     Byte offset of the byte immediately following the end of the
   136281 **            token within the input string.
   136282 **   pos:     Token offset of token within input.
   136283 **
   136284 */
   136285 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   136286 
   136287 /* #include <string.h> */
   136288 /* #include <assert.h> */
   136289 
   136290 typedef struct Fts3tokTable Fts3tokTable;
   136291 typedef struct Fts3tokCursor Fts3tokCursor;
   136292 
   136293 /*
   136294 ** Virtual table structure.
   136295 */
   136296 struct Fts3tokTable {
   136297   sqlite3_vtab base;              /* Base class used by SQLite core */
   136298   const sqlite3_tokenizer_module *pMod;
   136299   sqlite3_tokenizer *pTok;
   136300 };
   136301 
   136302 /*
   136303 ** Virtual table cursor structure.
   136304 */
   136305 struct Fts3tokCursor {
   136306   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   136307   char *zInput;                   /* Input string */
   136308   sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
   136309   int iRowid;                     /* Current 'rowid' value */
   136310   const char *zToken;             /* Current 'token' value */
   136311   int nToken;                     /* Size of zToken in bytes */
   136312   int iStart;                     /* Current 'start' value */
   136313   int iEnd;                       /* Current 'end' value */
   136314   int iPos;                       /* Current 'pos' value */
   136315 };
   136316 
   136317 /*
   136318 ** Query FTS for the tokenizer implementation named zName.
   136319 */
   136320 static int fts3tokQueryTokenizer(
   136321   Fts3Hash *pHash,
   136322   const char *zName,
   136323   const sqlite3_tokenizer_module **pp,
   136324   char **pzErr
   136325 ){
   136326   sqlite3_tokenizer_module *p;
   136327   int nName = (int)strlen(zName);
   136328 
   136329   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   136330   if( !p ){
   136331     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   136332     return SQLITE_ERROR;
   136333   }
   136334 
   136335   *pp = p;
   136336   return SQLITE_OK;
   136337 }
   136338 
   136339 /*
   136340 ** The second argument, argv[], is an array of pointers to nul-terminated
   136341 ** strings. This function makes a copy of the array and strings into a
   136342 ** single block of memory. It then dequotes any of the strings that appear
   136343 ** to be quoted.
   136344 **
   136345 ** If successful, output parameter *pazDequote is set to point at the
   136346 ** array of dequoted strings and SQLITE_OK is returned. The caller is
   136347 ** responsible for eventually calling sqlite3_free() to free the array
   136348 ** in this case. Or, if an error occurs, an SQLite error code is returned.
   136349 ** The final value of *pazDequote is undefined in this case.
   136350 */
   136351 static int fts3tokDequoteArray(
   136352   int argc,                       /* Number of elements in argv[] */
   136353   const char * const *argv,       /* Input array */
   136354   char ***pazDequote              /* Output array */
   136355 ){
   136356   int rc = SQLITE_OK;             /* Return code */
   136357   if( argc==0 ){
   136358     *pazDequote = 0;
   136359   }else{
   136360     int i;
   136361     int nByte = 0;
   136362     char **azDequote;
   136363 
   136364     for(i=0; i<argc; i++){
   136365       nByte += (int)(strlen(argv[i]) + 1);
   136366     }
   136367 
   136368     *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
   136369     if( azDequote==0 ){
   136370       rc = SQLITE_NOMEM;
   136371     }else{
   136372       char *pSpace = (char *)&azDequote[argc];
   136373       for(i=0; i<argc; i++){
   136374         int n = (int)strlen(argv[i]);
   136375         azDequote[i] = pSpace;
   136376         memcpy(pSpace, argv[i], n+1);
   136377         sqlite3Fts3Dequote(pSpace);
   136378         pSpace += (n+1);
   136379       }
   136380     }
   136381   }
   136382 
   136383   return rc;
   136384 }
   136385 
   136386 /*
   136387 ** Schema of the tokenizer table.
   136388 */
   136389 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
   136390 
   136391 /*
   136392 ** This function does all the work for both the xConnect and xCreate methods.
   136393 ** These tables have no persistent representation of their own, so xConnect
   136394 ** and xCreate are identical operations.
   136395 **
   136396 **   argv[0]: module name
   136397 **   argv[1]: database name
   136398 **   argv[2]: table name
   136399 **   argv[3]: first argument (tokenizer name)
   136400 */
   136401 static int fts3tokConnectMethod(
   136402   sqlite3 *db,                    /* Database connection */
   136403   void *pHash,                    /* Hash table of tokenizers */
   136404   int argc,                       /* Number of elements in argv array */
   136405   const char * const *argv,       /* xCreate/xConnect argument array */
   136406   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   136407   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   136408 ){
   136409   Fts3tokTable *pTab;
   136410   const sqlite3_tokenizer_module *pMod = 0;
   136411   sqlite3_tokenizer *pTok = 0;
   136412   int rc;
   136413   char **azDequote = 0;
   136414   int nDequote;
   136415 
   136416   rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
   136417   if( rc!=SQLITE_OK ) return rc;
   136418 
   136419   nDequote = argc-3;
   136420   rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
   136421 
   136422   if( rc==SQLITE_OK ){
   136423     const char *zModule;
   136424     if( nDequote<1 ){
   136425       zModule = "simple";
   136426     }else{
   136427       zModule = azDequote[0];
   136428     }
   136429     rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
   136430   }
   136431 
   136432   assert( (rc==SQLITE_OK)==(pMod!=0) );
   136433   if( rc==SQLITE_OK ){
   136434     const char * const *azArg = (const char * const *)&azDequote[1];
   136435     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
   136436   }
   136437 
   136438   if( rc==SQLITE_OK ){
   136439     pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
   136440     if( pTab==0 ){
   136441       rc = SQLITE_NOMEM;
   136442     }
   136443   }
   136444 
   136445   if( rc==SQLITE_OK ){
   136446     memset(pTab, 0, sizeof(Fts3tokTable));
   136447     pTab->pMod = pMod;
   136448     pTab->pTok = pTok;
   136449     *ppVtab = &pTab->base;
   136450   }else{
   136451     if( pTok ){
   136452       pMod->xDestroy(pTok);
   136453     }
   136454   }
   136455 
   136456   sqlite3_free(azDequote);
   136457   return rc;
   136458 }
   136459 
   136460 /*
   136461 ** This function does the work for both the xDisconnect and xDestroy methods.
   136462 ** These tables have no persistent representation of their own, so xDisconnect
   136463 ** and xDestroy are identical operations.
   136464 */
   136465 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
   136466   Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
   136467 
   136468   pTab->pMod->xDestroy(pTab->pTok);
   136469   sqlite3_free(pTab);
   136470   return SQLITE_OK;
   136471 }
   136472 
   136473 /*
   136474 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
   136475 */
   136476 static int fts3tokBestIndexMethod(
   136477   sqlite3_vtab *pVTab,
   136478   sqlite3_index_info *pInfo
   136479 ){
   136480   int i;
   136481   UNUSED_PARAMETER(pVTab);
   136482 
   136483   for(i=0; i<pInfo->nConstraint; i++){
   136484     if( pInfo->aConstraint[i].usable
   136485      && pInfo->aConstraint[i].iColumn==0
   136486      && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
   136487     ){
   136488       pInfo->idxNum = 1;
   136489       pInfo->aConstraintUsage[i].argvIndex = 1;
   136490       pInfo->aConstraintUsage[i].omit = 1;
   136491       pInfo->estimatedCost = 1;
   136492       return SQLITE_OK;
   136493     }
   136494   }
   136495 
   136496   pInfo->idxNum = 0;
   136497   assert( pInfo->estimatedCost>1000000.0 );
   136498 
   136499   return SQLITE_OK;
   136500 }
   136501 
   136502 /*
   136503 ** xOpen - Open a cursor.
   136504 */
   136505 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   136506   Fts3tokCursor *pCsr;
   136507   UNUSED_PARAMETER(pVTab);
   136508 
   136509   pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
   136510   if( pCsr==0 ){
   136511     return SQLITE_NOMEM;
   136512   }
   136513   memset(pCsr, 0, sizeof(Fts3tokCursor));
   136514 
   136515   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
   136516   return SQLITE_OK;
   136517 }
   136518 
   136519 /*
   136520 ** Reset the tokenizer cursor passed as the only argument. As if it had
   136521 ** just been returned by fts3tokOpenMethod().
   136522 */
   136523 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
   136524   if( pCsr->pCsr ){
   136525     Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
   136526     pTab->pMod->xClose(pCsr->pCsr);
   136527     pCsr->pCsr = 0;
   136528   }
   136529   sqlite3_free(pCsr->zInput);
   136530   pCsr->zInput = 0;
   136531   pCsr->zToken = 0;
   136532   pCsr->nToken = 0;
   136533   pCsr->iStart = 0;
   136534   pCsr->iEnd = 0;
   136535   pCsr->iPos = 0;
   136536   pCsr->iRowid = 0;
   136537 }
   136538 
   136539 /*
   136540 ** xClose - Close a cursor.
   136541 */
   136542 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
   136543   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136544 
   136545   fts3tokResetCursor(pCsr);
   136546   sqlite3_free(pCsr);
   136547   return SQLITE_OK;
   136548 }
   136549 
   136550 /*
   136551 ** xNext - Advance the cursor to the next row, if any.
   136552 */
   136553 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
   136554   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136555   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
   136556   int rc;                         /* Return code */
   136557 
   136558   pCsr->iRowid++;
   136559   rc = pTab->pMod->xNext(pCsr->pCsr,
   136560       &pCsr->zToken, &pCsr->nToken,
   136561       &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
   136562   );
   136563 
   136564   if( rc!=SQLITE_OK ){
   136565     fts3tokResetCursor(pCsr);
   136566     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   136567   }
   136568 
   136569   return rc;
   136570 }
   136571 
   136572 /*
   136573 ** xFilter - Initialize a cursor to point at the start of its data.
   136574 */
   136575 static int fts3tokFilterMethod(
   136576   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   136577   int idxNum,                     /* Strategy index */
   136578   const char *idxStr,             /* Unused */
   136579   int nVal,                       /* Number of elements in apVal */
   136580   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   136581 ){
   136582   int rc = SQLITE_ERROR;
   136583   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136584   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
   136585   UNUSED_PARAMETER(idxStr);
   136586   UNUSED_PARAMETER(nVal);
   136587 
   136588   fts3tokResetCursor(pCsr);
   136589   if( idxNum==1 ){
   136590     const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
   136591     int nByte = sqlite3_value_bytes(apVal[0]);
   136592     pCsr->zInput = sqlite3_malloc(nByte+1);
   136593     if( pCsr->zInput==0 ){
   136594       rc = SQLITE_NOMEM;
   136595     }else{
   136596       memcpy(pCsr->zInput, zByte, nByte);
   136597       pCsr->zInput[nByte] = 0;
   136598       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
   136599       if( rc==SQLITE_OK ){
   136600         pCsr->pCsr->pTokenizer = pTab->pTok;
   136601       }
   136602     }
   136603   }
   136604 
   136605   if( rc!=SQLITE_OK ) return rc;
   136606   return fts3tokNextMethod(pCursor);
   136607 }
   136608 
   136609 /*
   136610 ** xEof - Return true if the cursor is at EOF, or false otherwise.
   136611 */
   136612 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
   136613   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136614   return (pCsr->zToken==0);
   136615 }
   136616 
   136617 /*
   136618 ** xColumn - Return a column value.
   136619 */
   136620 static int fts3tokColumnMethod(
   136621   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   136622   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   136623   int iCol                        /* Index of column to read value from */
   136624 ){
   136625   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136626 
   136627   /* CREATE TABLE x(input, token, start, end, position) */
   136628   switch( iCol ){
   136629     case 0:
   136630       sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
   136631       break;
   136632     case 1:
   136633       sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
   136634       break;
   136635     case 2:
   136636       sqlite3_result_int(pCtx, pCsr->iStart);
   136637       break;
   136638     case 3:
   136639       sqlite3_result_int(pCtx, pCsr->iEnd);
   136640       break;
   136641     default:
   136642       assert( iCol==4 );
   136643       sqlite3_result_int(pCtx, pCsr->iPos);
   136644       break;
   136645   }
   136646   return SQLITE_OK;
   136647 }
   136648 
   136649 /*
   136650 ** xRowid - Return the current rowid for the cursor.
   136651 */
   136652 static int fts3tokRowidMethod(
   136653   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   136654   sqlite_int64 *pRowid            /* OUT: Rowid value */
   136655 ){
   136656   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   136657   *pRowid = (sqlite3_int64)pCsr->iRowid;
   136658   return SQLITE_OK;
   136659 }
   136660 
   136661 /*
   136662 ** Register the fts3tok module with database connection db. Return SQLITE_OK
   136663 ** if successful or an error code if sqlite3_create_module() fails.
   136664 */
   136665 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
   136666   static const sqlite3_module fts3tok_module = {
   136667      0,                           /* iVersion      */
   136668      fts3tokConnectMethod,        /* xCreate       */
   136669      fts3tokConnectMethod,        /* xConnect      */
   136670      fts3tokBestIndexMethod,      /* xBestIndex    */
   136671      fts3tokDisconnectMethod,     /* xDisconnect   */
   136672      fts3tokDisconnectMethod,     /* xDestroy      */
   136673      fts3tokOpenMethod,           /* xOpen         */
   136674      fts3tokCloseMethod,          /* xClose        */
   136675      fts3tokFilterMethod,         /* xFilter       */
   136676      fts3tokNextMethod,           /* xNext         */
   136677      fts3tokEofMethod,            /* xEof          */
   136678      fts3tokColumnMethod,         /* xColumn       */
   136679      fts3tokRowidMethod,          /* xRowid        */
   136680      0,                           /* xUpdate       */
   136681      0,                           /* xBegin        */
   136682      0,                           /* xSync         */
   136683      0,                           /* xCommit       */
   136684      0,                           /* xRollback     */
   136685      0,                           /* xFindFunction */
   136686      0,                           /* xRename       */
   136687      0,                           /* xSavepoint    */
   136688      0,                           /* xRelease      */
   136689      0                            /* xRollbackTo   */
   136690   };
   136691   int rc;                         /* Return code */
   136692 
   136693   rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
   136694   return rc;
   136695 }
   136696 
   136697 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   136698 
   136699 /************** End of fts3_tokenize_vtab.c **********************************/
   136700 /************** Begin file fts3_write.c **************************************/
   136701 /*
   136702 ** 2009 Oct 23
   136703 **
   136704 ** The author disclaims copyright to this source code.  In place of
   136705 ** a legal notice, here is a blessing:
   136706 **
   136707 **    May you do good and not evil.
   136708 **    May you find forgiveness for yourself and forgive others.
   136709 **    May you share freely, never taking more than you give.
   136710 **
   136711 ******************************************************************************
   136712 **
   136713 ** This file is part of the SQLite FTS3 extension module. Specifically,
   136714 ** this file contains code to insert, update and delete rows from FTS3
   136715 ** tables. It also contains code to merge FTS3 b-tree segments. Some
   136716 ** of the sub-routines used to merge segments are also used by the query
   136717 ** code in fts3.c.
   136718 */
   136719 
   136720 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   136721 
   136722 /* #include <string.h> */
   136723 /* #include <assert.h> */
   136724 /* #include <stdlib.h> */
   136725 
   136726 
   136727 #define FTS_MAX_APPENDABLE_HEIGHT 16
   136728 
   136729 /*
   136730 ** When full-text index nodes are loaded from disk, the buffer that they
   136731 ** are loaded into has the following number of bytes of padding at the end
   136732 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
   136733 ** of 920 bytes is allocated for it.
   136734 **
   136735 ** This means that if we have a pointer into a buffer containing node data,
   136736 ** it is always safe to read up to two varints from it without risking an
   136737 ** overread, even if the node data is corrupted.
   136738 */
   136739 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
   136740 
   136741 /*
   136742 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
   136743 ** memory incrementally instead of all at once. This can be a big performance
   136744 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
   136745 ** method before retrieving all query results (as may happen, for example,
   136746 ** if a query has a LIMIT clause).
   136747 **
   136748 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
   136749 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
   136750 ** The code is written so that the hard lower-limit for each of these values
   136751 ** is 1. Clearly such small values would be inefficient, but can be useful
   136752 ** for testing purposes.
   136753 **
   136754 ** If this module is built with SQLITE_TEST defined, these constants may
   136755 ** be overridden at runtime for testing purposes. File fts3_test.c contains
   136756 ** a Tcl interface to read and write the values.
   136757 */
   136758 #ifdef SQLITE_TEST
   136759 int test_fts3_node_chunksize = (4*1024);
   136760 int test_fts3_node_chunk_threshold = (4*1024)*4;
   136761 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
   136762 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
   136763 #else
   136764 # define FTS3_NODE_CHUNKSIZE (4*1024)
   136765 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
   136766 #endif
   136767 
   136768 /*
   136769 ** The two values that may be meaningfully bound to the :1 parameter in
   136770 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
   136771 */
   136772 #define FTS_STAT_DOCTOTAL      0
   136773 #define FTS_STAT_INCRMERGEHINT 1
   136774 #define FTS_STAT_AUTOINCRMERGE 2
   136775 
   136776 /*
   136777 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
   136778 ** and incremental merge operation that takes place. This is used for
   136779 ** debugging FTS only, it should not usually be turned on in production
   136780 ** systems.
   136781 */
   136782 #ifdef FTS3_LOG_MERGES
   136783 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
   136784   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
   136785 }
   136786 #else
   136787 #define fts3LogMerge(x, y)
   136788 #endif
   136789 
   136790 
   136791 typedef struct PendingList PendingList;
   136792 typedef struct SegmentNode SegmentNode;
   136793 typedef struct SegmentWriter SegmentWriter;
   136794 
   136795 /*
   136796 ** An instance of the following data structure is used to build doclists
   136797 ** incrementally. See function fts3PendingListAppend() for details.
   136798 */
   136799 struct PendingList {
   136800   int nData;
   136801   char *aData;
   136802   int nSpace;
   136803   sqlite3_int64 iLastDocid;
   136804   sqlite3_int64 iLastCol;
   136805   sqlite3_int64 iLastPos;
   136806 };
   136807 
   136808 
   136809 /*
   136810 ** Each cursor has a (possibly empty) linked list of the following objects.
   136811 */
   136812 struct Fts3DeferredToken {
   136813   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
   136814   int iCol;                       /* Column token must occur in */
   136815   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
   136816   PendingList *pList;             /* Doclist is assembled here */
   136817 };
   136818 
   136819 /*
   136820 ** An instance of this structure is used to iterate through the terms on
   136821 ** a contiguous set of segment b-tree leaf nodes. Although the details of
   136822 ** this structure are only manipulated by code in this file, opaque handles
   136823 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
   136824 ** terms when querying the full-text index. See functions:
   136825 **
   136826 **   sqlite3Fts3SegReaderNew()
   136827 **   sqlite3Fts3SegReaderFree()
   136828 **   sqlite3Fts3SegReaderIterate()
   136829 **
   136830 ** Methods used to manipulate Fts3SegReader structures:
   136831 **
   136832 **   fts3SegReaderNext()
   136833 **   fts3SegReaderFirstDocid()
   136834 **   fts3SegReaderNextDocid()
   136835 */
   136836 struct Fts3SegReader {
   136837   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
   136838   u8 bLookup;                     /* True for a lookup only */
   136839   u8 rootOnly;                    /* True for a root-only reader */
   136840 
   136841   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
   136842   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
   136843   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
   136844   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
   136845 
   136846   char *aNode;                    /* Pointer to node data (or NULL) */
   136847   int nNode;                      /* Size of buffer at aNode (or 0) */
   136848   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
   136849   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
   136850 
   136851   Fts3HashElem **ppNextElem;
   136852 
   136853   /* Variables set by fts3SegReaderNext(). These may be read directly
   136854   ** by the caller. They are valid from the time SegmentReaderNew() returns
   136855   ** until SegmentReaderNext() returns something other than SQLITE_OK
   136856   ** (i.e. SQLITE_DONE).
   136857   */
   136858   int nTerm;                      /* Number of bytes in current term */
   136859   char *zTerm;                    /* Pointer to current term */
   136860   int nTermAlloc;                 /* Allocated size of zTerm buffer */
   136861   char *aDoclist;                 /* Pointer to doclist of current entry */
   136862   int nDoclist;                   /* Size of doclist in current entry */
   136863 
   136864   /* The following variables are used by fts3SegReaderNextDocid() to iterate
   136865   ** through the current doclist (aDoclist/nDoclist).
   136866   */
   136867   char *pOffsetList;
   136868   int nOffsetList;                /* For descending pending seg-readers only */
   136869   sqlite3_int64 iDocid;
   136870 };
   136871 
   136872 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
   136873 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
   136874 
   136875 /*
   136876 ** An instance of this structure is used to create a segment b-tree in the
   136877 ** database. The internal details of this type are only accessed by the
   136878 ** following functions:
   136879 **
   136880 **   fts3SegWriterAdd()
   136881 **   fts3SegWriterFlush()
   136882 **   fts3SegWriterFree()
   136883 */
   136884 struct SegmentWriter {
   136885   SegmentNode *pTree;             /* Pointer to interior tree structure */
   136886   sqlite3_int64 iFirst;           /* First slot in %_segments written */
   136887   sqlite3_int64 iFree;            /* Next free slot in %_segments */
   136888   char *zTerm;                    /* Pointer to previous term buffer */
   136889   int nTerm;                      /* Number of bytes in zTerm */
   136890   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   136891   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   136892   int nSize;                      /* Size of allocation at aData */
   136893   int nData;                      /* Bytes of data in aData */
   136894   char *aData;                    /* Pointer to block from malloc() */
   136895   i64 nLeafData;                  /* Number of bytes of leaf data written */
   136896 };
   136897 
   136898 /*
   136899 ** Type SegmentNode is used by the following three functions to create
   136900 ** the interior part of the segment b+-tree structures (everything except
   136901 ** the leaf nodes). These functions and type are only ever used by code
   136902 ** within the fts3SegWriterXXX() family of functions described above.
   136903 **
   136904 **   fts3NodeAddTerm()
   136905 **   fts3NodeWrite()
   136906 **   fts3NodeFree()
   136907 **
   136908 ** When a b+tree is written to the database (either as a result of a merge
   136909 ** or the pending-terms table being flushed), leaves are written into the
   136910 ** database file as soon as they are completely populated. The interior of
   136911 ** the tree is assembled in memory and written out only once all leaves have
   136912 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
   136913 ** very large, meaning that the interior of the tree consumes relatively
   136914 ** little memory.
   136915 */
   136916 struct SegmentNode {
   136917   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
   136918   SegmentNode *pRight;            /* Pointer to right-sibling */
   136919   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
   136920   int nEntry;                     /* Number of terms written to node so far */
   136921   char *zTerm;                    /* Pointer to previous term buffer */
   136922   int nTerm;                      /* Number of bytes in zTerm */
   136923   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   136924   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   136925   int nData;                      /* Bytes of valid data so far */
   136926   char *aData;                    /* Node data */
   136927 };
   136928 
   136929 /*
   136930 ** Valid values for the second argument to fts3SqlStmt().
   136931 */
   136932 #define SQL_DELETE_CONTENT             0
   136933 #define SQL_IS_EMPTY                   1
   136934 #define SQL_DELETE_ALL_CONTENT         2
   136935 #define SQL_DELETE_ALL_SEGMENTS        3
   136936 #define SQL_DELETE_ALL_SEGDIR          4
   136937 #define SQL_DELETE_ALL_DOCSIZE         5
   136938 #define SQL_DELETE_ALL_STAT            6
   136939 #define SQL_SELECT_CONTENT_BY_ROWID    7
   136940 #define SQL_NEXT_SEGMENT_INDEX         8
   136941 #define SQL_INSERT_SEGMENTS            9
   136942 #define SQL_NEXT_SEGMENTS_ID          10
   136943 #define SQL_INSERT_SEGDIR             11
   136944 #define SQL_SELECT_LEVEL              12
   136945 #define SQL_SELECT_LEVEL_RANGE        13
   136946 #define SQL_SELECT_LEVEL_COUNT        14
   136947 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
   136948 #define SQL_DELETE_SEGDIR_LEVEL       16
   136949 #define SQL_DELETE_SEGMENTS_RANGE     17
   136950 #define SQL_CONTENT_INSERT            18
   136951 #define SQL_DELETE_DOCSIZE            19
   136952 #define SQL_REPLACE_DOCSIZE           20
   136953 #define SQL_SELECT_DOCSIZE            21
   136954 #define SQL_SELECT_STAT               22
   136955 #define SQL_REPLACE_STAT              23
   136956 
   136957 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
   136958 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
   136959 #define SQL_DELETE_SEGDIR_RANGE       26
   136960 #define SQL_SELECT_ALL_LANGID         27
   136961 #define SQL_FIND_MERGE_LEVEL          28
   136962 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
   136963 #define SQL_DELETE_SEGDIR_ENTRY       30
   136964 #define SQL_SHIFT_SEGDIR_ENTRY        31
   136965 #define SQL_SELECT_SEGDIR             32
   136966 #define SQL_CHOMP_SEGDIR              33
   136967 #define SQL_SEGMENT_IS_APPENDABLE     34
   136968 #define SQL_SELECT_INDEXES            35
   136969 #define SQL_SELECT_MXLEVEL            36
   136970 
   136971 #define SQL_SELECT_LEVEL_RANGE2       37
   136972 #define SQL_UPDATE_LEVEL_IDX          38
   136973 #define SQL_UPDATE_LEVEL              39
   136974 
   136975 /*
   136976 ** This function is used to obtain an SQLite prepared statement handle
   136977 ** for the statement identified by the second argument. If successful,
   136978 ** *pp is set to the requested statement handle and SQLITE_OK returned.
   136979 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
   136980 **
   136981 ** If argument apVal is not NULL, then it must point to an array with
   136982 ** at least as many entries as the requested statement has bound
   136983 ** parameters. The values are bound to the statements parameters before
   136984 ** returning.
   136985 */
   136986 static int fts3SqlStmt(
   136987   Fts3Table *p,                   /* Virtual table handle */
   136988   int eStmt,                      /* One of the SQL_XXX constants above */
   136989   sqlite3_stmt **pp,              /* OUT: Statement handle */
   136990   sqlite3_value **apVal           /* Values to bind to statement */
   136991 ){
   136992   const char *azSql[] = {
   136993 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
   136994 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
   136995 /* 2  */  "DELETE FROM %Q.'%q_content'",
   136996 /* 3  */  "DELETE FROM %Q.'%q_segments'",
   136997 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
   136998 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
   136999 /* 6  */  "DELETE FROM %Q.'%q_stat'",
   137000 /* 7  */  "SELECT %s WHERE rowid=?",
   137001 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
   137002 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
   137003 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
   137004 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
   137005 
   137006           /* Return segments in order from oldest to newest.*/
   137007 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   137008             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
   137009 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   137010             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
   137011             "ORDER BY level DESC, idx ASC",
   137012 
   137013 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
   137014 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   137015 
   137016 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
   137017 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
   137018 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
   137019 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
   137020 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
   137021 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
   137022 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
   137023 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
   137024 /* 24 */  "",
   137025 /* 25 */  "",
   137026 
   137027 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   137028 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
   137029 
   137030 /* This statement is used to determine which level to read the input from
   137031 ** when performing an incremental merge. It returns the absolute level number
   137032 ** of the oldest level in the db that contains at least ? segments. Or,
   137033 ** if no level in the FTS index contains more than ? segments, the statement
   137034 ** returns zero rows.  */
   137035 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
   137036          "  ORDER BY (level %% 1024) ASC LIMIT 1",
   137037 
   137038 /* Estimate the upper limit on the number of leaf nodes in a new segment
   137039 ** created by merging the oldest :2 segments from absolute level :1. See
   137040 ** function sqlite3Fts3Incrmerge() for details.  */
   137041 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
   137042          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
   137043 
   137044 /* SQL_DELETE_SEGDIR_ENTRY
   137045 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
   137046 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
   137047 
   137048 /* SQL_SHIFT_SEGDIR_ENTRY
   137049 **   Modify the idx value for the segment with idx=:3 on absolute level :2
   137050 **   to :1.  */
   137051 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
   137052 
   137053 /* SQL_SELECT_SEGDIR
   137054 **   Read a single entry from the %_segdir table. The entry from absolute
   137055 **   level :1 with index value :2.  */
   137056 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   137057             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
   137058 
   137059 /* SQL_CHOMP_SEGDIR
   137060 **   Update the start_block (:1) and root (:2) fields of the %_segdir
   137061 **   entry located on absolute level :3 with index :4.  */
   137062 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
   137063             "WHERE level = ? AND idx = ?",
   137064 
   137065 /* SQL_SEGMENT_IS_APPENDABLE
   137066 **   Return a single row if the segment with end_block=? is appendable. Or
   137067 **   no rows otherwise.  */
   137068 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
   137069 
   137070 /* SQL_SELECT_INDEXES
   137071 **   Return the list of valid segment indexes for absolute level ?  */
   137072 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
   137073 
   137074 /* SQL_SELECT_MXLEVEL
   137075 **   Return the largest relative level in the FTS index or indexes.  */
   137076 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
   137077 
   137078           /* Return segments in order from oldest to newest.*/
   137079 /* 37 */  "SELECT level, idx, end_block "
   137080             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
   137081             "ORDER BY level DESC, idx ASC",
   137082 
   137083           /* Update statements used while promoting segments */
   137084 /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
   137085             "WHERE level=? AND idx=?",
   137086 /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
   137087 
   137088   };
   137089   int rc = SQLITE_OK;
   137090   sqlite3_stmt *pStmt;
   137091 
   137092   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
   137093   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
   137094 
   137095   pStmt = p->aStmt[eStmt];
   137096   if( !pStmt ){
   137097     char *zSql;
   137098     if( eStmt==SQL_CONTENT_INSERT ){
   137099       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
   137100     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
   137101       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
   137102     }else{
   137103       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
   137104     }
   137105     if( !zSql ){
   137106       rc = SQLITE_NOMEM;
   137107     }else{
   137108       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
   137109       sqlite3_free(zSql);
   137110       assert( rc==SQLITE_OK || pStmt==0 );
   137111       p->aStmt[eStmt] = pStmt;
   137112     }
   137113   }
   137114   if( apVal ){
   137115     int i;
   137116     int nParam = sqlite3_bind_parameter_count(pStmt);
   137117     for(i=0; rc==SQLITE_OK && i<nParam; i++){
   137118       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
   137119     }
   137120   }
   137121   *pp = pStmt;
   137122   return rc;
   137123 }
   137124 
   137125 
   137126 static int fts3SelectDocsize(
   137127   Fts3Table *pTab,                /* FTS3 table handle */
   137128   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
   137129   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   137130 ){
   137131   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
   137132   int rc;                         /* Return code */
   137133 
   137134   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
   137135   if( rc==SQLITE_OK ){
   137136     sqlite3_bind_int64(pStmt, 1, iDocid);
   137137     rc = sqlite3_step(pStmt);
   137138     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
   137139       rc = sqlite3_reset(pStmt);
   137140       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
   137141       pStmt = 0;
   137142     }else{
   137143       rc = SQLITE_OK;
   137144     }
   137145   }
   137146 
   137147   *ppStmt = pStmt;
   137148   return rc;
   137149 }
   137150 
   137151 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
   137152   Fts3Table *pTab,                /* Fts3 table handle */
   137153   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   137154 ){
   137155   sqlite3_stmt *pStmt = 0;
   137156   int rc;
   137157   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
   137158   if( rc==SQLITE_OK ){
   137159     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   137160     if( sqlite3_step(pStmt)!=SQLITE_ROW
   137161      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
   137162     ){
   137163       rc = sqlite3_reset(pStmt);
   137164       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
   137165       pStmt = 0;
   137166     }
   137167   }
   137168   *ppStmt = pStmt;
   137169   return rc;
   137170 }
   137171 
   137172 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
   137173   Fts3Table *pTab,                /* Fts3 table handle */
   137174   sqlite3_int64 iDocid,           /* Docid to read size data for */
   137175   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   137176 ){
   137177   return fts3SelectDocsize(pTab, iDocid, ppStmt);
   137178 }
   137179 
   137180 /*
   137181 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
   137182 ** array apVal[] to the SQL statement identified by eStmt, the statement
   137183 ** is executed.
   137184 **
   137185 ** Returns SQLITE_OK if the statement is successfully executed, or an
   137186 ** SQLite error code otherwise.
   137187 */
   137188 static void fts3SqlExec(
   137189   int *pRC,                /* Result code */
   137190   Fts3Table *p,            /* The FTS3 table */
   137191   int eStmt,               /* Index of statement to evaluate */
   137192   sqlite3_value **apVal    /* Parameters to bind */
   137193 ){
   137194   sqlite3_stmt *pStmt;
   137195   int rc;
   137196   if( *pRC ) return;
   137197   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
   137198   if( rc==SQLITE_OK ){
   137199     sqlite3_step(pStmt);
   137200     rc = sqlite3_reset(pStmt);
   137201   }
   137202   *pRC = rc;
   137203 }
   137204 
   137205 
   137206 /*
   137207 ** This function ensures that the caller has obtained an exclusive
   137208 ** shared-cache table-lock on the %_segdir table. This is required before
   137209 ** writing data to the fts3 table. If this lock is not acquired first, then
   137210 ** the caller may end up attempting to take this lock as part of committing
   137211 ** a transaction, causing SQLite to return SQLITE_LOCKED or
   137212 ** LOCKED_SHAREDCACHEto a COMMIT command.
   137213 **
   137214 ** It is best to avoid this because if FTS3 returns any error when
   137215 ** committing a transaction, the whole transaction will be rolled back.
   137216 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
   137217 ** It can still happen if the user locks the underlying tables directly
   137218 ** instead of accessing them via FTS.
   137219 */
   137220 static int fts3Writelock(Fts3Table *p){
   137221   int rc = SQLITE_OK;
   137222 
   137223   if( p->nPendingData==0 ){
   137224     sqlite3_stmt *pStmt;
   137225     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
   137226     if( rc==SQLITE_OK ){
   137227       sqlite3_bind_null(pStmt, 1);
   137228       sqlite3_step(pStmt);
   137229       rc = sqlite3_reset(pStmt);
   137230     }
   137231   }
   137232 
   137233   return rc;
   137234 }
   137235 
   137236 /*
   137237 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
   137238 ** Within each language id, a separate index is maintained to store the
   137239 ** document terms, and each configured prefix size (configured the FTS
   137240 ** "prefix=" option). And each index consists of multiple levels ("relative
   137241 ** levels").
   137242 **
   137243 ** All three of these values (the language id, the specific index and the
   137244 ** level within the index) are encoded in 64-bit integer values stored
   137245 ** in the %_segdir table on disk. This function is used to convert three
   137246 ** separate component values into the single 64-bit integer value that
   137247 ** can be used to query the %_segdir table.
   137248 **
   137249 ** Specifically, each language-id/index combination is allocated 1024
   137250 ** 64-bit integer level values ("absolute levels"). The main terms index
   137251 ** for language-id 0 is allocate values 0-1023. The first prefix index
   137252 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
   137253 ** Language 1 indexes are allocated immediately following language 0.
   137254 **
   137255 ** So, for a system with nPrefix prefix indexes configured, the block of
   137256 ** absolute levels that corresponds to language-id iLangid and index
   137257 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
   137258 */
   137259 static sqlite3_int64 getAbsoluteLevel(
   137260   Fts3Table *p,                   /* FTS3 table handle */
   137261   int iLangid,                    /* Language id */
   137262   int iIndex,                     /* Index in p->aIndex[] */
   137263   int iLevel                      /* Level of segments */
   137264 ){
   137265   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
   137266   assert( iLangid>=0 );
   137267   assert( p->nIndex>0 );
   137268   assert( iIndex>=0 && iIndex<p->nIndex );
   137269 
   137270   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
   137271   return iBase + iLevel;
   137272 }
   137273 
   137274 /*
   137275 ** Set *ppStmt to a statement handle that may be used to iterate through
   137276 ** all rows in the %_segdir table, from oldest to newest. If successful,
   137277 ** return SQLITE_OK. If an error occurs while preparing the statement,
   137278 ** return an SQLite error code.
   137279 **
   137280 ** There is only ever one instance of this SQL statement compiled for
   137281 ** each FTS3 table.
   137282 **
   137283 ** The statement returns the following columns from the %_segdir table:
   137284 **
   137285 **   0: idx
   137286 **   1: start_block
   137287 **   2: leaves_end_block
   137288 **   3: end_block
   137289 **   4: root
   137290 */
   137291 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
   137292   Fts3Table *p,                   /* FTS3 table */
   137293   int iLangid,                    /* Language being queried */
   137294   int iIndex,                     /* Index for p->aIndex[] */
   137295   int iLevel,                     /* Level to select (relative level) */
   137296   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
   137297 ){
   137298   int rc;
   137299   sqlite3_stmt *pStmt = 0;
   137300 
   137301   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
   137302   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   137303   assert( iIndex>=0 && iIndex<p->nIndex );
   137304 
   137305   if( iLevel<0 ){
   137306     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
   137307     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
   137308     if( rc==SQLITE_OK ){
   137309       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   137310       sqlite3_bind_int64(pStmt, 2,
   137311           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   137312       );
   137313     }
   137314   }else{
   137315     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
   137316     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
   137317     if( rc==SQLITE_OK ){
   137318       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
   137319     }
   137320   }
   137321   *ppStmt = pStmt;
   137322   return rc;
   137323 }
   137324 
   137325 
   137326 /*
   137327 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
   137328 ** if successful, or an SQLite error code otherwise.
   137329 **
   137330 ** This function also serves to allocate the PendingList structure itself.
   137331 ** For example, to create a new PendingList structure containing two
   137332 ** varints:
   137333 **
   137334 **   PendingList *p = 0;
   137335 **   fts3PendingListAppendVarint(&p, 1);
   137336 **   fts3PendingListAppendVarint(&p, 2);
   137337 */
   137338 static int fts3PendingListAppendVarint(
   137339   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
   137340   sqlite3_int64 i                 /* Value to append to data */
   137341 ){
   137342   PendingList *p = *pp;
   137343 
   137344   /* Allocate or grow the PendingList as required. */
   137345   if( !p ){
   137346     p = sqlite3_malloc(sizeof(*p) + 100);
   137347     if( !p ){
   137348       return SQLITE_NOMEM;
   137349     }
   137350     p->nSpace = 100;
   137351     p->aData = (char *)&p[1];
   137352     p->nData = 0;
   137353   }
   137354   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
   137355     int nNew = p->nSpace * 2;
   137356     p = sqlite3_realloc(p, sizeof(*p) + nNew);
   137357     if( !p ){
   137358       sqlite3_free(*pp);
   137359       *pp = 0;
   137360       return SQLITE_NOMEM;
   137361     }
   137362     p->nSpace = nNew;
   137363     p->aData = (char *)&p[1];
   137364   }
   137365 
   137366   /* Append the new serialized varint to the end of the list. */
   137367   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
   137368   p->aData[p->nData] = '\0';
   137369   *pp = p;
   137370   return SQLITE_OK;
   137371 }
   137372 
   137373 /*
   137374 ** Add a docid/column/position entry to a PendingList structure. Non-zero
   137375 ** is returned if the structure is sqlite3_realloced as part of adding
   137376 ** the entry. Otherwise, zero.
   137377 **
   137378 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
   137379 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
   137380 ** it is set to SQLITE_OK.
   137381 */
   137382 static int fts3PendingListAppend(
   137383   PendingList **pp,               /* IN/OUT: PendingList structure */
   137384   sqlite3_int64 iDocid,           /* Docid for entry to add */
   137385   sqlite3_int64 iCol,             /* Column for entry to add */
   137386   sqlite3_int64 iPos,             /* Position of term for entry to add */
   137387   int *pRc                        /* OUT: Return code */
   137388 ){
   137389   PendingList *p = *pp;
   137390   int rc = SQLITE_OK;
   137391 
   137392   assert( !p || p->iLastDocid<=iDocid );
   137393 
   137394   if( !p || p->iLastDocid!=iDocid ){
   137395     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
   137396     if( p ){
   137397       assert( p->nData<p->nSpace );
   137398       assert( p->aData[p->nData]==0 );
   137399       p->nData++;
   137400     }
   137401     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
   137402       goto pendinglistappend_out;
   137403     }
   137404     p->iLastCol = -1;
   137405     p->iLastPos = 0;
   137406     p->iLastDocid = iDocid;
   137407   }
   137408   if( iCol>0 && p->iLastCol!=iCol ){
   137409     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
   137410      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
   137411     ){
   137412       goto pendinglistappend_out;
   137413     }
   137414     p->iLastCol = iCol;
   137415     p->iLastPos = 0;
   137416   }
   137417   if( iCol>=0 ){
   137418     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
   137419     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
   137420     if( rc==SQLITE_OK ){
   137421       p->iLastPos = iPos;
   137422     }
   137423   }
   137424 
   137425  pendinglistappend_out:
   137426   *pRc = rc;
   137427   if( p!=*pp ){
   137428     *pp = p;
   137429     return 1;
   137430   }
   137431   return 0;
   137432 }
   137433 
   137434 /*
   137435 ** Free a PendingList object allocated by fts3PendingListAppend().
   137436 */
   137437 static void fts3PendingListDelete(PendingList *pList){
   137438   sqlite3_free(pList);
   137439 }
   137440 
   137441 /*
   137442 ** Add an entry to one of the pending-terms hash tables.
   137443 */
   137444 static int fts3PendingTermsAddOne(
   137445   Fts3Table *p,
   137446   int iCol,
   137447   int iPos,
   137448   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
   137449   const char *zToken,
   137450   int nToken
   137451 ){
   137452   PendingList *pList;
   137453   int rc = SQLITE_OK;
   137454 
   137455   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
   137456   if( pList ){
   137457     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
   137458   }
   137459   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
   137460     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
   137461       /* Malloc failed while inserting the new entry. This can only
   137462       ** happen if there was no previous entry for this token.
   137463       */
   137464       assert( 0==fts3HashFind(pHash, zToken, nToken) );
   137465       sqlite3_free(pList);
   137466       rc = SQLITE_NOMEM;
   137467     }
   137468   }
   137469   if( rc==SQLITE_OK ){
   137470     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
   137471   }
   137472   return rc;
   137473 }
   137474 
   137475 /*
   137476 ** Tokenize the nul-terminated string zText and add all tokens to the
   137477 ** pending-terms hash-table. The docid used is that currently stored in
   137478 ** p->iPrevDocid, and the column is specified by argument iCol.
   137479 **
   137480 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   137481 */
   137482 static int fts3PendingTermsAdd(
   137483   Fts3Table *p,                   /* Table into which text will be inserted */
   137484   int iLangid,                    /* Language id to use */
   137485   const char *zText,              /* Text of document to be inserted */
   137486   int iCol,                       /* Column into which text is being inserted */
   137487   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
   137488 ){
   137489   int rc;
   137490   int iStart = 0;
   137491   int iEnd = 0;
   137492   int iPos = 0;
   137493   int nWord = 0;
   137494 
   137495   char const *zToken;
   137496   int nToken = 0;
   137497 
   137498   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
   137499   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   137500   sqlite3_tokenizer_cursor *pCsr;
   137501   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
   137502       const char**,int*,int*,int*,int*);
   137503 
   137504   assert( pTokenizer && pModule );
   137505 
   137506   /* If the user has inserted a NULL value, this function may be called with
   137507   ** zText==0. In this case, add zero token entries to the hash table and
   137508   ** return early. */
   137509   if( zText==0 ){
   137510     *pnWord = 0;
   137511     return SQLITE_OK;
   137512   }
   137513 
   137514   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
   137515   if( rc!=SQLITE_OK ){
   137516     return rc;
   137517   }
   137518 
   137519   xNext = pModule->xNext;
   137520   while( SQLITE_OK==rc
   137521       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
   137522   ){
   137523     int i;
   137524     if( iPos>=nWord ) nWord = iPos+1;
   137525 
   137526     /* Positions cannot be negative; we use -1 as a terminator internally.
   137527     ** Tokens must have a non-zero length.
   137528     */
   137529     if( iPos<0 || !zToken || nToken<=0 ){
   137530       rc = SQLITE_ERROR;
   137531       break;
   137532     }
   137533 
   137534     /* Add the term to the terms index */
   137535     rc = fts3PendingTermsAddOne(
   137536         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
   137537     );
   137538 
   137539     /* Add the term to each of the prefix indexes that it is not too
   137540     ** short for. */
   137541     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
   137542       struct Fts3Index *pIndex = &p->aIndex[i];
   137543       if( nToken<pIndex->nPrefix ) continue;
   137544       rc = fts3PendingTermsAddOne(
   137545           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
   137546       );
   137547     }
   137548   }
   137549 
   137550   pModule->xClose(pCsr);
   137551   *pnWord += nWord;
   137552   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   137553 }
   137554 
   137555 /*
   137556 ** Calling this function indicates that subsequent calls to
   137557 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
   137558 ** contents of the document with docid iDocid.
   137559 */
   137560 static int fts3PendingTermsDocid(
   137561   Fts3Table *p,                   /* Full-text table handle */
   137562   int iLangid,                    /* Language id of row being written */
   137563   sqlite_int64 iDocid             /* Docid of row being written */
   137564 ){
   137565   assert( iLangid>=0 );
   137566 
   137567   /* TODO(shess) Explore whether partially flushing the buffer on
   137568   ** forced-flush would provide better performance.  I suspect that if
   137569   ** we ordered the doclists by size and flushed the largest until the
   137570   ** buffer was half empty, that would let the less frequent terms
   137571   ** generate longer doclists.
   137572   */
   137573   if( iDocid<=p->iPrevDocid
   137574    || p->iPrevLangid!=iLangid
   137575    || p->nPendingData>p->nMaxPendingData
   137576   ){
   137577     int rc = sqlite3Fts3PendingTermsFlush(p);
   137578     if( rc!=SQLITE_OK ) return rc;
   137579   }
   137580   p->iPrevDocid = iDocid;
   137581   p->iPrevLangid = iLangid;
   137582   return SQLITE_OK;
   137583 }
   137584 
   137585 /*
   137586 ** Discard the contents of the pending-terms hash tables.
   137587 */
   137588 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
   137589   int i;
   137590   for(i=0; i<p->nIndex; i++){
   137591     Fts3HashElem *pElem;
   137592     Fts3Hash *pHash = &p->aIndex[i].hPending;
   137593     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
   137594       PendingList *pList = (PendingList *)fts3HashData(pElem);
   137595       fts3PendingListDelete(pList);
   137596     }
   137597     fts3HashClear(pHash);
   137598   }
   137599   p->nPendingData = 0;
   137600 }
   137601 
   137602 /*
   137603 ** This function is called by the xUpdate() method as part of an INSERT
   137604 ** operation. It adds entries for each term in the new record to the
   137605 ** pendingTerms hash table.
   137606 **
   137607 ** Argument apVal is the same as the similarly named argument passed to
   137608 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
   137609 */
   137610 static int fts3InsertTerms(
   137611   Fts3Table *p,
   137612   int iLangid,
   137613   sqlite3_value **apVal,
   137614   u32 *aSz
   137615 ){
   137616   int i;                          /* Iterator variable */
   137617   for(i=2; i<p->nColumn+2; i++){
   137618     int iCol = i-2;
   137619     if( p->abNotindexed[iCol]==0 ){
   137620       const char *zText = (const char *)sqlite3_value_text(apVal[i]);
   137621       int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
   137622       if( rc!=SQLITE_OK ){
   137623         return rc;
   137624       }
   137625       aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
   137626     }
   137627   }
   137628   return SQLITE_OK;
   137629 }
   137630 
   137631 /*
   137632 ** This function is called by the xUpdate() method for an INSERT operation.
   137633 ** The apVal parameter is passed a copy of the apVal argument passed by
   137634 ** SQLite to the xUpdate() method. i.e:
   137635 **
   137636 **   apVal[0]                Not used for INSERT.
   137637 **   apVal[1]                rowid
   137638 **   apVal[2]                Left-most user-defined column
   137639 **   ...
   137640 **   apVal[p->nColumn+1]     Right-most user-defined column
   137641 **   apVal[p->nColumn+2]     Hidden column with same name as table
   137642 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
   137643 **   apVal[p->nColumn+4]     Hidden languageid column
   137644 */
   137645 static int fts3InsertData(
   137646   Fts3Table *p,                   /* Full-text table */
   137647   sqlite3_value **apVal,          /* Array of values to insert */
   137648   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
   137649 ){
   137650   int rc;                         /* Return code */
   137651   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
   137652 
   137653   if( p->zContentTbl ){
   137654     sqlite3_value *pRowid = apVal[p->nColumn+3];
   137655     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
   137656       pRowid = apVal[1];
   137657     }
   137658     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
   137659       return SQLITE_CONSTRAINT;
   137660     }
   137661     *piDocid = sqlite3_value_int64(pRowid);
   137662     return SQLITE_OK;
   137663   }
   137664 
   137665   /* Locate the statement handle used to insert data into the %_content
   137666   ** table. The SQL for this statement is:
   137667   **
   137668   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
   137669   **
   137670   ** The statement features N '?' variables, where N is the number of user
   137671   ** defined columns in the FTS3 table, plus one for the docid field.
   137672   */
   137673   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
   137674   if( rc==SQLITE_OK && p->zLanguageid ){
   137675     rc = sqlite3_bind_int(
   137676         pContentInsert, p->nColumn+2,
   137677         sqlite3_value_int(apVal[p->nColumn+4])
   137678     );
   137679   }
   137680   if( rc!=SQLITE_OK ) return rc;
   137681 
   137682   /* There is a quirk here. The users INSERT statement may have specified
   137683   ** a value for the "rowid" field, for the "docid" field, or for both.
   137684   ** Which is a problem, since "rowid" and "docid" are aliases for the
   137685   ** same value. For example:
   137686   **
   137687   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
   137688   **
   137689   ** In FTS3, this is an error. It is an error to specify non-NULL values
   137690   ** for both docid and some other rowid alias.
   137691   */
   137692   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
   137693     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
   137694      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
   137695     ){
   137696       /* A rowid/docid conflict. */
   137697       return SQLITE_ERROR;
   137698     }
   137699     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
   137700     if( rc!=SQLITE_OK ) return rc;
   137701   }
   137702 
   137703   /* Execute the statement to insert the record. Set *piDocid to the
   137704   ** new docid value.
   137705   */
   137706   sqlite3_step(pContentInsert);
   137707   rc = sqlite3_reset(pContentInsert);
   137708 
   137709   *piDocid = sqlite3_last_insert_rowid(p->db);
   137710   return rc;
   137711 }
   137712 
   137713 
   137714 
   137715 /*
   137716 ** Remove all data from the FTS3 table. Clear the hash table containing
   137717 ** pending terms.
   137718 */
   137719 static int fts3DeleteAll(Fts3Table *p, int bContent){
   137720   int rc = SQLITE_OK;             /* Return code */
   137721 
   137722   /* Discard the contents of the pending-terms hash table. */
   137723   sqlite3Fts3PendingTermsClear(p);
   137724 
   137725   /* Delete everything from the shadow tables. Except, leave %_content as
   137726   ** is if bContent is false.  */
   137727   assert( p->zContentTbl==0 || bContent==0 );
   137728   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
   137729   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
   137730   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
   137731   if( p->bHasDocsize ){
   137732     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
   137733   }
   137734   if( p->bHasStat ){
   137735     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
   137736   }
   137737   return rc;
   137738 }
   137739 
   137740 /*
   137741 **
   137742 */
   137743 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
   137744   int iLangid = 0;
   137745   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
   137746   return iLangid;
   137747 }
   137748 
   137749 /*
   137750 ** The first element in the apVal[] array is assumed to contain the docid
   137751 ** (an integer) of a row about to be deleted. Remove all terms from the
   137752 ** full-text index.
   137753 */
   137754 static void fts3DeleteTerms(
   137755   int *pRC,               /* Result code */
   137756   Fts3Table *p,           /* The FTS table to delete from */
   137757   sqlite3_value *pRowid,  /* The docid to be deleted */
   137758   u32 *aSz,               /* Sizes of deleted document written here */
   137759   int *pbFound            /* OUT: Set to true if row really does exist */
   137760 ){
   137761   int rc;
   137762   sqlite3_stmt *pSelect;
   137763 
   137764   assert( *pbFound==0 );
   137765   if( *pRC ) return;
   137766   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
   137767   if( rc==SQLITE_OK ){
   137768     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   137769       int i;
   137770       int iLangid = langidFromSelect(p, pSelect);
   137771       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
   137772       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
   137773         int iCol = i-1;
   137774         if( p->abNotindexed[iCol]==0 ){
   137775           const char *zText = (const char *)sqlite3_column_text(pSelect, i);
   137776           rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
   137777           aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
   137778         }
   137779       }
   137780       if( rc!=SQLITE_OK ){
   137781         sqlite3_reset(pSelect);
   137782         *pRC = rc;
   137783         return;
   137784       }
   137785       *pbFound = 1;
   137786     }
   137787     rc = sqlite3_reset(pSelect);
   137788   }else{
   137789     sqlite3_reset(pSelect);
   137790   }
   137791   *pRC = rc;
   137792 }
   137793 
   137794 /*
   137795 ** Forward declaration to account for the circular dependency between
   137796 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
   137797 */
   137798 static int fts3SegmentMerge(Fts3Table *, int, int, int);
   137799 
   137800 /*
   137801 ** This function allocates a new level iLevel index in the segdir table.
   137802 ** Usually, indexes are allocated within a level sequentially starting
   137803 ** with 0, so the allocated index is one greater than the value returned
   137804 ** by:
   137805 **
   137806 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
   137807 **
   137808 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
   137809 ** level, they are merged into a single level (iLevel+1) segment and the
   137810 ** allocated index is 0.
   137811 **
   137812 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
   137813 ** returned. Otherwise, an SQLite error code is returned.
   137814 */
   137815 static int fts3AllocateSegdirIdx(
   137816   Fts3Table *p,
   137817   int iLangid,                    /* Language id */
   137818   int iIndex,                     /* Index for p->aIndex */
   137819   int iLevel,
   137820   int *piIdx
   137821 ){
   137822   int rc;                         /* Return Code */
   137823   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
   137824   int iNext = 0;                  /* Result of query pNextIdx */
   137825 
   137826   assert( iLangid>=0 );
   137827   assert( p->nIndex>=1 );
   137828 
   137829   /* Set variable iNext to the next available segdir index at level iLevel. */
   137830   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
   137831   if( rc==SQLITE_OK ){
   137832     sqlite3_bind_int64(
   137833         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   137834     );
   137835     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
   137836       iNext = sqlite3_column_int(pNextIdx, 0);
   137837     }
   137838     rc = sqlite3_reset(pNextIdx);
   137839   }
   137840 
   137841   if( rc==SQLITE_OK ){
   137842     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
   137843     ** full, merge all segments in level iLevel into a single iLevel+1
   137844     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
   137845     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
   137846     */
   137847     if( iNext>=FTS3_MERGE_COUNT ){
   137848       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
   137849       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
   137850       *piIdx = 0;
   137851     }else{
   137852       *piIdx = iNext;
   137853     }
   137854   }
   137855 
   137856   return rc;
   137857 }
   137858 
   137859 /*
   137860 ** The %_segments table is declared as follows:
   137861 **
   137862 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
   137863 **
   137864 ** This function reads data from a single row of the %_segments table. The
   137865 ** specific row is identified by the iBlockid parameter. If paBlob is not
   137866 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
   137867 ** with the contents of the blob stored in the "block" column of the
   137868 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
   137869 ** to the size of the blob in bytes before returning.
   137870 **
   137871 ** If an error occurs, or the table does not contain the specified row,
   137872 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
   137873 ** paBlob is non-NULL, then it is the responsibility of the caller to
   137874 ** eventually free the returned buffer.
   137875 **
   137876 ** This function may leave an open sqlite3_blob* handle in the
   137877 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
   137878 ** to this function. The handle may be closed by calling the
   137879 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
   137880 ** performance improvement, but the blob handle should always be closed
   137881 ** before control is returned to the user (to prevent a lock being held
   137882 ** on the database file for longer than necessary). Thus, any virtual table
   137883 ** method (xFilter etc.) that may directly or indirectly call this function
   137884 ** must call sqlite3Fts3SegmentsClose() before returning.
   137885 */
   137886 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
   137887   Fts3Table *p,                   /* FTS3 table handle */
   137888   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
   137889   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
   137890   int *pnBlob,                    /* OUT: Size of blob data */
   137891   int *pnLoad                     /* OUT: Bytes actually loaded */
   137892 ){
   137893   int rc;                         /* Return code */
   137894 
   137895   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
   137896   assert( pnBlob );
   137897 
   137898   if( p->pSegments ){
   137899     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
   137900   }else{
   137901     if( 0==p->zSegmentsTbl ){
   137902       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
   137903       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
   137904     }
   137905     rc = sqlite3_blob_open(
   137906        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
   137907     );
   137908   }
   137909 
   137910   if( rc==SQLITE_OK ){
   137911     int nByte = sqlite3_blob_bytes(p->pSegments);
   137912     *pnBlob = nByte;
   137913     if( paBlob ){
   137914       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
   137915       if( !aByte ){
   137916         rc = SQLITE_NOMEM;
   137917       }else{
   137918         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
   137919           nByte = FTS3_NODE_CHUNKSIZE;
   137920           *pnLoad = nByte;
   137921         }
   137922         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
   137923         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
   137924         if( rc!=SQLITE_OK ){
   137925           sqlite3_free(aByte);
   137926           aByte = 0;
   137927         }
   137928       }
   137929       *paBlob = aByte;
   137930     }
   137931   }
   137932 
   137933   return rc;
   137934 }
   137935 
   137936 /*
   137937 ** Close the blob handle at p->pSegments, if it is open. See comments above
   137938 ** the sqlite3Fts3ReadBlock() function for details.
   137939 */
   137940 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
   137941   sqlite3_blob_close(p->pSegments);
   137942   p->pSegments = 0;
   137943 }
   137944 
   137945 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
   137946   int nRead;                      /* Number of bytes to read */
   137947   int rc;                         /* Return code */
   137948 
   137949   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
   137950   rc = sqlite3_blob_read(
   137951       pReader->pBlob,
   137952       &pReader->aNode[pReader->nPopulate],
   137953       nRead,
   137954       pReader->nPopulate
   137955   );
   137956 
   137957   if( rc==SQLITE_OK ){
   137958     pReader->nPopulate += nRead;
   137959     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
   137960     if( pReader->nPopulate==pReader->nNode ){
   137961       sqlite3_blob_close(pReader->pBlob);
   137962       pReader->pBlob = 0;
   137963       pReader->nPopulate = 0;
   137964     }
   137965   }
   137966   return rc;
   137967 }
   137968 
   137969 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
   137970   int rc = SQLITE_OK;
   137971   assert( !pReader->pBlob
   137972        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
   137973   );
   137974   while( pReader->pBlob && rc==SQLITE_OK
   137975      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
   137976   ){
   137977     rc = fts3SegReaderIncrRead(pReader);
   137978   }
   137979   return rc;
   137980 }
   137981 
   137982 /*
   137983 ** Set an Fts3SegReader cursor to point at EOF.
   137984 */
   137985 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
   137986   if( !fts3SegReaderIsRootOnly(pSeg) ){
   137987     sqlite3_free(pSeg->aNode);
   137988     sqlite3_blob_close(pSeg->pBlob);
   137989     pSeg->pBlob = 0;
   137990   }
   137991   pSeg->aNode = 0;
   137992 }
   137993 
   137994 /*
   137995 ** Move the iterator passed as the first argument to the next term in the
   137996 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
   137997 ** SQLITE_DONE. Otherwise, an SQLite error code.
   137998 */
   137999 static int fts3SegReaderNext(
   138000   Fts3Table *p,
   138001   Fts3SegReader *pReader,
   138002   int bIncr
   138003 ){
   138004   int rc;                         /* Return code of various sub-routines */
   138005   char *pNext;                    /* Cursor variable */
   138006   int nPrefix;                    /* Number of bytes in term prefix */
   138007   int nSuffix;                    /* Number of bytes in term suffix */
   138008 
   138009   if( !pReader->aDoclist ){
   138010     pNext = pReader->aNode;
   138011   }else{
   138012     pNext = &pReader->aDoclist[pReader->nDoclist];
   138013   }
   138014 
   138015   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
   138016 
   138017     if( fts3SegReaderIsPending(pReader) ){
   138018       Fts3HashElem *pElem = *(pReader->ppNextElem);
   138019       if( pElem==0 ){
   138020         pReader->aNode = 0;
   138021       }else{
   138022         PendingList *pList = (PendingList *)fts3HashData(pElem);
   138023         pReader->zTerm = (char *)fts3HashKey(pElem);
   138024         pReader->nTerm = fts3HashKeysize(pElem);
   138025         pReader->nNode = pReader->nDoclist = pList->nData + 1;
   138026         pReader->aNode = pReader->aDoclist = pList->aData;
   138027         pReader->ppNextElem++;
   138028         assert( pReader->aNode );
   138029       }
   138030       return SQLITE_OK;
   138031     }
   138032 
   138033     fts3SegReaderSetEof(pReader);
   138034 
   138035     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
   138036     ** blocks have already been traversed.  */
   138037     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
   138038     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
   138039       return SQLITE_OK;
   138040     }
   138041 
   138042     rc = sqlite3Fts3ReadBlock(
   138043         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
   138044         (bIncr ? &pReader->nPopulate : 0)
   138045     );
   138046     if( rc!=SQLITE_OK ) return rc;
   138047     assert( pReader->pBlob==0 );
   138048     if( bIncr && pReader->nPopulate<pReader->nNode ){
   138049       pReader->pBlob = p->pSegments;
   138050       p->pSegments = 0;
   138051     }
   138052     pNext = pReader->aNode;
   138053   }
   138054 
   138055   assert( !fts3SegReaderIsPending(pReader) );
   138056 
   138057   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
   138058   if( rc!=SQLITE_OK ) return rc;
   138059 
   138060   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
   138061   ** safe (no risk of overread) even if the node data is corrupted. */
   138062   pNext += fts3GetVarint32(pNext, &nPrefix);
   138063   pNext += fts3GetVarint32(pNext, &nSuffix);
   138064   if( nPrefix<0 || nSuffix<=0
   138065    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
   138066   ){
   138067     return FTS_CORRUPT_VTAB;
   138068   }
   138069 
   138070   if( nPrefix+nSuffix>pReader->nTermAlloc ){
   138071     int nNew = (nPrefix+nSuffix)*2;
   138072     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
   138073     if( !zNew ){
   138074       return SQLITE_NOMEM;
   138075     }
   138076     pReader->zTerm = zNew;
   138077     pReader->nTermAlloc = nNew;
   138078   }
   138079 
   138080   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
   138081   if( rc!=SQLITE_OK ) return rc;
   138082 
   138083   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
   138084   pReader->nTerm = nPrefix+nSuffix;
   138085   pNext += nSuffix;
   138086   pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
   138087   pReader->aDoclist = pNext;
   138088   pReader->pOffsetList = 0;
   138089 
   138090   /* Check that the doclist does not appear to extend past the end of the
   138091   ** b-tree node. And that the final byte of the doclist is 0x00. If either
   138092   ** of these statements is untrue, then the data structure is corrupt.
   138093   */
   138094   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
   138095    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
   138096   ){
   138097     return FTS_CORRUPT_VTAB;
   138098   }
   138099   return SQLITE_OK;
   138100 }
   138101 
   138102 /*
   138103 ** Set the SegReader to point to the first docid in the doclist associated
   138104 ** with the current term.
   138105 */
   138106 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
   138107   int rc = SQLITE_OK;
   138108   assert( pReader->aDoclist );
   138109   assert( !pReader->pOffsetList );
   138110   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   138111     u8 bEof = 0;
   138112     pReader->iDocid = 0;
   138113     pReader->nOffsetList = 0;
   138114     sqlite3Fts3DoclistPrev(0,
   138115         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
   138116         &pReader->iDocid, &pReader->nOffsetList, &bEof
   138117     );
   138118   }else{
   138119     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
   138120     if( rc==SQLITE_OK ){
   138121       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
   138122       pReader->pOffsetList = &pReader->aDoclist[n];
   138123     }
   138124   }
   138125   return rc;
   138126 }
   138127 
   138128 /*
   138129 ** Advance the SegReader to point to the next docid in the doclist
   138130 ** associated with the current term.
   138131 **
   138132 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
   138133 ** *ppOffsetList is set to point to the first column-offset list
   138134 ** in the doclist entry (i.e. immediately past the docid varint).
   138135 ** *pnOffsetList is set to the length of the set of column-offset
   138136 ** lists, not including the nul-terminator byte. For example:
   138137 */
   138138 static int fts3SegReaderNextDocid(
   138139   Fts3Table *pTab,
   138140   Fts3SegReader *pReader,         /* Reader to advance to next docid */
   138141   char **ppOffsetList,            /* OUT: Pointer to current position-list */
   138142   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
   138143 ){
   138144   int rc = SQLITE_OK;
   138145   char *p = pReader->pOffsetList;
   138146   char c = 0;
   138147 
   138148   assert( p );
   138149 
   138150   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   138151     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
   138152     ** Pending-terms doclists are always built up in ascending order, so
   138153     ** we have to iterate through them backwards here. */
   138154     u8 bEof = 0;
   138155     if( ppOffsetList ){
   138156       *ppOffsetList = pReader->pOffsetList;
   138157       *pnOffsetList = pReader->nOffsetList - 1;
   138158     }
   138159     sqlite3Fts3DoclistPrev(0,
   138160         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
   138161         &pReader->nOffsetList, &bEof
   138162     );
   138163     if( bEof ){
   138164       pReader->pOffsetList = 0;
   138165     }else{
   138166       pReader->pOffsetList = p;
   138167     }
   138168   }else{
   138169     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
   138170 
   138171     /* Pointer p currently points at the first byte of an offset list. The
   138172     ** following block advances it to point one byte past the end of
   138173     ** the same offset list. */
   138174     while( 1 ){
   138175 
   138176       /* The following line of code (and the "p++" below the while() loop) is
   138177       ** normally all that is required to move pointer p to the desired
   138178       ** position. The exception is if this node is being loaded from disk
   138179       ** incrementally and pointer "p" now points to the first byte past
   138180       ** the populated part of pReader->aNode[].
   138181       */
   138182       while( *p | c ) c = *p++ & 0x80;
   138183       assert( *p==0 );
   138184 
   138185       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
   138186       rc = fts3SegReaderIncrRead(pReader);
   138187       if( rc!=SQLITE_OK ) return rc;
   138188     }
   138189     p++;
   138190 
   138191     /* If required, populate the output variables with a pointer to and the
   138192     ** size of the previous offset-list.
   138193     */
   138194     if( ppOffsetList ){
   138195       *ppOffsetList = pReader->pOffsetList;
   138196       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
   138197     }
   138198 
   138199     /* List may have been edited in place by fts3EvalNearTrim() */
   138200     while( p<pEnd && *p==0 ) p++;
   138201 
   138202     /* If there are no more entries in the doclist, set pOffsetList to
   138203     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
   138204     ** Fts3SegReader.pOffsetList to point to the next offset list before
   138205     ** returning.
   138206     */
   138207     if( p>=pEnd ){
   138208       pReader->pOffsetList = 0;
   138209     }else{
   138210       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
   138211       if( rc==SQLITE_OK ){
   138212         sqlite3_int64 iDelta;
   138213         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
   138214         if( pTab->bDescIdx ){
   138215           pReader->iDocid -= iDelta;
   138216         }else{
   138217           pReader->iDocid += iDelta;
   138218         }
   138219       }
   138220     }
   138221   }
   138222 
   138223   return SQLITE_OK;
   138224 }
   138225 
   138226 
   138227 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
   138228   Fts3Cursor *pCsr,
   138229   Fts3MultiSegReader *pMsr,
   138230   int *pnOvfl
   138231 ){
   138232   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   138233   int nOvfl = 0;
   138234   int ii;
   138235   int rc = SQLITE_OK;
   138236   int pgsz = p->nPgsz;
   138237 
   138238   assert( p->bFts4 );
   138239   assert( pgsz>0 );
   138240 
   138241   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
   138242     Fts3SegReader *pReader = pMsr->apSegment[ii];
   138243     if( !fts3SegReaderIsPending(pReader)
   138244      && !fts3SegReaderIsRootOnly(pReader)
   138245     ){
   138246       sqlite3_int64 jj;
   138247       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
   138248         int nBlob;
   138249         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
   138250         if( rc!=SQLITE_OK ) break;
   138251         if( (nBlob+35)>pgsz ){
   138252           nOvfl += (nBlob + 34)/pgsz;
   138253         }
   138254       }
   138255     }
   138256   }
   138257   *pnOvfl = nOvfl;
   138258   return rc;
   138259 }
   138260 
   138261 /*
   138262 ** Free all allocations associated with the iterator passed as the
   138263 ** second argument.
   138264 */
   138265 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
   138266   if( pReader && !fts3SegReaderIsPending(pReader) ){
   138267     sqlite3_free(pReader->zTerm);
   138268     if( !fts3SegReaderIsRootOnly(pReader) ){
   138269       sqlite3_free(pReader->aNode);
   138270       sqlite3_blob_close(pReader->pBlob);
   138271     }
   138272   }
   138273   sqlite3_free(pReader);
   138274 }
   138275 
   138276 /*
   138277 ** Allocate a new SegReader object.
   138278 */
   138279 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
   138280   int iAge,                       /* Segment "age". */
   138281   int bLookup,                    /* True for a lookup only */
   138282   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
   138283   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
   138284   sqlite3_int64 iEndBlock,        /* Final block of segment */
   138285   const char *zRoot,              /* Buffer containing root node */
   138286   int nRoot,                      /* Size of buffer containing root node */
   138287   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   138288 ){
   138289   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
   138290   int nExtra = 0;                 /* Bytes to allocate segment root node */
   138291 
   138292   assert( iStartLeaf<=iEndLeaf );
   138293   if( iStartLeaf==0 ){
   138294     nExtra = nRoot + FTS3_NODE_PADDING;
   138295   }
   138296 
   138297   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
   138298   if( !pReader ){
   138299     return SQLITE_NOMEM;
   138300   }
   138301   memset(pReader, 0, sizeof(Fts3SegReader));
   138302   pReader->iIdx = iAge;
   138303   pReader->bLookup = bLookup!=0;
   138304   pReader->iStartBlock = iStartLeaf;
   138305   pReader->iLeafEndBlock = iEndLeaf;
   138306   pReader->iEndBlock = iEndBlock;
   138307 
   138308   if( nExtra ){
   138309     /* The entire segment is stored in the root node. */
   138310     pReader->aNode = (char *)&pReader[1];
   138311     pReader->rootOnly = 1;
   138312     pReader->nNode = nRoot;
   138313     memcpy(pReader->aNode, zRoot, nRoot);
   138314     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
   138315   }else{
   138316     pReader->iCurrentBlock = iStartLeaf-1;
   138317   }
   138318   *ppReader = pReader;
   138319   return SQLITE_OK;
   138320 }
   138321 
   138322 /*
   138323 ** This is a comparison function used as a qsort() callback when sorting
   138324 ** an array of pending terms by term. This occurs as part of flushing
   138325 ** the contents of the pending-terms hash table to the database.
   138326 */
   138327 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
   138328   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
   138329   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
   138330   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
   138331   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
   138332 
   138333   int n = (n1<n2 ? n1 : n2);
   138334   int c = memcmp(z1, z2, n);
   138335   if( c==0 ){
   138336     c = n1 - n2;
   138337   }
   138338   return c;
   138339 }
   138340 
   138341 /*
   138342 ** This function is used to allocate an Fts3SegReader that iterates through
   138343 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
   138344 **
   138345 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
   138346 ** through each term in the pending-terms table. Or, if isPrefixIter is
   138347 ** non-zero, it iterates through each term and its prefixes. For example, if
   138348 ** the pending terms hash table contains the terms "sqlite", "mysql" and
   138349 ** "firebird", then the iterator visits the following 'terms' (in the order
   138350 ** shown):
   138351 **
   138352 **   f fi fir fire fireb firebi firebir firebird
   138353 **   m my mys mysq mysql
   138354 **   s sq sql sqli sqlit sqlite
   138355 **
   138356 ** Whereas if isPrefixIter is zero, the terms visited are:
   138357 **
   138358 **   firebird mysql sqlite
   138359 */
   138360 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   138361   Fts3Table *p,                   /* Virtual table handle */
   138362   int iIndex,                     /* Index for p->aIndex */
   138363   const char *zTerm,              /* Term to search for */
   138364   int nTerm,                      /* Size of buffer zTerm */
   138365   int bPrefix,                    /* True for a prefix iterator */
   138366   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
   138367 ){
   138368   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
   138369   Fts3HashElem *pE;               /* Iterator variable */
   138370   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
   138371   int nElem = 0;                  /* Size of array at aElem */
   138372   int rc = SQLITE_OK;             /* Return Code */
   138373   Fts3Hash *pHash;
   138374 
   138375   pHash = &p->aIndex[iIndex].hPending;
   138376   if( bPrefix ){
   138377     int nAlloc = 0;               /* Size of allocated array at aElem */
   138378 
   138379     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
   138380       char *zKey = (char *)fts3HashKey(pE);
   138381       int nKey = fts3HashKeysize(pE);
   138382       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
   138383         if( nElem==nAlloc ){
   138384           Fts3HashElem **aElem2;
   138385           nAlloc += 16;
   138386           aElem2 = (Fts3HashElem **)sqlite3_realloc(
   138387               aElem, nAlloc*sizeof(Fts3HashElem *)
   138388           );
   138389           if( !aElem2 ){
   138390             rc = SQLITE_NOMEM;
   138391             nElem = 0;
   138392             break;
   138393           }
   138394           aElem = aElem2;
   138395         }
   138396 
   138397         aElem[nElem++] = pE;
   138398       }
   138399     }
   138400 
   138401     /* If more than one term matches the prefix, sort the Fts3HashElem
   138402     ** objects in term order using qsort(). This uses the same comparison
   138403     ** callback as is used when flushing terms to disk.
   138404     */
   138405     if( nElem>1 ){
   138406       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
   138407     }
   138408 
   138409   }else{
   138410     /* The query is a simple term lookup that matches at most one term in
   138411     ** the index. All that is required is a straight hash-lookup.
   138412     **
   138413     ** Because the stack address of pE may be accessed via the aElem pointer
   138414     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
   138415     ** within this entire function, not just this "else{...}" block.
   138416     */
   138417     pE = fts3HashFindElem(pHash, zTerm, nTerm);
   138418     if( pE ){
   138419       aElem = &pE;
   138420       nElem = 1;
   138421     }
   138422   }
   138423 
   138424   if( nElem>0 ){
   138425     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
   138426     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
   138427     if( !pReader ){
   138428       rc = SQLITE_NOMEM;
   138429     }else{
   138430       memset(pReader, 0, nByte);
   138431       pReader->iIdx = 0x7FFFFFFF;
   138432       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
   138433       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
   138434     }
   138435   }
   138436 
   138437   if( bPrefix ){
   138438     sqlite3_free(aElem);
   138439   }
   138440   *ppReader = pReader;
   138441   return rc;
   138442 }
   138443 
   138444 /*
   138445 ** Compare the entries pointed to by two Fts3SegReader structures.
   138446 ** Comparison is as follows:
   138447 **
   138448 **   1) EOF is greater than not EOF.
   138449 **
   138450 **   2) The current terms (if any) are compared using memcmp(). If one
   138451 **      term is a prefix of another, the longer term is considered the
   138452 **      larger.
   138453 **
   138454 **   3) By segment age. An older segment is considered larger.
   138455 */
   138456 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   138457   int rc;
   138458   if( pLhs->aNode && pRhs->aNode ){
   138459     int rc2 = pLhs->nTerm - pRhs->nTerm;
   138460     if( rc2<0 ){
   138461       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
   138462     }else{
   138463       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
   138464     }
   138465     if( rc==0 ){
   138466       rc = rc2;
   138467     }
   138468   }else{
   138469     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
   138470   }
   138471   if( rc==0 ){
   138472     rc = pRhs->iIdx - pLhs->iIdx;
   138473   }
   138474   assert( rc!=0 );
   138475   return rc;
   138476 }
   138477 
   138478 /*
   138479 ** A different comparison function for SegReader structures. In this
   138480 ** version, it is assumed that each SegReader points to an entry in
   138481 ** a doclist for identical terms. Comparison is made as follows:
   138482 **
   138483 **   1) EOF (end of doclist in this case) is greater than not EOF.
   138484 **
   138485 **   2) By current docid.
   138486 **
   138487 **   3) By segment age. An older segment is considered larger.
   138488 */
   138489 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   138490   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   138491   if( rc==0 ){
   138492     if( pLhs->iDocid==pRhs->iDocid ){
   138493       rc = pRhs->iIdx - pLhs->iIdx;
   138494     }else{
   138495       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
   138496     }
   138497   }
   138498   assert( pLhs->aNode && pRhs->aNode );
   138499   return rc;
   138500 }
   138501 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   138502   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   138503   if( rc==0 ){
   138504     if( pLhs->iDocid==pRhs->iDocid ){
   138505       rc = pRhs->iIdx - pLhs->iIdx;
   138506     }else{
   138507       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
   138508     }
   138509   }
   138510   assert( pLhs->aNode && pRhs->aNode );
   138511   return rc;
   138512 }
   138513 
   138514 /*
   138515 ** Compare the term that the Fts3SegReader object passed as the first argument
   138516 ** points to with the term specified by arguments zTerm and nTerm.
   138517 **
   138518 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
   138519 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
   138520 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
   138521 */
   138522 static int fts3SegReaderTermCmp(
   138523   Fts3SegReader *pSeg,            /* Segment reader object */
   138524   const char *zTerm,              /* Term to compare to */
   138525   int nTerm                       /* Size of term zTerm in bytes */
   138526 ){
   138527   int res = 0;
   138528   if( pSeg->aNode ){
   138529     if( pSeg->nTerm>nTerm ){
   138530       res = memcmp(pSeg->zTerm, zTerm, nTerm);
   138531     }else{
   138532       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
   138533     }
   138534     if( res==0 ){
   138535       res = pSeg->nTerm-nTerm;
   138536     }
   138537   }
   138538   return res;
   138539 }
   138540 
   138541 /*
   138542 ** Argument apSegment is an array of nSegment elements. It is known that
   138543 ** the final (nSegment-nSuspect) members are already in sorted order
   138544 ** (according to the comparison function provided). This function shuffles
   138545 ** the array around until all entries are in sorted order.
   138546 */
   138547 static void fts3SegReaderSort(
   138548   Fts3SegReader **apSegment,                     /* Array to sort entries of */
   138549   int nSegment,                                  /* Size of apSegment array */
   138550   int nSuspect,                                  /* Unsorted entry count */
   138551   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
   138552 ){
   138553   int i;                          /* Iterator variable */
   138554 
   138555   assert( nSuspect<=nSegment );
   138556 
   138557   if( nSuspect==nSegment ) nSuspect--;
   138558   for(i=nSuspect-1; i>=0; i--){
   138559     int j;
   138560     for(j=i; j<(nSegment-1); j++){
   138561       Fts3SegReader *pTmp;
   138562       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
   138563       pTmp = apSegment[j+1];
   138564       apSegment[j+1] = apSegment[j];
   138565       apSegment[j] = pTmp;
   138566     }
   138567   }
   138568 
   138569 #ifndef NDEBUG
   138570   /* Check that the list really is sorted now. */
   138571   for(i=0; i<(nSuspect-1); i++){
   138572     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
   138573   }
   138574 #endif
   138575 }
   138576 
   138577 /*
   138578 ** Insert a record into the %_segments table.
   138579 */
   138580 static int fts3WriteSegment(
   138581   Fts3Table *p,                   /* Virtual table handle */
   138582   sqlite3_int64 iBlock,           /* Block id for new block */
   138583   char *z,                        /* Pointer to buffer containing block data */
   138584   int n                           /* Size of buffer z in bytes */
   138585 ){
   138586   sqlite3_stmt *pStmt;
   138587   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
   138588   if( rc==SQLITE_OK ){
   138589     sqlite3_bind_int64(pStmt, 1, iBlock);
   138590     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
   138591     sqlite3_step(pStmt);
   138592     rc = sqlite3_reset(pStmt);
   138593   }
   138594   return rc;
   138595 }
   138596 
   138597 /*
   138598 ** Find the largest relative level number in the table. If successful, set
   138599 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
   138600 ** set *pnMax to zero and return an SQLite error code.
   138601 */
   138602 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
   138603   int rc;
   138604   int mxLevel = 0;
   138605   sqlite3_stmt *pStmt = 0;
   138606 
   138607   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
   138608   if( rc==SQLITE_OK ){
   138609     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   138610       mxLevel = sqlite3_column_int(pStmt, 0);
   138611     }
   138612     rc = sqlite3_reset(pStmt);
   138613   }
   138614   *pnMax = mxLevel;
   138615   return rc;
   138616 }
   138617 
   138618 /*
   138619 ** Insert a record into the %_segdir table.
   138620 */
   138621 static int fts3WriteSegdir(
   138622   Fts3Table *p,                   /* Virtual table handle */
   138623   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
   138624   int iIdx,                       /* Value for "idx" field */
   138625   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
   138626   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
   138627   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
   138628   sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
   138629   char *zRoot,                    /* Blob value for "root" field */
   138630   int nRoot                       /* Number of bytes in buffer zRoot */
   138631 ){
   138632   sqlite3_stmt *pStmt;
   138633   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
   138634   if( rc==SQLITE_OK ){
   138635     sqlite3_bind_int64(pStmt, 1, iLevel);
   138636     sqlite3_bind_int(pStmt, 2, iIdx);
   138637     sqlite3_bind_int64(pStmt, 3, iStartBlock);
   138638     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
   138639     if( nLeafData==0 ){
   138640       sqlite3_bind_int64(pStmt, 5, iEndBlock);
   138641     }else{
   138642       char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
   138643       if( !zEnd ) return SQLITE_NOMEM;
   138644       sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
   138645     }
   138646     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
   138647     sqlite3_step(pStmt);
   138648     rc = sqlite3_reset(pStmt);
   138649   }
   138650   return rc;
   138651 }
   138652 
   138653 /*
   138654 ** Return the size of the common prefix (if any) shared by zPrev and
   138655 ** zNext, in bytes. For example,
   138656 **
   138657 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
   138658 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
   138659 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
   138660 */
   138661 static int fts3PrefixCompress(
   138662   const char *zPrev,              /* Buffer containing previous term */
   138663   int nPrev,                      /* Size of buffer zPrev in bytes */
   138664   const char *zNext,              /* Buffer containing next term */
   138665   int nNext                       /* Size of buffer zNext in bytes */
   138666 ){
   138667   int n;
   138668   UNUSED_PARAMETER(nNext);
   138669   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
   138670   return n;
   138671 }
   138672 
   138673 /*
   138674 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
   138675 ** (according to memcmp) than the previous term.
   138676 */
   138677 static int fts3NodeAddTerm(
   138678   Fts3Table *p,                   /* Virtual table handle */
   138679   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
   138680   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
   138681   const char *zTerm,              /* Pointer to buffer containing term */
   138682   int nTerm                       /* Size of term in bytes */
   138683 ){
   138684   SegmentNode *pTree = *ppTree;
   138685   int rc;
   138686   SegmentNode *pNew;
   138687 
   138688   /* First try to append the term to the current node. Return early if
   138689   ** this is possible.
   138690   */
   138691   if( pTree ){
   138692     int nData = pTree->nData;     /* Current size of node in bytes */
   138693     int nReq = nData;             /* Required space after adding zTerm */
   138694     int nPrefix;                  /* Number of bytes of prefix compression */
   138695     int nSuffix;                  /* Suffix length */
   138696 
   138697     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
   138698     nSuffix = nTerm-nPrefix;
   138699 
   138700     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
   138701     if( nReq<=p->nNodeSize || !pTree->zTerm ){
   138702 
   138703       if( nReq>p->nNodeSize ){
   138704         /* An unusual case: this is the first term to be added to the node
   138705         ** and the static node buffer (p->nNodeSize bytes) is not large
   138706         ** enough. Use a separately malloced buffer instead This wastes
   138707         ** p->nNodeSize bytes, but since this scenario only comes about when
   138708         ** the database contain two terms that share a prefix of almost 2KB,
   138709         ** this is not expected to be a serious problem.
   138710         */
   138711         assert( pTree->aData==(char *)&pTree[1] );
   138712         pTree->aData = (char *)sqlite3_malloc(nReq);
   138713         if( !pTree->aData ){
   138714           return SQLITE_NOMEM;
   138715         }
   138716       }
   138717 
   138718       if( pTree->zTerm ){
   138719         /* There is no prefix-length field for first term in a node */
   138720         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
   138721       }
   138722 
   138723       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
   138724       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
   138725       pTree->nData = nData + nSuffix;
   138726       pTree->nEntry++;
   138727 
   138728       if( isCopyTerm ){
   138729         if( pTree->nMalloc<nTerm ){
   138730           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
   138731           if( !zNew ){
   138732             return SQLITE_NOMEM;
   138733           }
   138734           pTree->nMalloc = nTerm*2;
   138735           pTree->zMalloc = zNew;
   138736         }
   138737         pTree->zTerm = pTree->zMalloc;
   138738         memcpy(pTree->zTerm, zTerm, nTerm);
   138739         pTree->nTerm = nTerm;
   138740       }else{
   138741         pTree->zTerm = (char *)zTerm;
   138742         pTree->nTerm = nTerm;
   138743       }
   138744       return SQLITE_OK;
   138745     }
   138746   }
   138747 
   138748   /* If control flows to here, it was not possible to append zTerm to the
   138749   ** current node. Create a new node (a right-sibling of the current node).
   138750   ** If this is the first node in the tree, the term is added to it.
   138751   **
   138752   ** Otherwise, the term is not added to the new node, it is left empty for
   138753   ** now. Instead, the term is inserted into the parent of pTree. If pTree
   138754   ** has no parent, one is created here.
   138755   */
   138756   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
   138757   if( !pNew ){
   138758     return SQLITE_NOMEM;
   138759   }
   138760   memset(pNew, 0, sizeof(SegmentNode));
   138761   pNew->nData = 1 + FTS3_VARINT_MAX;
   138762   pNew->aData = (char *)&pNew[1];
   138763 
   138764   if( pTree ){
   138765     SegmentNode *pParent = pTree->pParent;
   138766     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
   138767     if( pTree->pParent==0 ){
   138768       pTree->pParent = pParent;
   138769     }
   138770     pTree->pRight = pNew;
   138771     pNew->pLeftmost = pTree->pLeftmost;
   138772     pNew->pParent = pParent;
   138773     pNew->zMalloc = pTree->zMalloc;
   138774     pNew->nMalloc = pTree->nMalloc;
   138775     pTree->zMalloc = 0;
   138776   }else{
   138777     pNew->pLeftmost = pNew;
   138778     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
   138779   }
   138780 
   138781   *ppTree = pNew;
   138782   return rc;
   138783 }
   138784 
   138785 /*
   138786 ** Helper function for fts3NodeWrite().
   138787 */
   138788 static int fts3TreeFinishNode(
   138789   SegmentNode *pTree,
   138790   int iHeight,
   138791   sqlite3_int64 iLeftChild
   138792 ){
   138793   int nStart;
   138794   assert( iHeight>=1 && iHeight<128 );
   138795   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
   138796   pTree->aData[nStart] = (char)iHeight;
   138797   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
   138798   return nStart;
   138799 }
   138800 
   138801 /*
   138802 ** Write the buffer for the segment node pTree and all of its peers to the
   138803 ** database. Then call this function recursively to write the parent of
   138804 ** pTree and its peers to the database.
   138805 **
   138806 ** Except, if pTree is a root node, do not write it to the database. Instead,
   138807 ** set output variables *paRoot and *pnRoot to contain the root node.
   138808 **
   138809 ** If successful, SQLITE_OK is returned and output variable *piLast is
   138810 ** set to the largest blockid written to the database (or zero if no
   138811 ** blocks were written to the db). Otherwise, an SQLite error code is
   138812 ** returned.
   138813 */
   138814 static int fts3NodeWrite(
   138815   Fts3Table *p,                   /* Virtual table handle */
   138816   SegmentNode *pTree,             /* SegmentNode handle */
   138817   int iHeight,                    /* Height of this node in tree */
   138818   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
   138819   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
   138820   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
   138821   char **paRoot,                  /* OUT: Data for root node */
   138822   int *pnRoot                     /* OUT: Size of root node in bytes */
   138823 ){
   138824   int rc = SQLITE_OK;
   138825 
   138826   if( !pTree->pParent ){
   138827     /* Root node of the tree. */
   138828     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
   138829     *piLast = iFree-1;
   138830     *pnRoot = pTree->nData - nStart;
   138831     *paRoot = &pTree->aData[nStart];
   138832   }else{
   138833     SegmentNode *pIter;
   138834     sqlite3_int64 iNextFree = iFree;
   138835     sqlite3_int64 iNextLeaf = iLeaf;
   138836     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
   138837       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
   138838       int nWrite = pIter->nData - nStart;
   138839 
   138840       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
   138841       iNextFree++;
   138842       iNextLeaf += (pIter->nEntry+1);
   138843     }
   138844     if( rc==SQLITE_OK ){
   138845       assert( iNextLeaf==iFree );
   138846       rc = fts3NodeWrite(
   138847           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
   138848       );
   138849     }
   138850   }
   138851 
   138852   return rc;
   138853 }
   138854 
   138855 /*
   138856 ** Free all memory allocations associated with the tree pTree.
   138857 */
   138858 static void fts3NodeFree(SegmentNode *pTree){
   138859   if( pTree ){
   138860     SegmentNode *p = pTree->pLeftmost;
   138861     fts3NodeFree(p->pParent);
   138862     while( p ){
   138863       SegmentNode *pRight = p->pRight;
   138864       if( p->aData!=(char *)&p[1] ){
   138865         sqlite3_free(p->aData);
   138866       }
   138867       assert( pRight==0 || p->zMalloc==0 );
   138868       sqlite3_free(p->zMalloc);
   138869       sqlite3_free(p);
   138870       p = pRight;
   138871     }
   138872   }
   138873 }
   138874 
   138875 /*
   138876 ** Add a term to the segment being constructed by the SegmentWriter object
   138877 ** *ppWriter. When adding the first term to a segment, *ppWriter should
   138878 ** be passed NULL. This function will allocate a new SegmentWriter object
   138879 ** and return it via the input/output variable *ppWriter in this case.
   138880 **
   138881 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   138882 */
   138883 static int fts3SegWriterAdd(
   138884   Fts3Table *p,                   /* Virtual table handle */
   138885   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
   138886   int isCopyTerm,                 /* True if buffer zTerm must be copied */
   138887   const char *zTerm,              /* Pointer to buffer containing term */
   138888   int nTerm,                      /* Size of term in bytes */
   138889   const char *aDoclist,           /* Pointer to buffer containing doclist */
   138890   int nDoclist                    /* Size of doclist in bytes */
   138891 ){
   138892   int nPrefix;                    /* Size of term prefix in bytes */
   138893   int nSuffix;                    /* Size of term suffix in bytes */
   138894   int nReq;                       /* Number of bytes required on leaf page */
   138895   int nData;
   138896   SegmentWriter *pWriter = *ppWriter;
   138897 
   138898   if( !pWriter ){
   138899     int rc;
   138900     sqlite3_stmt *pStmt;
   138901 
   138902     /* Allocate the SegmentWriter structure */
   138903     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
   138904     if( !pWriter ) return SQLITE_NOMEM;
   138905     memset(pWriter, 0, sizeof(SegmentWriter));
   138906     *ppWriter = pWriter;
   138907 
   138908     /* Allocate a buffer in which to accumulate data */
   138909     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
   138910     if( !pWriter->aData ) return SQLITE_NOMEM;
   138911     pWriter->nSize = p->nNodeSize;
   138912 
   138913     /* Find the next free blockid in the %_segments table */
   138914     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
   138915     if( rc!=SQLITE_OK ) return rc;
   138916     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   138917       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
   138918       pWriter->iFirst = pWriter->iFree;
   138919     }
   138920     rc = sqlite3_reset(pStmt);
   138921     if( rc!=SQLITE_OK ) return rc;
   138922   }
   138923   nData = pWriter->nData;
   138924 
   138925   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
   138926   nSuffix = nTerm-nPrefix;
   138927 
   138928   /* Figure out how many bytes are required by this new entry */
   138929   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
   138930     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
   138931     nSuffix +                               /* Term suffix */
   138932     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
   138933     nDoclist;                               /* Doclist data */
   138934 
   138935   if( nData>0 && nData+nReq>p->nNodeSize ){
   138936     int rc;
   138937 
   138938     /* The current leaf node is full. Write it out to the database. */
   138939     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
   138940     if( rc!=SQLITE_OK ) return rc;
   138941     p->nLeafAdd++;
   138942 
   138943     /* Add the current term to the interior node tree. The term added to
   138944     ** the interior tree must:
   138945     **
   138946     **   a) be greater than the largest term on the leaf node just written
   138947     **      to the database (still available in pWriter->zTerm), and
   138948     **
   138949     **   b) be less than or equal to the term about to be added to the new
   138950     **      leaf node (zTerm/nTerm).
   138951     **
   138952     ** In other words, it must be the prefix of zTerm 1 byte longer than
   138953     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   138954     */
   138955     assert( nPrefix<nTerm );
   138956     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
   138957     if( rc!=SQLITE_OK ) return rc;
   138958 
   138959     nData = 0;
   138960     pWriter->nTerm = 0;
   138961 
   138962     nPrefix = 0;
   138963     nSuffix = nTerm;
   138964     nReq = 1 +                              /* varint containing prefix size */
   138965       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
   138966       nTerm +                               /* Term suffix */
   138967       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
   138968       nDoclist;                             /* Doclist data */
   138969   }
   138970 
   138971   /* Increase the total number of bytes written to account for the new entry. */
   138972   pWriter->nLeafData += nReq;
   138973 
   138974   /* If the buffer currently allocated is too small for this entry, realloc
   138975   ** the buffer to make it large enough.
   138976   */
   138977   if( nReq>pWriter->nSize ){
   138978     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
   138979     if( !aNew ) return SQLITE_NOMEM;
   138980     pWriter->aData = aNew;
   138981     pWriter->nSize = nReq;
   138982   }
   138983   assert( nData+nReq<=pWriter->nSize );
   138984 
   138985   /* Append the prefix-compressed term and doclist to the buffer. */
   138986   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
   138987   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
   138988   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
   138989   nData += nSuffix;
   138990   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
   138991   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
   138992   pWriter->nData = nData + nDoclist;
   138993 
   138994   /* Save the current term so that it can be used to prefix-compress the next.
   138995   ** If the isCopyTerm parameter is true, then the buffer pointed to by
   138996   ** zTerm is transient, so take a copy of the term data. Otherwise, just
   138997   ** store a copy of the pointer.
   138998   */
   138999   if( isCopyTerm ){
   139000     if( nTerm>pWriter->nMalloc ){
   139001       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
   139002       if( !zNew ){
   139003         return SQLITE_NOMEM;
   139004       }
   139005       pWriter->nMalloc = nTerm*2;
   139006       pWriter->zMalloc = zNew;
   139007       pWriter->zTerm = zNew;
   139008     }
   139009     assert( pWriter->zTerm==pWriter->zMalloc );
   139010     memcpy(pWriter->zTerm, zTerm, nTerm);
   139011   }else{
   139012     pWriter->zTerm = (char *)zTerm;
   139013   }
   139014   pWriter->nTerm = nTerm;
   139015 
   139016   return SQLITE_OK;
   139017 }
   139018 
   139019 /*
   139020 ** Flush all data associated with the SegmentWriter object pWriter to the
   139021 ** database. This function must be called after all terms have been added
   139022 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
   139023 ** returned. Otherwise, an SQLite error code.
   139024 */
   139025 static int fts3SegWriterFlush(
   139026   Fts3Table *p,                   /* Virtual table handle */
   139027   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
   139028   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
   139029   int iIdx                        /* Value for 'idx' column of %_segdir */
   139030 ){
   139031   int rc;                         /* Return code */
   139032   if( pWriter->pTree ){
   139033     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
   139034     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
   139035     char *zRoot = NULL;           /* Pointer to buffer containing root node */
   139036     int nRoot = 0;                /* Size of buffer zRoot */
   139037 
   139038     iLastLeaf = pWriter->iFree;
   139039     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
   139040     if( rc==SQLITE_OK ){
   139041       rc = fts3NodeWrite(p, pWriter->pTree, 1,
   139042           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
   139043     }
   139044     if( rc==SQLITE_OK ){
   139045       rc = fts3WriteSegdir(p, iLevel, iIdx,
   139046           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
   139047     }
   139048   }else{
   139049     /* The entire tree fits on the root node. Write it to the segdir table. */
   139050     rc = fts3WriteSegdir(p, iLevel, iIdx,
   139051         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
   139052   }
   139053   p->nLeafAdd++;
   139054   return rc;
   139055 }
   139056 
   139057 /*
   139058 ** Release all memory held by the SegmentWriter object passed as the
   139059 ** first argument.
   139060 */
   139061 static void fts3SegWriterFree(SegmentWriter *pWriter){
   139062   if( pWriter ){
   139063     sqlite3_free(pWriter->aData);
   139064     sqlite3_free(pWriter->zMalloc);
   139065     fts3NodeFree(pWriter->pTree);
   139066     sqlite3_free(pWriter);
   139067   }
   139068 }
   139069 
   139070 /*
   139071 ** The first value in the apVal[] array is assumed to contain an integer.
   139072 ** This function tests if there exist any documents with docid values that
   139073 ** are different from that integer. i.e. if deleting the document with docid
   139074 ** pRowid would mean the FTS3 table were empty.
   139075 **
   139076 ** If successful, *pisEmpty is set to true if the table is empty except for
   139077 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
   139078 ** error occurs, an SQLite error code is returned.
   139079 */
   139080 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
   139081   sqlite3_stmt *pStmt;
   139082   int rc;
   139083   if( p->zContentTbl ){
   139084     /* If using the content=xxx option, assume the table is never empty */
   139085     *pisEmpty = 0;
   139086     rc = SQLITE_OK;
   139087   }else{
   139088     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
   139089     if( rc==SQLITE_OK ){
   139090       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   139091         *pisEmpty = sqlite3_column_int(pStmt, 0);
   139092       }
   139093       rc = sqlite3_reset(pStmt);
   139094     }
   139095   }
   139096   return rc;
   139097 }
   139098 
   139099 /*
   139100 ** Set *pnMax to the largest segment level in the database for the index
   139101 ** iIndex.
   139102 **
   139103 ** Segment levels are stored in the 'level' column of the %_segdir table.
   139104 **
   139105 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   139106 */
   139107 static int fts3SegmentMaxLevel(
   139108   Fts3Table *p,
   139109   int iLangid,
   139110   int iIndex,
   139111   sqlite3_int64 *pnMax
   139112 ){
   139113   sqlite3_stmt *pStmt;
   139114   int rc;
   139115   assert( iIndex>=0 && iIndex<p->nIndex );
   139116 
   139117   /* Set pStmt to the compiled version of:
   139118   **
   139119   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
   139120   **
   139121   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
   139122   */
   139123   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   139124   if( rc!=SQLITE_OK ) return rc;
   139125   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   139126   sqlite3_bind_int64(pStmt, 2,
   139127       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   139128   );
   139129   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   139130     *pnMax = sqlite3_column_int64(pStmt, 0);
   139131   }
   139132   return sqlite3_reset(pStmt);
   139133 }
   139134 
   139135 /*
   139136 ** iAbsLevel is an absolute level that may be assumed to exist within
   139137 ** the database. This function checks if it is the largest level number
   139138 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
   139139 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
   139140 ** is returned. If an error occurs, an error code is returned and the
   139141 ** final value of *pbMax is undefined.
   139142 */
   139143 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
   139144 
   139145   /* Set pStmt to the compiled version of:
   139146   **
   139147   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
   139148   **
   139149   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
   139150   */
   139151   sqlite3_stmt *pStmt;
   139152   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   139153   if( rc!=SQLITE_OK ) return rc;
   139154   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
   139155   sqlite3_bind_int64(pStmt, 2,
   139156       ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
   139157   );
   139158 
   139159   *pbMax = 0;
   139160   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   139161     *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
   139162   }
   139163   return sqlite3_reset(pStmt);
   139164 }
   139165 
   139166 /*
   139167 ** Delete all entries in the %_segments table associated with the segment
   139168 ** opened with seg-reader pSeg. This function does not affect the contents
   139169 ** of the %_segdir table.
   139170 */
   139171 static int fts3DeleteSegment(
   139172   Fts3Table *p,                   /* FTS table handle */
   139173   Fts3SegReader *pSeg             /* Segment to delete */
   139174 ){
   139175   int rc = SQLITE_OK;             /* Return code */
   139176   if( pSeg->iStartBlock ){
   139177     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
   139178     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
   139179     if( rc==SQLITE_OK ){
   139180       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
   139181       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
   139182       sqlite3_step(pDelete);
   139183       rc = sqlite3_reset(pDelete);
   139184     }
   139185   }
   139186   return rc;
   139187 }
   139188 
   139189 /*
   139190 ** This function is used after merging multiple segments into a single large
   139191 ** segment to delete the old, now redundant, segment b-trees. Specifically,
   139192 ** it:
   139193 **
   139194 **   1) Deletes all %_segments entries for the segments associated with
   139195 **      each of the SegReader objects in the array passed as the third
   139196 **      argument, and
   139197 **
   139198 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
   139199 **      entries regardless of level if (iLevel<0).
   139200 **
   139201 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
   139202 */
   139203 static int fts3DeleteSegdir(
   139204   Fts3Table *p,                   /* Virtual table handle */
   139205   int iLangid,                    /* Language id */
   139206   int iIndex,                     /* Index for p->aIndex */
   139207   int iLevel,                     /* Level of %_segdir entries to delete */
   139208   Fts3SegReader **apSegment,      /* Array of SegReader objects */
   139209   int nReader                     /* Size of array apSegment */
   139210 ){
   139211   int rc = SQLITE_OK;             /* Return Code */
   139212   int i;                          /* Iterator variable */
   139213   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
   139214 
   139215   for(i=0; rc==SQLITE_OK && i<nReader; i++){
   139216     rc = fts3DeleteSegment(p, apSegment[i]);
   139217   }
   139218   if( rc!=SQLITE_OK ){
   139219     return rc;
   139220   }
   139221 
   139222   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
   139223   if( iLevel==FTS3_SEGCURSOR_ALL ){
   139224     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
   139225     if( rc==SQLITE_OK ){
   139226       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   139227       sqlite3_bind_int64(pDelete, 2,
   139228           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   139229       );
   139230     }
   139231   }else{
   139232     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
   139233     if( rc==SQLITE_OK ){
   139234       sqlite3_bind_int64(
   139235           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   139236       );
   139237     }
   139238   }
   139239 
   139240   if( rc==SQLITE_OK ){
   139241     sqlite3_step(pDelete);
   139242     rc = sqlite3_reset(pDelete);
   139243   }
   139244 
   139245   return rc;
   139246 }
   139247 
   139248 /*
   139249 ** When this function is called, buffer *ppList (size *pnList bytes) contains
   139250 ** a position list that may (or may not) feature multiple columns. This
   139251 ** function adjusts the pointer *ppList and the length *pnList so that they
   139252 ** identify the subset of the position list that corresponds to column iCol.
   139253 **
   139254 ** If there are no entries in the input position list for column iCol, then
   139255 ** *pnList is set to zero before returning.
   139256 **
   139257 ** If parameter bZero is non-zero, then any part of the input list following
   139258 ** the end of the output list is zeroed before returning.
   139259 */
   139260 static void fts3ColumnFilter(
   139261   int iCol,                       /* Column to filter on */
   139262   int bZero,                      /* Zero out anything following *ppList */
   139263   char **ppList,                  /* IN/OUT: Pointer to position list */
   139264   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
   139265 ){
   139266   char *pList = *ppList;
   139267   int nList = *pnList;
   139268   char *pEnd = &pList[nList];
   139269   int iCurrent = 0;
   139270   char *p = pList;
   139271 
   139272   assert( iCol>=0 );
   139273   while( 1 ){
   139274     char c = 0;
   139275     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
   139276 
   139277     if( iCol==iCurrent ){
   139278       nList = (int)(p - pList);
   139279       break;
   139280     }
   139281 
   139282     nList -= (int)(p - pList);
   139283     pList = p;
   139284     if( nList==0 ){
   139285       break;
   139286     }
   139287     p = &pList[1];
   139288     p += fts3GetVarint32(p, &iCurrent);
   139289   }
   139290 
   139291   if( bZero && &pList[nList]!=pEnd ){
   139292     memset(&pList[nList], 0, pEnd - &pList[nList]);
   139293   }
   139294   *ppList = pList;
   139295   *pnList = nList;
   139296 }
   139297 
   139298 /*
   139299 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
   139300 ** existing data). Grow the buffer if required.
   139301 **
   139302 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
   139303 ** trying to resize the buffer, return SQLITE_NOMEM.
   139304 */
   139305 static int fts3MsrBufferData(
   139306   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   139307   char *pList,
   139308   int nList
   139309 ){
   139310   if( nList>pMsr->nBuffer ){
   139311     char *pNew;
   139312     pMsr->nBuffer = nList*2;
   139313     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
   139314     if( !pNew ) return SQLITE_NOMEM;
   139315     pMsr->aBuffer = pNew;
   139316   }
   139317 
   139318   memcpy(pMsr->aBuffer, pList, nList);
   139319   return SQLITE_OK;
   139320 }
   139321 
   139322 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   139323   Fts3Table *p,                   /* Virtual table handle */
   139324   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   139325   sqlite3_int64 *piDocid,         /* OUT: Docid value */
   139326   char **paPoslist,               /* OUT: Pointer to position list */
   139327   int *pnPoslist                  /* OUT: Size of position list in bytes */
   139328 ){
   139329   int nMerge = pMsr->nAdvance;
   139330   Fts3SegReader **apSegment = pMsr->apSegment;
   139331   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   139332     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   139333   );
   139334 
   139335   if( nMerge==0 ){
   139336     *paPoslist = 0;
   139337     return SQLITE_OK;
   139338   }
   139339 
   139340   while( 1 ){
   139341     Fts3SegReader *pSeg;
   139342     pSeg = pMsr->apSegment[0];
   139343 
   139344     if( pSeg->pOffsetList==0 ){
   139345       *paPoslist = 0;
   139346       break;
   139347     }else{
   139348       int rc;
   139349       char *pList;
   139350       int nList;
   139351       int j;
   139352       sqlite3_int64 iDocid = apSegment[0]->iDocid;
   139353 
   139354       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   139355       j = 1;
   139356       while( rc==SQLITE_OK
   139357         && j<nMerge
   139358         && apSegment[j]->pOffsetList
   139359         && apSegment[j]->iDocid==iDocid
   139360       ){
   139361         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   139362         j++;
   139363       }
   139364       if( rc!=SQLITE_OK ) return rc;
   139365       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
   139366 
   139367       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
   139368         rc = fts3MsrBufferData(pMsr, pList, nList+1);
   139369         if( rc!=SQLITE_OK ) return rc;
   139370         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
   139371         pList = pMsr->aBuffer;
   139372       }
   139373 
   139374       if( pMsr->iColFilter>=0 ){
   139375         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
   139376       }
   139377 
   139378       if( nList>0 ){
   139379         *paPoslist = pList;
   139380         *piDocid = iDocid;
   139381         *pnPoslist = nList;
   139382         break;
   139383       }
   139384     }
   139385   }
   139386 
   139387   return SQLITE_OK;
   139388 }
   139389 
   139390 static int fts3SegReaderStart(
   139391   Fts3Table *p,                   /* Virtual table handle */
   139392   Fts3MultiSegReader *pCsr,       /* Cursor object */
   139393   const char *zTerm,              /* Term searched for (or NULL) */
   139394   int nTerm                       /* Length of zTerm in bytes */
   139395 ){
   139396   int i;
   139397   int nSeg = pCsr->nSegment;
   139398 
   139399   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
   139400   ** for, then advance each segment iterator until it points to a term of
   139401   ** equal or greater value than the specified term. This prevents many
   139402   ** unnecessary merge/sort operations for the case where single segment
   139403   ** b-tree leaf nodes contain more than one term.
   139404   */
   139405   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
   139406     int res = 0;
   139407     Fts3SegReader *pSeg = pCsr->apSegment[i];
   139408     do {
   139409       int rc = fts3SegReaderNext(p, pSeg, 0);
   139410       if( rc!=SQLITE_OK ) return rc;
   139411     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
   139412 
   139413     if( pSeg->bLookup && res!=0 ){
   139414       fts3SegReaderSetEof(pSeg);
   139415     }
   139416   }
   139417   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
   139418 
   139419   return SQLITE_OK;
   139420 }
   139421 
   139422 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
   139423   Fts3Table *p,                   /* Virtual table handle */
   139424   Fts3MultiSegReader *pCsr,       /* Cursor object */
   139425   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
   139426 ){
   139427   pCsr->pFilter = pFilter;
   139428   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
   139429 }
   139430 
   139431 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   139432   Fts3Table *p,                   /* Virtual table handle */
   139433   Fts3MultiSegReader *pCsr,       /* Cursor object */
   139434   int iCol,                       /* Column to match on. */
   139435   const char *zTerm,              /* Term to iterate through a doclist for */
   139436   int nTerm                       /* Number of bytes in zTerm */
   139437 ){
   139438   int i;
   139439   int rc;
   139440   int nSegment = pCsr->nSegment;
   139441   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   139442     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   139443   );
   139444 
   139445   assert( pCsr->pFilter==0 );
   139446   assert( zTerm && nTerm>0 );
   139447 
   139448   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
   139449   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
   139450   if( rc!=SQLITE_OK ) return rc;
   139451 
   139452   /* Determine how many of the segments actually point to zTerm/nTerm. */
   139453   for(i=0; i<nSegment; i++){
   139454     Fts3SegReader *pSeg = pCsr->apSegment[i];
   139455     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
   139456       break;
   139457     }
   139458   }
   139459   pCsr->nAdvance = i;
   139460 
   139461   /* Advance each of the segments to point to the first docid. */
   139462   for(i=0; i<pCsr->nAdvance; i++){
   139463     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
   139464     if( rc!=SQLITE_OK ) return rc;
   139465   }
   139466   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
   139467 
   139468   assert( iCol<0 || iCol<p->nColumn );
   139469   pCsr->iColFilter = iCol;
   139470 
   139471   return SQLITE_OK;
   139472 }
   139473 
   139474 /*
   139475 ** This function is called on a MultiSegReader that has been started using
   139476 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
   139477 ** have been made. Calling this function puts the MultiSegReader in such
   139478 ** a state that if the next two calls are:
   139479 **
   139480 **   sqlite3Fts3SegReaderStart()
   139481 **   sqlite3Fts3SegReaderStep()
   139482 **
   139483 ** then the entire doclist for the term is available in
   139484 ** MultiSegReader.aDoclist/nDoclist.
   139485 */
   139486 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
   139487   int i;                          /* Used to iterate through segment-readers */
   139488 
   139489   assert( pCsr->zTerm==0 );
   139490   assert( pCsr->nTerm==0 );
   139491   assert( pCsr->aDoclist==0 );
   139492   assert( pCsr->nDoclist==0 );
   139493 
   139494   pCsr->nAdvance = 0;
   139495   pCsr->bRestart = 1;
   139496   for(i=0; i<pCsr->nSegment; i++){
   139497     pCsr->apSegment[i]->pOffsetList = 0;
   139498     pCsr->apSegment[i]->nOffsetList = 0;
   139499     pCsr->apSegment[i]->iDocid = 0;
   139500   }
   139501 
   139502   return SQLITE_OK;
   139503 }
   139504 
   139505 
   139506 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
   139507   Fts3Table *p,                   /* Virtual table handle */
   139508   Fts3MultiSegReader *pCsr        /* Cursor object */
   139509 ){
   139510   int rc = SQLITE_OK;
   139511 
   139512   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
   139513   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
   139514   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
   139515   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
   139516   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
   139517   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
   139518 
   139519   Fts3SegReader **apSegment = pCsr->apSegment;
   139520   int nSegment = pCsr->nSegment;
   139521   Fts3SegFilter *pFilter = pCsr->pFilter;
   139522   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   139523     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   139524   );
   139525 
   139526   if( pCsr->nSegment==0 ) return SQLITE_OK;
   139527 
   139528   do {
   139529     int nMerge;
   139530     int i;
   139531 
   139532     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
   139533     ** forward. Then sort the list in order of current term again.
   139534     */
   139535     for(i=0; i<pCsr->nAdvance; i++){
   139536       Fts3SegReader *pSeg = apSegment[i];
   139537       if( pSeg->bLookup ){
   139538         fts3SegReaderSetEof(pSeg);
   139539       }else{
   139540         rc = fts3SegReaderNext(p, pSeg, 0);
   139541       }
   139542       if( rc!=SQLITE_OK ) return rc;
   139543     }
   139544     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
   139545     pCsr->nAdvance = 0;
   139546 
   139547     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
   139548     assert( rc==SQLITE_OK );
   139549     if( apSegment[0]->aNode==0 ) break;
   139550 
   139551     pCsr->nTerm = apSegment[0]->nTerm;
   139552     pCsr->zTerm = apSegment[0]->zTerm;
   139553 
   139554     /* If this is a prefix-search, and if the term that apSegment[0] points
   139555     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
   139556     ** required callbacks have been made. In this case exit early.
   139557     **
   139558     ** Similarly, if this is a search for an exact match, and the first term
   139559     ** of segment apSegment[0] is not a match, exit early.
   139560     */
   139561     if( pFilter->zTerm && !isScan ){
   139562       if( pCsr->nTerm<pFilter->nTerm
   139563        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
   139564        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
   139565       ){
   139566         break;
   139567       }
   139568     }
   139569 
   139570     nMerge = 1;
   139571     while( nMerge<nSegment
   139572         && apSegment[nMerge]->aNode
   139573         && apSegment[nMerge]->nTerm==pCsr->nTerm
   139574         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
   139575     ){
   139576       nMerge++;
   139577     }
   139578 
   139579     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
   139580     if( nMerge==1
   139581      && !isIgnoreEmpty
   139582      && !isFirst
   139583      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
   139584     ){
   139585       pCsr->nDoclist = apSegment[0]->nDoclist;
   139586       if( fts3SegReaderIsPending(apSegment[0]) ){
   139587         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
   139588         pCsr->aDoclist = pCsr->aBuffer;
   139589       }else{
   139590         pCsr->aDoclist = apSegment[0]->aDoclist;
   139591       }
   139592       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
   139593     }else{
   139594       int nDoclist = 0;           /* Size of doclist */
   139595       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
   139596 
   139597       /* The current term of the first nMerge entries in the array
   139598       ** of Fts3SegReader objects is the same. The doclists must be merged
   139599       ** and a single term returned with the merged doclist.
   139600       */
   139601       for(i=0; i<nMerge; i++){
   139602         fts3SegReaderFirstDocid(p, apSegment[i]);
   139603       }
   139604       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
   139605       while( apSegment[0]->pOffsetList ){
   139606         int j;                    /* Number of segments that share a docid */
   139607         char *pList = 0;
   139608         int nList = 0;
   139609         int nByte;
   139610         sqlite3_int64 iDocid = apSegment[0]->iDocid;
   139611         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   139612         j = 1;
   139613         while( j<nMerge
   139614             && apSegment[j]->pOffsetList
   139615             && apSegment[j]->iDocid==iDocid
   139616         ){
   139617           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   139618           j++;
   139619         }
   139620 
   139621         if( isColFilter ){
   139622           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
   139623         }
   139624 
   139625         if( !isIgnoreEmpty || nList>0 ){
   139626 
   139627           /* Calculate the 'docid' delta value to write into the merged
   139628           ** doclist. */
   139629           sqlite3_int64 iDelta;
   139630           if( p->bDescIdx && nDoclist>0 ){
   139631             iDelta = iPrev - iDocid;
   139632           }else{
   139633             iDelta = iDocid - iPrev;
   139634           }
   139635           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
   139636           assert( nDoclist>0 || iDelta==iDocid );
   139637 
   139638           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
   139639           if( nDoclist+nByte>pCsr->nBuffer ){
   139640             char *aNew;
   139641             pCsr->nBuffer = (nDoclist+nByte)*2;
   139642             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
   139643             if( !aNew ){
   139644               return SQLITE_NOMEM;
   139645             }
   139646             pCsr->aBuffer = aNew;
   139647           }
   139648 
   139649           if( isFirst ){
   139650             char *a = &pCsr->aBuffer[nDoclist];
   139651             int nWrite;
   139652 
   139653             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
   139654             if( nWrite ){
   139655               iPrev = iDocid;
   139656               nDoclist += nWrite;
   139657             }
   139658           }else{
   139659             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
   139660             iPrev = iDocid;
   139661             if( isRequirePos ){
   139662               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
   139663               nDoclist += nList;
   139664               pCsr->aBuffer[nDoclist++] = '\0';
   139665             }
   139666           }
   139667         }
   139668 
   139669         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
   139670       }
   139671       if( nDoclist>0 ){
   139672         pCsr->aDoclist = pCsr->aBuffer;
   139673         pCsr->nDoclist = nDoclist;
   139674         rc = SQLITE_ROW;
   139675       }
   139676     }
   139677     pCsr->nAdvance = nMerge;
   139678   }while( rc==SQLITE_OK );
   139679 
   139680   return rc;
   139681 }
   139682 
   139683 
   139684 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
   139685   Fts3MultiSegReader *pCsr       /* Cursor object */
   139686 ){
   139687   if( pCsr ){
   139688     int i;
   139689     for(i=0; i<pCsr->nSegment; i++){
   139690       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
   139691     }
   139692     sqlite3_free(pCsr->apSegment);
   139693     sqlite3_free(pCsr->aBuffer);
   139694 
   139695     pCsr->nSegment = 0;
   139696     pCsr->apSegment = 0;
   139697     pCsr->aBuffer = 0;
   139698   }
   139699 }
   139700 
   139701 /*
   139702 ** Decode the "end_block" field, selected by column iCol of the SELECT
   139703 ** statement passed as the first argument.
   139704 **
   139705 ** The "end_block" field may contain either an integer, or a text field
   139706 ** containing the text representation of two non-negative integers separated
   139707 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
   139708 ** to the integer value and *pnByte to zero before returning. In the second,
   139709 ** set *piEndBlock to the first value and *pnByte to the second.
   139710 */
   139711 static void fts3ReadEndBlockField(
   139712   sqlite3_stmt *pStmt,
   139713   int iCol,
   139714   i64 *piEndBlock,
   139715   i64 *pnByte
   139716 ){
   139717   const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
   139718   if( zText ){
   139719     int i;
   139720     int iMul = 1;
   139721     i64 iVal = 0;
   139722     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
   139723       iVal = iVal*10 + (zText[i] - '0');
   139724     }
   139725     *piEndBlock = iVal;
   139726     while( zText[i]==' ' ) i++;
   139727     iVal = 0;
   139728     if( zText[i]=='-' ){
   139729       i++;
   139730       iMul = -1;
   139731     }
   139732     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
   139733       iVal = iVal*10 + (zText[i] - '0');
   139734     }
   139735     *pnByte = (iVal * (i64)iMul);
   139736   }
   139737 }
   139738 
   139739 
   139740 /*
   139741 ** A segment of size nByte bytes has just been written to absolute level
   139742 ** iAbsLevel. Promote any segments that should be promoted as a result.
   139743 */
   139744 static int fts3PromoteSegments(
   139745   Fts3Table *p,                   /* FTS table handle */
   139746   sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
   139747   sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
   139748 ){
   139749   int rc = SQLITE_OK;
   139750   sqlite3_stmt *pRange;
   139751 
   139752   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
   139753 
   139754   if( rc==SQLITE_OK ){
   139755     int bOk = 0;
   139756     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
   139757     i64 nLimit = (nByte*3)/2;
   139758 
   139759     /* Loop through all entries in the %_segdir table corresponding to
   139760     ** segments in this index on levels greater than iAbsLevel. If there is
   139761     ** at least one such segment, and it is possible to determine that all
   139762     ** such segments are smaller than nLimit bytes in size, they will be
   139763     ** promoted to level iAbsLevel.  */
   139764     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
   139765     sqlite3_bind_int64(pRange, 2, iLast);
   139766     while( SQLITE_ROW==sqlite3_step(pRange) ){
   139767       i64 nSize = 0, dummy;
   139768       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
   139769       if( nSize<=0 || nSize>nLimit ){
   139770         /* If nSize==0, then the %_segdir.end_block field does not not
   139771         ** contain a size value. This happens if it was written by an
   139772         ** old version of FTS. In this case it is not possible to determine
   139773         ** the size of the segment, and so segment promotion does not
   139774         ** take place.  */
   139775         bOk = 0;
   139776         break;
   139777       }
   139778       bOk = 1;
   139779     }
   139780     rc = sqlite3_reset(pRange);
   139781 
   139782     if( bOk ){
   139783       int iIdx = 0;
   139784       sqlite3_stmt *pUpdate1;
   139785       sqlite3_stmt *pUpdate2;
   139786 
   139787       if( rc==SQLITE_OK ){
   139788         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
   139789       }
   139790       if( rc==SQLITE_OK ){
   139791         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
   139792       }
   139793 
   139794       if( rc==SQLITE_OK ){
   139795 
   139796         /* Loop through all %_segdir entries for segments in this index with
   139797         ** levels equal to or greater than iAbsLevel. As each entry is visited,
   139798         ** updated it to set (level = -1) and (idx = N), where N is 0 for the
   139799         ** oldest segment in the range, 1 for the next oldest, and so on.
   139800         **
   139801         ** In other words, move all segments being promoted to level -1,
   139802         ** setting the "idx" fields as appropriate to keep them in the same
   139803         ** order. The contents of level -1 (which is never used, except
   139804         ** transiently here), will be moved back to level iAbsLevel below.  */
   139805         sqlite3_bind_int64(pRange, 1, iAbsLevel);
   139806         while( SQLITE_ROW==sqlite3_step(pRange) ){
   139807           sqlite3_bind_int(pUpdate1, 1, iIdx++);
   139808           sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
   139809           sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
   139810           sqlite3_step(pUpdate1);
   139811           rc = sqlite3_reset(pUpdate1);
   139812           if( rc!=SQLITE_OK ){
   139813             sqlite3_reset(pRange);
   139814             break;
   139815           }
   139816         }
   139817       }
   139818       if( rc==SQLITE_OK ){
   139819         rc = sqlite3_reset(pRange);
   139820       }
   139821 
   139822       /* Move level -1 to level iAbsLevel */
   139823       if( rc==SQLITE_OK ){
   139824         sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
   139825         sqlite3_step(pUpdate2);
   139826         rc = sqlite3_reset(pUpdate2);
   139827       }
   139828     }
   139829   }
   139830 
   139831 
   139832   return rc;
   139833 }
   139834 
   139835 /*
   139836 ** Merge all level iLevel segments in the database into a single
   139837 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
   139838 ** single segment with a level equal to the numerically largest level
   139839 ** currently present in the database.
   139840 **
   139841 ** If this function is called with iLevel<0, but there is only one
   139842 ** segment in the database, SQLITE_DONE is returned immediately.
   139843 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
   139844 ** an SQLite error code is returned.
   139845 */
   139846 static int fts3SegmentMerge(
   139847   Fts3Table *p,
   139848   int iLangid,                    /* Language id to merge */
   139849   int iIndex,                     /* Index in p->aIndex[] to merge */
   139850   int iLevel                      /* Level to merge */
   139851 ){
   139852   int rc;                         /* Return code */
   139853   int iIdx = 0;                   /* Index of new segment */
   139854   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
   139855   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
   139856   Fts3SegFilter filter;           /* Segment term filter condition */
   139857   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
   139858   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
   139859   i64 iMaxLevel = 0;              /* Max level number for this index/langid */
   139860 
   139861   assert( iLevel==FTS3_SEGCURSOR_ALL
   139862        || iLevel==FTS3_SEGCURSOR_PENDING
   139863        || iLevel>=0
   139864   );
   139865   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   139866   assert( iIndex>=0 && iIndex<p->nIndex );
   139867 
   139868   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
   139869   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
   139870 
   139871   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   139872     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
   139873     if( rc!=SQLITE_OK ) goto finished;
   139874   }
   139875 
   139876   if( iLevel==FTS3_SEGCURSOR_ALL ){
   139877     /* This call is to merge all segments in the database to a single
   139878     ** segment. The level of the new segment is equal to the numerically
   139879     ** greatest segment level currently present in the database for this
   139880     ** index. The idx of the new segment is always 0.  */
   139881     if( csr.nSegment==1 ){
   139882       rc = SQLITE_DONE;
   139883       goto finished;
   139884     }
   139885     iNewLevel = iMaxLevel;
   139886     bIgnoreEmpty = 1;
   139887 
   139888   }else{
   139889     /* This call is to merge all segments at level iLevel. find the next
   139890     ** available segment index at level iLevel+1. The call to
   139891     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
   139892     ** a single iLevel+2 segment if necessary.  */
   139893     assert( FTS3_SEGCURSOR_PENDING==-1 );
   139894     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
   139895     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
   139896     bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
   139897   }
   139898   if( rc!=SQLITE_OK ) goto finished;
   139899 
   139900   assert( csr.nSegment>0 );
   139901   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
   139902   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
   139903 
   139904   memset(&filter, 0, sizeof(Fts3SegFilter));
   139905   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
   139906   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
   139907 
   139908   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
   139909   while( SQLITE_OK==rc ){
   139910     rc = sqlite3Fts3SegReaderStep(p, &csr);
   139911     if( rc!=SQLITE_ROW ) break;
   139912     rc = fts3SegWriterAdd(p, &pWriter, 1,
   139913         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
   139914   }
   139915   if( rc!=SQLITE_OK ) goto finished;
   139916   assert( pWriter || bIgnoreEmpty );
   139917 
   139918   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   139919     rc = fts3DeleteSegdir(
   139920         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
   139921     );
   139922     if( rc!=SQLITE_OK ) goto finished;
   139923   }
   139924   if( pWriter ){
   139925     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
   139926     if( rc==SQLITE_OK ){
   139927       if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
   139928         rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
   139929       }
   139930     }
   139931   }
   139932 
   139933  finished:
   139934   fts3SegWriterFree(pWriter);
   139935   sqlite3Fts3SegReaderFinish(&csr);
   139936   return rc;
   139937 }
   139938 
   139939 
   139940 /*
   139941 ** Flush the contents of pendingTerms to level 0 segments.
   139942 */
   139943 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
   139944   int rc = SQLITE_OK;
   139945   int i;
   139946 
   139947   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   139948     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
   139949     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   139950   }
   139951   sqlite3Fts3PendingTermsClear(p);
   139952 
   139953   /* Determine the auto-incr-merge setting if unknown.  If enabled,
   139954   ** estimate the number of leaf blocks of content to be written
   139955   */
   139956   if( rc==SQLITE_OK && p->bHasStat
   139957    && p->nAutoincrmerge==0xff && p->nLeafAdd>0
   139958   ){
   139959     sqlite3_stmt *pStmt = 0;
   139960     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
   139961     if( rc==SQLITE_OK ){
   139962       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
   139963       rc = sqlite3_step(pStmt);
   139964       if( rc==SQLITE_ROW ){
   139965         p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
   139966         if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
   139967       }else if( rc==SQLITE_DONE ){
   139968         p->nAutoincrmerge = 0;
   139969       }
   139970       rc = sqlite3_reset(pStmt);
   139971     }
   139972   }
   139973   return rc;
   139974 }
   139975 
   139976 /*
   139977 ** Encode N integers as varints into a blob.
   139978 */
   139979 static void fts3EncodeIntArray(
   139980   int N,             /* The number of integers to encode */
   139981   u32 *a,            /* The integer values */
   139982   char *zBuf,        /* Write the BLOB here */
   139983   int *pNBuf         /* Write number of bytes if zBuf[] used here */
   139984 ){
   139985   int i, j;
   139986   for(i=j=0; i<N; i++){
   139987     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
   139988   }
   139989   *pNBuf = j;
   139990 }
   139991 
   139992 /*
   139993 ** Decode a blob of varints into N integers
   139994 */
   139995 static void fts3DecodeIntArray(
   139996   int N,             /* The number of integers to decode */
   139997   u32 *a,            /* Write the integer values */
   139998   const char *zBuf,  /* The BLOB containing the varints */
   139999   int nBuf           /* size of the BLOB */
   140000 ){
   140001   int i, j;
   140002   UNUSED_PARAMETER(nBuf);
   140003   for(i=j=0; i<N; i++){
   140004     sqlite3_int64 x;
   140005     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
   140006     assert(j<=nBuf);
   140007     a[i] = (u32)(x & 0xffffffff);
   140008   }
   140009 }
   140010 
   140011 /*
   140012 ** Insert the sizes (in tokens) for each column of the document
   140013 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
   140014 ** a blob of varints.
   140015 */
   140016 static void fts3InsertDocsize(
   140017   int *pRC,                       /* Result code */
   140018   Fts3Table *p,                   /* Table into which to insert */
   140019   u32 *aSz                        /* Sizes of each column, in tokens */
   140020 ){
   140021   char *pBlob;             /* The BLOB encoding of the document size */
   140022   int nBlob;               /* Number of bytes in the BLOB */
   140023   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
   140024   int rc;                  /* Result code from subfunctions */
   140025 
   140026   if( *pRC ) return;
   140027   pBlob = sqlite3_malloc( 10*p->nColumn );
   140028   if( pBlob==0 ){
   140029     *pRC = SQLITE_NOMEM;
   140030     return;
   140031   }
   140032   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
   140033   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
   140034   if( rc ){
   140035     sqlite3_free(pBlob);
   140036     *pRC = rc;
   140037     return;
   140038   }
   140039   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
   140040   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
   140041   sqlite3_step(pStmt);
   140042   *pRC = sqlite3_reset(pStmt);
   140043 }
   140044 
   140045 /*
   140046 ** Record 0 of the %_stat table contains a blob consisting of N varints,
   140047 ** where N is the number of user defined columns in the fts3 table plus
   140048 ** two. If nCol is the number of user defined columns, then values of the
   140049 ** varints are set as follows:
   140050 **
   140051 **   Varint 0:       Total number of rows in the table.
   140052 **
   140053 **   Varint 1..nCol: For each column, the total number of tokens stored in
   140054 **                   the column for all rows of the table.
   140055 **
   140056 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
   140057 **                   columns of all rows of the table.
   140058 **
   140059 */
   140060 static void fts3UpdateDocTotals(
   140061   int *pRC,                       /* The result code */
   140062   Fts3Table *p,                   /* Table being updated */
   140063   u32 *aSzIns,                    /* Size increases */
   140064   u32 *aSzDel,                    /* Size decreases */
   140065   int nChng                       /* Change in the number of documents */
   140066 ){
   140067   char *pBlob;             /* Storage for BLOB written into %_stat */
   140068   int nBlob;               /* Size of BLOB written into %_stat */
   140069   u32 *a;                  /* Array of integers that becomes the BLOB */
   140070   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
   140071   int i;                   /* Loop counter */
   140072   int rc;                  /* Result code from subfunctions */
   140073 
   140074   const int nStat = p->nColumn+2;
   140075 
   140076   if( *pRC ) return;
   140077   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
   140078   if( a==0 ){
   140079     *pRC = SQLITE_NOMEM;
   140080     return;
   140081   }
   140082   pBlob = (char*)&a[nStat];
   140083   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
   140084   if( rc ){
   140085     sqlite3_free(a);
   140086     *pRC = rc;
   140087     return;
   140088   }
   140089   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   140090   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   140091     fts3DecodeIntArray(nStat, a,
   140092          sqlite3_column_blob(pStmt, 0),
   140093          sqlite3_column_bytes(pStmt, 0));
   140094   }else{
   140095     memset(a, 0, sizeof(u32)*(nStat) );
   140096   }
   140097   rc = sqlite3_reset(pStmt);
   140098   if( rc!=SQLITE_OK ){
   140099     sqlite3_free(a);
   140100     *pRC = rc;
   140101     return;
   140102   }
   140103   if( nChng<0 && a[0]<(u32)(-nChng) ){
   140104     a[0] = 0;
   140105   }else{
   140106     a[0] += nChng;
   140107   }
   140108   for(i=0; i<p->nColumn+1; i++){
   140109     u32 x = a[i+1];
   140110     if( x+aSzIns[i] < aSzDel[i] ){
   140111       x = 0;
   140112     }else{
   140113       x = x + aSzIns[i] - aSzDel[i];
   140114     }
   140115     a[i+1] = x;
   140116   }
   140117   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
   140118   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
   140119   if( rc ){
   140120     sqlite3_free(a);
   140121     *pRC = rc;
   140122     return;
   140123   }
   140124   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   140125   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
   140126   sqlite3_step(pStmt);
   140127   *pRC = sqlite3_reset(pStmt);
   140128   sqlite3_free(a);
   140129 }
   140130 
   140131 /*
   140132 ** Merge the entire database so that there is one segment for each
   140133 ** iIndex/iLangid combination.
   140134 */
   140135 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
   140136   int bSeenDone = 0;
   140137   int rc;
   140138   sqlite3_stmt *pAllLangid = 0;
   140139 
   140140   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   140141   if( rc==SQLITE_OK ){
   140142     int rc2;
   140143     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
   140144     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
   140145       int i;
   140146       int iLangid = sqlite3_column_int(pAllLangid, 0);
   140147       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   140148         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
   140149         if( rc==SQLITE_DONE ){
   140150           bSeenDone = 1;
   140151           rc = SQLITE_OK;
   140152         }
   140153       }
   140154     }
   140155     rc2 = sqlite3_reset(pAllLangid);
   140156     if( rc==SQLITE_OK ) rc = rc2;
   140157   }
   140158 
   140159   sqlite3Fts3SegmentsClose(p);
   140160   sqlite3Fts3PendingTermsClear(p);
   140161 
   140162   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
   140163 }
   140164 
   140165 /*
   140166 ** This function is called when the user executes the following statement:
   140167 **
   140168 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
   140169 **
   140170 ** The entire FTS index is discarded and rebuilt. If the table is one
   140171 ** created using the content=xxx option, then the new index is based on
   140172 ** the current contents of the xxx table. Otherwise, it is rebuilt based
   140173 ** on the contents of the %_content table.
   140174 */
   140175 static int fts3DoRebuild(Fts3Table *p){
   140176   int rc;                         /* Return Code */
   140177 
   140178   rc = fts3DeleteAll(p, 0);
   140179   if( rc==SQLITE_OK ){
   140180     u32 *aSz = 0;
   140181     u32 *aSzIns = 0;
   140182     u32 *aSzDel = 0;
   140183     sqlite3_stmt *pStmt = 0;
   140184     int nEntry = 0;
   140185 
   140186     /* Compose and prepare an SQL statement to loop through the content table */
   140187     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
   140188     if( !zSql ){
   140189       rc = SQLITE_NOMEM;
   140190     }else{
   140191       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   140192       sqlite3_free(zSql);
   140193     }
   140194 
   140195     if( rc==SQLITE_OK ){
   140196       int nByte = sizeof(u32) * (p->nColumn+1)*3;
   140197       aSz = (u32 *)sqlite3_malloc(nByte);
   140198       if( aSz==0 ){
   140199         rc = SQLITE_NOMEM;
   140200       }else{
   140201         memset(aSz, 0, nByte);
   140202         aSzIns = &aSz[p->nColumn+1];
   140203         aSzDel = &aSzIns[p->nColumn+1];
   140204       }
   140205     }
   140206 
   140207     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   140208       int iCol;
   140209       int iLangid = langidFromSelect(p, pStmt);
   140210       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
   140211       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
   140212       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
   140213         if( p->abNotindexed[iCol]==0 ){
   140214           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
   140215           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
   140216           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
   140217         }
   140218       }
   140219       if( p->bHasDocsize ){
   140220         fts3InsertDocsize(&rc, p, aSz);
   140221       }
   140222       if( rc!=SQLITE_OK ){
   140223         sqlite3_finalize(pStmt);
   140224         pStmt = 0;
   140225       }else{
   140226         nEntry++;
   140227         for(iCol=0; iCol<=p->nColumn; iCol++){
   140228           aSzIns[iCol] += aSz[iCol];
   140229         }
   140230       }
   140231     }
   140232     if( p->bFts4 ){
   140233       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
   140234     }
   140235     sqlite3_free(aSz);
   140236 
   140237     if( pStmt ){
   140238       int rc2 = sqlite3_finalize(pStmt);
   140239       if( rc==SQLITE_OK ){
   140240         rc = rc2;
   140241       }
   140242     }
   140243   }
   140244 
   140245   return rc;
   140246 }
   140247 
   140248 
   140249 /*
   140250 ** This function opens a cursor used to read the input data for an
   140251 ** incremental merge operation. Specifically, it opens a cursor to scan
   140252 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
   140253 ** level iAbsLevel.
   140254 */
   140255 static int fts3IncrmergeCsr(
   140256   Fts3Table *p,                   /* FTS3 table handle */
   140257   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
   140258   int nSeg,                       /* Number of segments to merge */
   140259   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
   140260 ){
   140261   int rc;                         /* Return Code */
   140262   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
   140263   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
   140264 
   140265   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
   140266   memset(pCsr, 0, sizeof(*pCsr));
   140267   nByte = sizeof(Fts3SegReader *) * nSeg;
   140268   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
   140269 
   140270   if( pCsr->apSegment==0 ){
   140271     rc = SQLITE_NOMEM;
   140272   }else{
   140273     memset(pCsr->apSegment, 0, nByte);
   140274     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
   140275   }
   140276   if( rc==SQLITE_OK ){
   140277     int i;
   140278     int rc2;
   140279     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
   140280     assert( pCsr->nSegment==0 );
   140281     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
   140282       rc = sqlite3Fts3SegReaderNew(i, 0,
   140283           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
   140284           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
   140285           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
   140286           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
   140287           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
   140288           &pCsr->apSegment[i]
   140289       );
   140290       pCsr->nSegment++;
   140291     }
   140292     rc2 = sqlite3_reset(pStmt);
   140293     if( rc==SQLITE_OK ) rc = rc2;
   140294   }
   140295 
   140296   return rc;
   140297 }
   140298 
   140299 typedef struct IncrmergeWriter IncrmergeWriter;
   140300 typedef struct NodeWriter NodeWriter;
   140301 typedef struct Blob Blob;
   140302 typedef struct NodeReader NodeReader;
   140303 
   140304 /*
   140305 ** An instance of the following structure is used as a dynamic buffer
   140306 ** to build up nodes or other blobs of data in.
   140307 **
   140308 ** The function blobGrowBuffer() is used to extend the allocation.
   140309 */
   140310 struct Blob {
   140311   char *a;                        /* Pointer to allocation */
   140312   int n;                          /* Number of valid bytes of data in a[] */
   140313   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
   140314 };
   140315 
   140316 /*
   140317 ** This structure is used to build up buffers containing segment b-tree
   140318 ** nodes (blocks).
   140319 */
   140320 struct NodeWriter {
   140321   sqlite3_int64 iBlock;           /* Current block id */
   140322   Blob key;                       /* Last key written to the current block */
   140323   Blob block;                     /* Current block image */
   140324 };
   140325 
   140326 /*
   140327 ** An object of this type contains the state required to create or append
   140328 ** to an appendable b-tree segment.
   140329 */
   140330 struct IncrmergeWriter {
   140331   int nLeafEst;                   /* Space allocated for leaf blocks */
   140332   int nWork;                      /* Number of leaf pages flushed */
   140333   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
   140334   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
   140335   sqlite3_int64 iStart;           /* Block number of first allocated block */
   140336   sqlite3_int64 iEnd;             /* Block number of last allocated block */
   140337   sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
   140338   u8 bNoLeafData;                 /* If true, store 0 for segment size */
   140339   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
   140340 };
   140341 
   140342 /*
   140343 ** An object of the following type is used to read data from a single
   140344 ** FTS segment node. See the following functions:
   140345 **
   140346 **     nodeReaderInit()
   140347 **     nodeReaderNext()
   140348 **     nodeReaderRelease()
   140349 */
   140350 struct NodeReader {
   140351   const char *aNode;
   140352   int nNode;
   140353   int iOff;                       /* Current offset within aNode[] */
   140354 
   140355   /* Output variables. Containing the current node entry. */
   140356   sqlite3_int64 iChild;           /* Pointer to child node */
   140357   Blob term;                      /* Current term */
   140358   const char *aDoclist;           /* Pointer to doclist */
   140359   int nDoclist;                   /* Size of doclist in bytes */
   140360 };
   140361 
   140362 /*
   140363 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   140364 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
   140365 ** bytes in size, extend (realloc) it to be so.
   140366 **
   140367 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
   140368 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
   140369 ** to reflect the new size of the pBlob->a[] buffer.
   140370 */
   140371 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
   140372   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
   140373     int nAlloc = nMin;
   140374     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
   140375     if( a ){
   140376       pBlob->nAlloc = nAlloc;
   140377       pBlob->a = a;
   140378     }else{
   140379       *pRc = SQLITE_NOMEM;
   140380     }
   140381   }
   140382 }
   140383 
   140384 /*
   140385 ** Attempt to advance the node-reader object passed as the first argument to
   140386 ** the next entry on the node.
   140387 **
   140388 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
   140389 ** Otherwise return SQLITE_OK. If there is no next entry on the node
   140390 ** (e.g. because the current entry is the last) set NodeReader->aNode to
   140391 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
   140392 ** variables for the new entry.
   140393 */
   140394 static int nodeReaderNext(NodeReader *p){
   140395   int bFirst = (p->term.n==0);    /* True for first term on the node */
   140396   int nPrefix = 0;                /* Bytes to copy from previous term */
   140397   int nSuffix = 0;                /* Bytes to append to the prefix */
   140398   int rc = SQLITE_OK;             /* Return code */
   140399 
   140400   assert( p->aNode );
   140401   if( p->iChild && bFirst==0 ) p->iChild++;
   140402   if( p->iOff>=p->nNode ){
   140403     /* EOF */
   140404     p->aNode = 0;
   140405   }else{
   140406     if( bFirst==0 ){
   140407       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
   140408     }
   140409     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
   140410 
   140411     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
   140412     if( rc==SQLITE_OK ){
   140413       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
   140414       p->term.n = nPrefix+nSuffix;
   140415       p->iOff += nSuffix;
   140416       if( p->iChild==0 ){
   140417         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
   140418         p->aDoclist = &p->aNode[p->iOff];
   140419         p->iOff += p->nDoclist;
   140420       }
   140421     }
   140422   }
   140423 
   140424   assert( p->iOff<=p->nNode );
   140425 
   140426   return rc;
   140427 }
   140428 
   140429 /*
   140430 ** Release all dynamic resources held by node-reader object *p.
   140431 */
   140432 static void nodeReaderRelease(NodeReader *p){
   140433   sqlite3_free(p->term.a);
   140434 }
   140435 
   140436 /*
   140437 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
   140438 **
   140439 ** If successful, SQLITE_OK is returned and the NodeReader object set to
   140440 ** point to the first entry on the node (if any). Otherwise, an SQLite
   140441 ** error code is returned.
   140442 */
   140443 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
   140444   memset(p, 0, sizeof(NodeReader));
   140445   p->aNode = aNode;
   140446   p->nNode = nNode;
   140447 
   140448   /* Figure out if this is a leaf or an internal node. */
   140449   if( p->aNode[0] ){
   140450     /* An internal node. */
   140451     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
   140452   }else{
   140453     p->iOff = 1;
   140454   }
   140455 
   140456   return nodeReaderNext(p);
   140457 }
   140458 
   140459 /*
   140460 ** This function is called while writing an FTS segment each time a leaf o
   140461 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
   140462 ** to be greater than the largest key on the node just written, but smaller
   140463 ** than or equal to the first key that will be written to the next leaf
   140464 ** node.
   140465 **
   140466 ** The block id of the leaf node just written to disk may be found in
   140467 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
   140468 */
   140469 static int fts3IncrmergePush(
   140470   Fts3Table *p,                   /* Fts3 table handle */
   140471   IncrmergeWriter *pWriter,       /* Writer object */
   140472   const char *zTerm,              /* Term to write to internal node */
   140473   int nTerm                       /* Bytes at zTerm */
   140474 ){
   140475   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
   140476   int iLayer;
   140477 
   140478   assert( nTerm>0 );
   140479   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
   140480     sqlite3_int64 iNextPtr = 0;
   140481     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
   140482     int rc = SQLITE_OK;
   140483     int nPrefix;
   140484     int nSuffix;
   140485     int nSpace;
   140486 
   140487     /* Figure out how much space the key will consume if it is written to
   140488     ** the current node of layer iLayer. Due to the prefix compression,
   140489     ** the space required changes depending on which node the key is to
   140490     ** be added to.  */
   140491     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
   140492     nSuffix = nTerm - nPrefix;
   140493     nSpace  = sqlite3Fts3VarintLen(nPrefix);
   140494     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   140495 
   140496     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
   140497       /* If the current node of layer iLayer contains zero keys, or if adding
   140498       ** the key to it will not cause it to grow to larger than nNodeSize
   140499       ** bytes in size, write the key here.  */
   140500 
   140501       Blob *pBlk = &pNode->block;
   140502       if( pBlk->n==0 ){
   140503         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
   140504         if( rc==SQLITE_OK ){
   140505           pBlk->a[0] = (char)iLayer;
   140506           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
   140507         }
   140508       }
   140509       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
   140510       blobGrowBuffer(&pNode->key, nTerm, &rc);
   140511 
   140512       if( rc==SQLITE_OK ){
   140513         if( pNode->key.n ){
   140514           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
   140515         }
   140516         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
   140517         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
   140518         pBlk->n += nSuffix;
   140519 
   140520         memcpy(pNode->key.a, zTerm, nTerm);
   140521         pNode->key.n = nTerm;
   140522       }
   140523     }else{
   140524       /* Otherwise, flush the current node of layer iLayer to disk.
   140525       ** Then allocate a new, empty sibling node. The key will be written
   140526       ** into the parent of this node. */
   140527       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
   140528 
   140529       assert( pNode->block.nAlloc>=p->nNodeSize );
   140530       pNode->block.a[0] = (char)iLayer;
   140531       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
   140532 
   140533       iNextPtr = pNode->iBlock;
   140534       pNode->iBlock++;
   140535       pNode->key.n = 0;
   140536     }
   140537 
   140538     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
   140539     iPtr = iNextPtr;
   140540   }
   140541 
   140542   assert( 0 );
   140543   return 0;
   140544 }
   140545 
   140546 /*
   140547 ** Append a term and (optionally) doclist to the FTS segment node currently
   140548 ** stored in blob *pNode. The node need not contain any terms, but the
   140549 ** header must be written before this function is called.
   140550 **
   140551 ** A node header is a single 0x00 byte for a leaf node, or a height varint
   140552 ** followed by the left-hand-child varint for an internal node.
   140553 **
   140554 ** The term to be appended is passed via arguments zTerm/nTerm. For a
   140555 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
   140556 ** node, both aDoclist and nDoclist must be passed 0.
   140557 **
   140558 ** If the size of the value in blob pPrev is zero, then this is the first
   140559 ** term written to the node. Otherwise, pPrev contains a copy of the
   140560 ** previous term. Before this function returns, it is updated to contain a
   140561 ** copy of zTerm/nTerm.
   140562 **
   140563 ** It is assumed that the buffer associated with pNode is already large
   140564 ** enough to accommodate the new entry. The buffer associated with pPrev
   140565 ** is extended by this function if requrired.
   140566 **
   140567 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
   140568 ** returned. Otherwise, SQLITE_OK.
   140569 */
   140570 static int fts3AppendToNode(
   140571   Blob *pNode,                    /* Current node image to append to */
   140572   Blob *pPrev,                    /* Buffer containing previous term written */
   140573   const char *zTerm,              /* New term to write */
   140574   int nTerm,                      /* Size of zTerm in bytes */
   140575   const char *aDoclist,           /* Doclist (or NULL) to write */
   140576   int nDoclist                    /* Size of aDoclist in bytes */
   140577 ){
   140578   int rc = SQLITE_OK;             /* Return code */
   140579   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
   140580   int nPrefix;                    /* Size of term prefix in bytes */
   140581   int nSuffix;                    /* Size of term suffix in bytes */
   140582 
   140583   /* Node must have already been started. There must be a doclist for a
   140584   ** leaf node, and there must not be a doclist for an internal node.  */
   140585   assert( pNode->n>0 );
   140586   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
   140587 
   140588   blobGrowBuffer(pPrev, nTerm, &rc);
   140589   if( rc!=SQLITE_OK ) return rc;
   140590 
   140591   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
   140592   nSuffix = nTerm - nPrefix;
   140593   memcpy(pPrev->a, zTerm, nTerm);
   140594   pPrev->n = nTerm;
   140595 
   140596   if( bFirst==0 ){
   140597     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
   140598   }
   140599   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
   140600   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
   140601   pNode->n += nSuffix;
   140602 
   140603   if( aDoclist ){
   140604     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
   140605     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
   140606     pNode->n += nDoclist;
   140607   }
   140608 
   140609   assert( pNode->n<=pNode->nAlloc );
   140610 
   140611   return SQLITE_OK;
   140612 }
   140613 
   140614 /*
   140615 ** Append the current term and doclist pointed to by cursor pCsr to the
   140616 ** appendable b-tree segment opened for writing by pWriter.
   140617 **
   140618 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
   140619 */
   140620 static int fts3IncrmergeAppend(
   140621   Fts3Table *p,                   /* Fts3 table handle */
   140622   IncrmergeWriter *pWriter,       /* Writer object */
   140623   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
   140624 ){
   140625   const char *zTerm = pCsr->zTerm;
   140626   int nTerm = pCsr->nTerm;
   140627   const char *aDoclist = pCsr->aDoclist;
   140628   int nDoclist = pCsr->nDoclist;
   140629   int rc = SQLITE_OK;           /* Return code */
   140630   int nSpace;                   /* Total space in bytes required on leaf */
   140631   int nPrefix;                  /* Size of prefix shared with previous term */
   140632   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
   140633   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
   140634 
   140635   pLeaf = &pWriter->aNodeWriter[0];
   140636   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
   140637   nSuffix = nTerm - nPrefix;
   140638 
   140639   nSpace  = sqlite3Fts3VarintLen(nPrefix);
   140640   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   140641   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
   140642 
   140643   /* If the current block is not empty, and if adding this term/doclist
   140644   ** to the current block would make it larger than Fts3Table.nNodeSize
   140645   ** bytes, write this block out to the database. */
   140646   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
   140647     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
   140648     pWriter->nWork++;
   140649 
   140650     /* Add the current term to the parent node. The term added to the
   140651     ** parent must:
   140652     **
   140653     **   a) be greater than the largest term on the leaf node just written
   140654     **      to the database (still available in pLeaf->key), and
   140655     **
   140656     **   b) be less than or equal to the term about to be added to the new
   140657     **      leaf node (zTerm/nTerm).
   140658     **
   140659     ** In other words, it must be the prefix of zTerm 1 byte longer than
   140660     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   140661     */
   140662     if( rc==SQLITE_OK ){
   140663       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
   140664     }
   140665 
   140666     /* Advance to the next output block */
   140667     pLeaf->iBlock++;
   140668     pLeaf->key.n = 0;
   140669     pLeaf->block.n = 0;
   140670 
   140671     nSuffix = nTerm;
   140672     nSpace  = 1;
   140673     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   140674     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
   140675   }
   140676 
   140677   pWriter->nLeafData += nSpace;
   140678   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
   140679   if( rc==SQLITE_OK ){
   140680     if( pLeaf->block.n==0 ){
   140681       pLeaf->block.n = 1;
   140682       pLeaf->block.a[0] = '\0';
   140683     }
   140684     rc = fts3AppendToNode(
   140685         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
   140686     );
   140687   }
   140688 
   140689   return rc;
   140690 }
   140691 
   140692 /*
   140693 ** This function is called to release all dynamic resources held by the
   140694 ** merge-writer object pWriter, and if no error has occurred, to flush
   140695 ** all outstanding node buffers held by pWriter to disk.
   140696 **
   140697 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
   140698 ** is made to write any data to disk. Instead, this function serves only
   140699 ** to release outstanding resources.
   140700 **
   140701 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
   140702 ** flushing buffers to disk, *pRc is set to an SQLite error code before
   140703 ** returning.
   140704 */
   140705 static void fts3IncrmergeRelease(
   140706   Fts3Table *p,                   /* FTS3 table handle */
   140707   IncrmergeWriter *pWriter,       /* Merge-writer object */
   140708   int *pRc                        /* IN/OUT: Error code */
   140709 ){
   140710   int i;                          /* Used to iterate through non-root layers */
   140711   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
   140712   NodeWriter *pRoot;              /* NodeWriter for root node */
   140713   int rc = *pRc;                  /* Error code */
   140714 
   140715   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
   140716   ** root node. If the segment fits entirely on a single leaf node, iRoot
   140717   ** will be set to 0. If the root node is the parent of the leaves, iRoot
   140718   ** will be 1. And so on.  */
   140719   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
   140720     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
   140721     if( pNode->block.n>0 ) break;
   140722     assert( *pRc || pNode->block.nAlloc==0 );
   140723     assert( *pRc || pNode->key.nAlloc==0 );
   140724     sqlite3_free(pNode->block.a);
   140725     sqlite3_free(pNode->key.a);
   140726   }
   140727 
   140728   /* Empty output segment. This is a no-op. */
   140729   if( iRoot<0 ) return;
   140730 
   140731   /* The entire output segment fits on a single node. Normally, this means
   140732   ** the node would be stored as a blob in the "root" column of the %_segdir
   140733   ** table. However, this is not permitted in this case. The problem is that
   140734   ** space has already been reserved in the %_segments table, and so the
   140735   ** start_block and end_block fields of the %_segdir table must be populated.
   140736   ** And, by design or by accident, released versions of FTS cannot handle
   140737   ** segments that fit entirely on the root node with start_block!=0.
   140738   **
   140739   ** Instead, create a synthetic root node that contains nothing but a
   140740   ** pointer to the single content node. So that the segment consists of a
   140741   ** single leaf and a single interior (root) node.
   140742   **
   140743   ** Todo: Better might be to defer allocating space in the %_segments
   140744   ** table until we are sure it is needed.
   140745   */
   140746   if( iRoot==0 ){
   140747     Blob *pBlock = &pWriter->aNodeWriter[1].block;
   140748     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
   140749     if( rc==SQLITE_OK ){
   140750       pBlock->a[0] = 0x01;
   140751       pBlock->n = 1 + sqlite3Fts3PutVarint(
   140752           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
   140753       );
   140754     }
   140755     iRoot = 1;
   140756   }
   140757   pRoot = &pWriter->aNodeWriter[iRoot];
   140758 
   140759   /* Flush all currently outstanding nodes to disk. */
   140760   for(i=0; i<iRoot; i++){
   140761     NodeWriter *pNode = &pWriter->aNodeWriter[i];
   140762     if( pNode->block.n>0 && rc==SQLITE_OK ){
   140763       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
   140764     }
   140765     sqlite3_free(pNode->block.a);
   140766     sqlite3_free(pNode->key.a);
   140767   }
   140768 
   140769   /* Write the %_segdir record. */
   140770   if( rc==SQLITE_OK ){
   140771     rc = fts3WriteSegdir(p,
   140772         pWriter->iAbsLevel+1,               /* level */
   140773         pWriter->iIdx,                      /* idx */
   140774         pWriter->iStart,                    /* start_block */
   140775         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
   140776         pWriter->iEnd,                      /* end_block */
   140777         (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
   140778         pRoot->block.a, pRoot->block.n      /* root */
   140779     );
   140780   }
   140781   sqlite3_free(pRoot->block.a);
   140782   sqlite3_free(pRoot->key.a);
   140783 
   140784   *pRc = rc;
   140785 }
   140786 
   140787 /*
   140788 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
   140789 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
   140790 ** the other, it is considered to be smaller than the other.
   140791 **
   140792 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
   140793 ** if it is greater.
   140794 */
   140795 static int fts3TermCmp(
   140796   const char *zLhs, int nLhs,     /* LHS of comparison */
   140797   const char *zRhs, int nRhs      /* RHS of comparison */
   140798 ){
   140799   int nCmp = MIN(nLhs, nRhs);
   140800   int res;
   140801 
   140802   res = memcmp(zLhs, zRhs, nCmp);
   140803   if( res==0 ) res = nLhs - nRhs;
   140804 
   140805   return res;
   140806 }
   140807 
   140808 
   140809 /*
   140810 ** Query to see if the entry in the %_segments table with blockid iEnd is
   140811 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
   140812 ** returning. Otherwise, set *pbRes to 0.
   140813 **
   140814 ** Or, if an error occurs while querying the database, return an SQLite
   140815 ** error code. The final value of *pbRes is undefined in this case.
   140816 **
   140817 ** This is used to test if a segment is an "appendable" segment. If it
   140818 ** is, then a NULL entry has been inserted into the %_segments table
   140819 ** with blockid %_segdir.end_block.
   140820 */
   140821 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
   140822   int bRes = 0;                   /* Result to set *pbRes to */
   140823   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
   140824   int rc;                         /* Return code */
   140825 
   140826   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
   140827   if( rc==SQLITE_OK ){
   140828     sqlite3_bind_int64(pCheck, 1, iEnd);
   140829     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
   140830     rc = sqlite3_reset(pCheck);
   140831   }
   140832 
   140833   *pbRes = bRes;
   140834   return rc;
   140835 }
   140836 
   140837 /*
   140838 ** This function is called when initializing an incremental-merge operation.
   140839 ** It checks if the existing segment with index value iIdx at absolute level
   140840 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
   140841 ** merge-writer object *pWriter is initialized to write to it.
   140842 **
   140843 ** An existing segment can be appended to by an incremental merge if:
   140844 **
   140845 **   * It was initially created as an appendable segment (with all required
   140846 **     space pre-allocated), and
   140847 **
   140848 **   * The first key read from the input (arguments zKey and nKey) is
   140849 **     greater than the largest key currently stored in the potential
   140850 **     output segment.
   140851 */
   140852 static int fts3IncrmergeLoad(
   140853   Fts3Table *p,                   /* Fts3 table handle */
   140854   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
   140855   int iIdx,                       /* Index of candidate output segment */
   140856   const char *zKey,               /* First key to write */
   140857   int nKey,                       /* Number of bytes in nKey */
   140858   IncrmergeWriter *pWriter        /* Populate this object */
   140859 ){
   140860   int rc;                         /* Return code */
   140861   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
   140862 
   140863   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
   140864   if( rc==SQLITE_OK ){
   140865     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
   140866     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
   140867     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
   140868     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
   140869     int nRoot = 0;                /* Size of aRoot[] in bytes */
   140870     int rc2;                      /* Return code from sqlite3_reset() */
   140871     int bAppendable = 0;          /* Set to true if segment is appendable */
   140872 
   140873     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
   140874     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
   140875     sqlite3_bind_int(pSelect, 2, iIdx);
   140876     if( sqlite3_step(pSelect)==SQLITE_ROW ){
   140877       iStart = sqlite3_column_int64(pSelect, 1);
   140878       iLeafEnd = sqlite3_column_int64(pSelect, 2);
   140879       fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
   140880       if( pWriter->nLeafData<0 ){
   140881         pWriter->nLeafData = pWriter->nLeafData * -1;
   140882       }
   140883       pWriter->bNoLeafData = (pWriter->nLeafData==0);
   140884       nRoot = sqlite3_column_bytes(pSelect, 4);
   140885       aRoot = sqlite3_column_blob(pSelect, 4);
   140886     }else{
   140887       return sqlite3_reset(pSelect);
   140888     }
   140889 
   140890     /* Check for the zero-length marker in the %_segments table */
   140891     rc = fts3IsAppendable(p, iEnd, &bAppendable);
   140892 
   140893     /* Check that zKey/nKey is larger than the largest key the candidate */
   140894     if( rc==SQLITE_OK && bAppendable ){
   140895       char *aLeaf = 0;
   140896       int nLeaf = 0;
   140897 
   140898       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
   140899       if( rc==SQLITE_OK ){
   140900         NodeReader reader;
   140901         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
   140902             rc==SQLITE_OK && reader.aNode;
   140903             rc = nodeReaderNext(&reader)
   140904         ){
   140905           assert( reader.aNode );
   140906         }
   140907         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
   140908           bAppendable = 0;
   140909         }
   140910         nodeReaderRelease(&reader);
   140911       }
   140912       sqlite3_free(aLeaf);
   140913     }
   140914 
   140915     if( rc==SQLITE_OK && bAppendable ){
   140916       /* It is possible to append to this segment. Set up the IncrmergeWriter
   140917       ** object to do so.  */
   140918       int i;
   140919       int nHeight = (int)aRoot[0];
   140920       NodeWriter *pNode;
   140921 
   140922       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
   140923       pWriter->iStart = iStart;
   140924       pWriter->iEnd = iEnd;
   140925       pWriter->iAbsLevel = iAbsLevel;
   140926       pWriter->iIdx = iIdx;
   140927 
   140928       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
   140929         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
   140930       }
   140931 
   140932       pNode = &pWriter->aNodeWriter[nHeight];
   140933       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
   140934       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
   140935       if( rc==SQLITE_OK ){
   140936         memcpy(pNode->block.a, aRoot, nRoot);
   140937         pNode->block.n = nRoot;
   140938       }
   140939 
   140940       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
   140941         NodeReader reader;
   140942         pNode = &pWriter->aNodeWriter[i];
   140943 
   140944         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
   140945         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
   140946         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
   140947         if( rc==SQLITE_OK ){
   140948           memcpy(pNode->key.a, reader.term.a, reader.term.n);
   140949           pNode->key.n = reader.term.n;
   140950           if( i>0 ){
   140951             char *aBlock = 0;
   140952             int nBlock = 0;
   140953             pNode = &pWriter->aNodeWriter[i-1];
   140954             pNode->iBlock = reader.iChild;
   140955             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
   140956             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
   140957             if( rc==SQLITE_OK ){
   140958               memcpy(pNode->block.a, aBlock, nBlock);
   140959               pNode->block.n = nBlock;
   140960             }
   140961             sqlite3_free(aBlock);
   140962           }
   140963         }
   140964         nodeReaderRelease(&reader);
   140965       }
   140966     }
   140967 
   140968     rc2 = sqlite3_reset(pSelect);
   140969     if( rc==SQLITE_OK ) rc = rc2;
   140970   }
   140971 
   140972   return rc;
   140973 }
   140974 
   140975 /*
   140976 ** Determine the largest segment index value that exists within absolute
   140977 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
   140978 ** one before returning SQLITE_OK. Or, if there are no segments at all
   140979 ** within level iAbsLevel, set *piIdx to zero.
   140980 **
   140981 ** If an error occurs, return an SQLite error code. The final value of
   140982 ** *piIdx is undefined in this case.
   140983 */
   140984 static int fts3IncrmergeOutputIdx(
   140985   Fts3Table *p,                   /* FTS Table handle */
   140986   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
   140987   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
   140988 ){
   140989   int rc;
   140990   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
   140991 
   140992   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
   140993   if( rc==SQLITE_OK ){
   140994     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
   140995     sqlite3_step(pOutputIdx);
   140996     *piIdx = sqlite3_column_int(pOutputIdx, 0);
   140997     rc = sqlite3_reset(pOutputIdx);
   140998   }
   140999 
   141000   return rc;
   141001 }
   141002 
   141003 /*
   141004 ** Allocate an appendable output segment on absolute level iAbsLevel+1
   141005 ** with idx value iIdx.
   141006 **
   141007 ** In the %_segdir table, a segment is defined by the values in three
   141008 ** columns:
   141009 **
   141010 **     start_block
   141011 **     leaves_end_block
   141012 **     end_block
   141013 **
   141014 ** When an appendable segment is allocated, it is estimated that the
   141015 ** maximum number of leaf blocks that may be required is the sum of the
   141016 ** number of leaf blocks consumed by the input segments, plus the number
   141017 ** of input segments, multiplied by two. This value is stored in stack
   141018 ** variable nLeafEst.
   141019 **
   141020 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
   141021 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
   141022 ** array of leaf nodes starts at the first block allocated. The array
   141023 ** of interior nodes that are parents of the leaf nodes start at block
   141024 ** (start_block + (1 + end_block - start_block) / 16). And so on.
   141025 **
   141026 ** In the actual code below, the value "16" is replaced with the
   141027 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
   141028 */
   141029 static int fts3IncrmergeWriter(
   141030   Fts3Table *p,                   /* Fts3 table handle */
   141031   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
   141032   int iIdx,                       /* Index of new output segment */
   141033   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
   141034   IncrmergeWriter *pWriter        /* Populate this object */
   141035 ){
   141036   int rc;                         /* Return Code */
   141037   int i;                          /* Iterator variable */
   141038   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
   141039   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
   141040   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
   141041 
   141042   /* Calculate nLeafEst. */
   141043   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
   141044   if( rc==SQLITE_OK ){
   141045     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
   141046     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
   141047     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
   141048       nLeafEst = sqlite3_column_int(pLeafEst, 0);
   141049     }
   141050     rc = sqlite3_reset(pLeafEst);
   141051   }
   141052   if( rc!=SQLITE_OK ) return rc;
   141053 
   141054   /* Calculate the first block to use in the output segment */
   141055   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
   141056   if( rc==SQLITE_OK ){
   141057     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
   141058       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
   141059       pWriter->iEnd = pWriter->iStart - 1;
   141060       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
   141061     }
   141062     rc = sqlite3_reset(pFirstBlock);
   141063   }
   141064   if( rc!=SQLITE_OK ) return rc;
   141065 
   141066   /* Insert the marker in the %_segments table to make sure nobody tries
   141067   ** to steal the space just allocated. This is also used to identify
   141068   ** appendable segments.  */
   141069   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
   141070   if( rc!=SQLITE_OK ) return rc;
   141071 
   141072   pWriter->iAbsLevel = iAbsLevel;
   141073   pWriter->nLeafEst = nLeafEst;
   141074   pWriter->iIdx = iIdx;
   141075 
   141076   /* Set up the array of NodeWriter objects */
   141077   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
   141078     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
   141079   }
   141080   return SQLITE_OK;
   141081 }
   141082 
   141083 /*
   141084 ** Remove an entry from the %_segdir table. This involves running the
   141085 ** following two statements:
   141086 **
   141087 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
   141088 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
   141089 **
   141090 ** The DELETE statement removes the specific %_segdir level. The UPDATE
   141091 ** statement ensures that the remaining segments have contiguously allocated
   141092 ** idx values.
   141093 */
   141094 static int fts3RemoveSegdirEntry(
   141095   Fts3Table *p,                   /* FTS3 table handle */
   141096   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
   141097   int iIdx                        /* Index of %_segdir entry to delete */
   141098 ){
   141099   int rc;                         /* Return code */
   141100   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
   141101 
   141102   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
   141103   if( rc==SQLITE_OK ){
   141104     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
   141105     sqlite3_bind_int(pDelete, 2, iIdx);
   141106     sqlite3_step(pDelete);
   141107     rc = sqlite3_reset(pDelete);
   141108   }
   141109 
   141110   return rc;
   141111 }
   141112 
   141113 /*
   141114 ** One or more segments have just been removed from absolute level iAbsLevel.
   141115 ** Update the 'idx' values of the remaining segments in the level so that
   141116 ** the idx values are a contiguous sequence starting from 0.
   141117 */
   141118 static int fts3RepackSegdirLevel(
   141119   Fts3Table *p,                   /* FTS3 table handle */
   141120   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
   141121 ){
   141122   int rc;                         /* Return code */
   141123   int *aIdx = 0;                  /* Array of remaining idx values */
   141124   int nIdx = 0;                   /* Valid entries in aIdx[] */
   141125   int nAlloc = 0;                 /* Allocated size of aIdx[] */
   141126   int i;                          /* Iterator variable */
   141127   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
   141128   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
   141129 
   141130   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
   141131   if( rc==SQLITE_OK ){
   141132     int rc2;
   141133     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
   141134     while( SQLITE_ROW==sqlite3_step(pSelect) ){
   141135       if( nIdx>=nAlloc ){
   141136         int *aNew;
   141137         nAlloc += 16;
   141138         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
   141139         if( !aNew ){
   141140           rc = SQLITE_NOMEM;
   141141           break;
   141142         }
   141143         aIdx = aNew;
   141144       }
   141145       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
   141146     }
   141147     rc2 = sqlite3_reset(pSelect);
   141148     if( rc==SQLITE_OK ) rc = rc2;
   141149   }
   141150 
   141151   if( rc==SQLITE_OK ){
   141152     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
   141153   }
   141154   if( rc==SQLITE_OK ){
   141155     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
   141156   }
   141157 
   141158   assert( p->bIgnoreSavepoint==0 );
   141159   p->bIgnoreSavepoint = 1;
   141160   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
   141161     if( aIdx[i]!=i ){
   141162       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
   141163       sqlite3_bind_int(pUpdate, 1, i);
   141164       sqlite3_step(pUpdate);
   141165       rc = sqlite3_reset(pUpdate);
   141166     }
   141167   }
   141168   p->bIgnoreSavepoint = 0;
   141169 
   141170   sqlite3_free(aIdx);
   141171   return rc;
   141172 }
   141173 
   141174 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
   141175   pNode->a[0] = (char)iHeight;
   141176   if( iChild ){
   141177     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
   141178     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
   141179   }else{
   141180     assert( pNode->nAlloc>=1 );
   141181     pNode->n = 1;
   141182   }
   141183 }
   141184 
   141185 /*
   141186 ** The first two arguments are a pointer to and the size of a segment b-tree
   141187 ** node. The node may be a leaf or an internal node.
   141188 **
   141189 ** This function creates a new node image in blob object *pNew by copying
   141190 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
   141191 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
   141192 */
   141193 static int fts3TruncateNode(
   141194   const char *aNode,              /* Current node image */
   141195   int nNode,                      /* Size of aNode in bytes */
   141196   Blob *pNew,                     /* OUT: Write new node image here */
   141197   const char *zTerm,              /* Omit all terms smaller than this */
   141198   int nTerm,                      /* Size of zTerm in bytes */
   141199   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
   141200 ){
   141201   NodeReader reader;              /* Reader object */
   141202   Blob prev = {0, 0, 0};          /* Previous term written to new node */
   141203   int rc = SQLITE_OK;             /* Return code */
   141204   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
   141205 
   141206   /* Allocate required output space */
   141207   blobGrowBuffer(pNew, nNode, &rc);
   141208   if( rc!=SQLITE_OK ) return rc;
   141209   pNew->n = 0;
   141210 
   141211   /* Populate new node buffer */
   141212   for(rc = nodeReaderInit(&reader, aNode, nNode);
   141213       rc==SQLITE_OK && reader.aNode;
   141214       rc = nodeReaderNext(&reader)
   141215   ){
   141216     if( pNew->n==0 ){
   141217       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
   141218       if( res<0 || (bLeaf==0 && res==0) ) continue;
   141219       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
   141220       *piBlock = reader.iChild;
   141221     }
   141222     rc = fts3AppendToNode(
   141223         pNew, &prev, reader.term.a, reader.term.n,
   141224         reader.aDoclist, reader.nDoclist
   141225     );
   141226     if( rc!=SQLITE_OK ) break;
   141227   }
   141228   if( pNew->n==0 ){
   141229     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
   141230     *piBlock = reader.iChild;
   141231   }
   141232   assert( pNew->n<=pNew->nAlloc );
   141233 
   141234   nodeReaderRelease(&reader);
   141235   sqlite3_free(prev.a);
   141236   return rc;
   141237 }
   141238 
   141239 /*
   141240 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
   141241 ** level iAbsLevel. This may involve deleting entries from the %_segments
   141242 ** table, and modifying existing entries in both the %_segments and %_segdir
   141243 ** tables.
   141244 **
   141245 ** SQLITE_OK is returned if the segment is updated successfully. Or an
   141246 ** SQLite error code otherwise.
   141247 */
   141248 static int fts3TruncateSegment(
   141249   Fts3Table *p,                   /* FTS3 table handle */
   141250   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
   141251   int iIdx,                       /* Index within level of segment to modify */
   141252   const char *zTerm,              /* Remove terms smaller than this */
   141253   int nTerm                      /* Number of bytes in buffer zTerm */
   141254 ){
   141255   int rc = SQLITE_OK;             /* Return code */
   141256   Blob root = {0,0,0};            /* New root page image */
   141257   Blob block = {0,0,0};           /* Buffer used for any other block */
   141258   sqlite3_int64 iBlock = 0;       /* Block id */
   141259   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
   141260   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
   141261   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
   141262 
   141263   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
   141264   if( rc==SQLITE_OK ){
   141265     int rc2;                      /* sqlite3_reset() return code */
   141266     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
   141267     sqlite3_bind_int(pFetch, 2, iIdx);
   141268     if( SQLITE_ROW==sqlite3_step(pFetch) ){
   141269       const char *aRoot = sqlite3_column_blob(pFetch, 4);
   141270       int nRoot = sqlite3_column_bytes(pFetch, 4);
   141271       iOldStart = sqlite3_column_int64(pFetch, 1);
   141272       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
   141273     }
   141274     rc2 = sqlite3_reset(pFetch);
   141275     if( rc==SQLITE_OK ) rc = rc2;
   141276   }
   141277 
   141278   while( rc==SQLITE_OK && iBlock ){
   141279     char *aBlock = 0;
   141280     int nBlock = 0;
   141281     iNewStart = iBlock;
   141282 
   141283     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
   141284     if( rc==SQLITE_OK ){
   141285       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
   141286     }
   141287     if( rc==SQLITE_OK ){
   141288       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
   141289     }
   141290     sqlite3_free(aBlock);
   141291   }
   141292 
   141293   /* Variable iNewStart now contains the first valid leaf node. */
   141294   if( rc==SQLITE_OK && iNewStart ){
   141295     sqlite3_stmt *pDel = 0;
   141296     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
   141297     if( rc==SQLITE_OK ){
   141298       sqlite3_bind_int64(pDel, 1, iOldStart);
   141299       sqlite3_bind_int64(pDel, 2, iNewStart-1);
   141300       sqlite3_step(pDel);
   141301       rc = sqlite3_reset(pDel);
   141302     }
   141303   }
   141304 
   141305   if( rc==SQLITE_OK ){
   141306     sqlite3_stmt *pChomp = 0;
   141307     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
   141308     if( rc==SQLITE_OK ){
   141309       sqlite3_bind_int64(pChomp, 1, iNewStart);
   141310       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
   141311       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
   141312       sqlite3_bind_int(pChomp, 4, iIdx);
   141313       sqlite3_step(pChomp);
   141314       rc = sqlite3_reset(pChomp);
   141315     }
   141316   }
   141317 
   141318   sqlite3_free(root.a);
   141319   sqlite3_free(block.a);
   141320   return rc;
   141321 }
   141322 
   141323 /*
   141324 ** This function is called after an incrmental-merge operation has run to
   141325 ** merge (or partially merge) two or more segments from absolute level
   141326 ** iAbsLevel.
   141327 **
   141328 ** Each input segment is either removed from the db completely (if all of
   141329 ** its data was copied to the output segment by the incrmerge operation)
   141330 ** or modified in place so that it no longer contains those entries that
   141331 ** have been duplicated in the output segment.
   141332 */
   141333 static int fts3IncrmergeChomp(
   141334   Fts3Table *p,                   /* FTS table handle */
   141335   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
   141336   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
   141337   int *pnRem                      /* Number of segments not deleted */
   141338 ){
   141339   int i;
   141340   int nRem = 0;
   141341   int rc = SQLITE_OK;
   141342 
   141343   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
   141344     Fts3SegReader *pSeg = 0;
   141345     int j;
   141346 
   141347     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
   141348     ** somewhere in the pCsr->apSegment[] array.  */
   141349     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
   141350       pSeg = pCsr->apSegment[j];
   141351       if( pSeg->iIdx==i ) break;
   141352     }
   141353     assert( j<pCsr->nSegment && pSeg->iIdx==i );
   141354 
   141355     if( pSeg->aNode==0 ){
   141356       /* Seg-reader is at EOF. Remove the entire input segment. */
   141357       rc = fts3DeleteSegment(p, pSeg);
   141358       if( rc==SQLITE_OK ){
   141359         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
   141360       }
   141361       *pnRem = 0;
   141362     }else{
   141363       /* The incremental merge did not copy all the data from this
   141364       ** segment to the upper level. The segment is modified in place
   141365       ** so that it contains no keys smaller than zTerm/nTerm. */
   141366       const char *zTerm = pSeg->zTerm;
   141367       int nTerm = pSeg->nTerm;
   141368       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
   141369       nRem++;
   141370     }
   141371   }
   141372 
   141373   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
   141374     rc = fts3RepackSegdirLevel(p, iAbsLevel);
   141375   }
   141376 
   141377   *pnRem = nRem;
   141378   return rc;
   141379 }
   141380 
   141381 /*
   141382 ** Store an incr-merge hint in the database.
   141383 */
   141384 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
   141385   sqlite3_stmt *pReplace = 0;
   141386   int rc;                         /* Return code */
   141387 
   141388   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
   141389   if( rc==SQLITE_OK ){
   141390     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
   141391     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
   141392     sqlite3_step(pReplace);
   141393     rc = sqlite3_reset(pReplace);
   141394   }
   141395 
   141396   return rc;
   141397 }
   141398 
   141399 /*
   141400 ** Load an incr-merge hint from the database. The incr-merge hint, if one
   141401 ** exists, is stored in the rowid==1 row of the %_stat table.
   141402 **
   141403 ** If successful, populate blob *pHint with the value read from the %_stat
   141404 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
   141405 ** SQLite error code.
   141406 */
   141407 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
   141408   sqlite3_stmt *pSelect = 0;
   141409   int rc;
   141410 
   141411   pHint->n = 0;
   141412   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
   141413   if( rc==SQLITE_OK ){
   141414     int rc2;
   141415     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
   141416     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   141417       const char *aHint = sqlite3_column_blob(pSelect, 0);
   141418       int nHint = sqlite3_column_bytes(pSelect, 0);
   141419       if( aHint ){
   141420         blobGrowBuffer(pHint, nHint, &rc);
   141421         if( rc==SQLITE_OK ){
   141422           memcpy(pHint->a, aHint, nHint);
   141423           pHint->n = nHint;
   141424         }
   141425       }
   141426     }
   141427     rc2 = sqlite3_reset(pSelect);
   141428     if( rc==SQLITE_OK ) rc = rc2;
   141429   }
   141430 
   141431   return rc;
   141432 }
   141433 
   141434 /*
   141435 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   141436 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
   141437 ** consists of two varints, the absolute level number of the input segments
   141438 ** and the number of input segments.
   141439 **
   141440 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
   141441 ** set *pRc to an SQLite error code before returning.
   141442 */
   141443 static void fts3IncrmergeHintPush(
   141444   Blob *pHint,                    /* Hint blob to append to */
   141445   i64 iAbsLevel,                  /* First varint to store in hint */
   141446   int nInput,                     /* Second varint to store in hint */
   141447   int *pRc                        /* IN/OUT: Error code */
   141448 ){
   141449   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
   141450   if( *pRc==SQLITE_OK ){
   141451     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
   141452     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
   141453   }
   141454 }
   141455 
   141456 /*
   141457 ** Read the last entry (most recently pushed) from the hint blob *pHint
   141458 ** and then remove the entry. Write the two values read to *piAbsLevel and
   141459 ** *pnInput before returning.
   141460 **
   141461 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
   141462 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
   141463 */
   141464 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
   141465   const int nHint = pHint->n;
   141466   int i;
   141467 
   141468   i = pHint->n-2;
   141469   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
   141470   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
   141471 
   141472   pHint->n = i;
   141473   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
   141474   i += fts3GetVarint32(&pHint->a[i], pnInput);
   141475   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
   141476 
   141477   return SQLITE_OK;
   141478 }
   141479 
   141480 
   141481 /*
   141482 ** Attempt an incremental merge that writes nMerge leaf blocks.
   141483 **
   141484 ** Incremental merges happen nMin segments at a time. The segments
   141485 ** to be merged are the nMin oldest segments (the ones with the smallest
   141486 ** values for the _segdir.idx field) in the highest level that contains
   141487 ** at least nMin segments. Multiple merges might occur in an attempt to
   141488 ** write the quota of nMerge leaf blocks.
   141489 */
   141490 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
   141491   int rc;                         /* Return code */
   141492   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
   141493   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
   141494   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
   141495   IncrmergeWriter *pWriter;       /* Writer object */
   141496   int nSeg = 0;                   /* Number of input segments */
   141497   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
   141498   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
   141499   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
   141500 
   141501   /* Allocate space for the cursor, filter and writer objects */
   141502   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
   141503   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
   141504   if( !pWriter ) return SQLITE_NOMEM;
   141505   pFilter = (Fts3SegFilter *)&pWriter[1];
   141506   pCsr = (Fts3MultiSegReader *)&pFilter[1];
   141507 
   141508   rc = fts3IncrmergeHintLoad(p, &hint);
   141509   while( rc==SQLITE_OK && nRem>0 ){
   141510     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
   141511     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
   141512     int bUseHint = 0;             /* True if attempting to append */
   141513     int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
   141514 
   141515     /* Search the %_segdir table for the absolute level with the smallest
   141516     ** relative level number that contains at least nMin segments, if any.
   141517     ** If one is found, set iAbsLevel to the absolute level number and
   141518     ** nSeg to nMin. If no level with at least nMin segments can be found,
   141519     ** set nSeg to -1.
   141520     */
   141521     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
   141522     sqlite3_bind_int(pFindLevel, 1, nMin);
   141523     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
   141524       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
   141525       nSeg = nMin;
   141526     }else{
   141527       nSeg = -1;
   141528     }
   141529     rc = sqlite3_reset(pFindLevel);
   141530 
   141531     /* If the hint read from the %_stat table is not empty, check if the
   141532     ** last entry in it specifies a relative level smaller than or equal
   141533     ** to the level identified by the block above (if any). If so, this
   141534     ** iteration of the loop will work on merging at the hinted level.
   141535     */
   141536     if( rc==SQLITE_OK && hint.n ){
   141537       int nHint = hint.n;
   141538       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
   141539       int nHintSeg = 0;                     /* Hint number of segments */
   141540 
   141541       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
   141542       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
   141543         iAbsLevel = iHintAbsLevel;
   141544         nSeg = nHintSeg;
   141545         bUseHint = 1;
   141546         bDirtyHint = 1;
   141547       }else{
   141548         /* This undoes the effect of the HintPop() above - so that no entry
   141549         ** is removed from the hint blob.  */
   141550         hint.n = nHint;
   141551       }
   141552     }
   141553 
   141554     /* If nSeg is less that zero, then there is no level with at least
   141555     ** nMin segments and no hint in the %_stat table. No work to do.
   141556     ** Exit early in this case.  */
   141557     if( nSeg<0 ) break;
   141558 
   141559     /* Open a cursor to iterate through the contents of the oldest nSeg
   141560     ** indexes of absolute level iAbsLevel. If this cursor is opened using
   141561     ** the 'hint' parameters, it is possible that there are less than nSeg
   141562     ** segments available in level iAbsLevel. In this case, no work is
   141563     ** done on iAbsLevel - fall through to the next iteration of the loop
   141564     ** to start work on some other level.  */
   141565     memset(pWriter, 0, nAlloc);
   141566     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
   141567 
   141568     if( rc==SQLITE_OK ){
   141569       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
   141570       assert( bUseHint==1 || bUseHint==0 );
   141571       if( iIdx==0 || (bUseHint && iIdx==1) ){
   141572         int bIgnore = 0;
   141573         rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
   141574         if( bIgnore ){
   141575           pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
   141576         }
   141577       }
   141578     }
   141579 
   141580     if( rc==SQLITE_OK ){
   141581       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
   141582     }
   141583     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
   141584      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
   141585      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
   141586     ){
   141587       if( bUseHint && iIdx>0 ){
   141588         const char *zKey = pCsr->zTerm;
   141589         int nKey = pCsr->nTerm;
   141590         rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
   141591       }else{
   141592         rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
   141593       }
   141594 
   141595       if( rc==SQLITE_OK && pWriter->nLeafEst ){
   141596         fts3LogMerge(nSeg, iAbsLevel);
   141597         do {
   141598           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
   141599           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
   141600           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
   141601         }while( rc==SQLITE_ROW );
   141602 
   141603         /* Update or delete the input segments */
   141604         if( rc==SQLITE_OK ){
   141605           nRem -= (1 + pWriter->nWork);
   141606           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
   141607           if( nSeg!=0 ){
   141608             bDirtyHint = 1;
   141609             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
   141610           }
   141611         }
   141612       }
   141613 
   141614       if( nSeg!=0 ){
   141615         pWriter->nLeafData = pWriter->nLeafData * -1;
   141616       }
   141617       fts3IncrmergeRelease(p, pWriter, &rc);
   141618       if( nSeg==0 && pWriter->bNoLeafData==0 ){
   141619         fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
   141620       }
   141621     }
   141622 
   141623     sqlite3Fts3SegReaderFinish(pCsr);
   141624   }
   141625 
   141626   /* Write the hint values into the %_stat table for the next incr-merger */
   141627   if( bDirtyHint && rc==SQLITE_OK ){
   141628     rc = fts3IncrmergeHintStore(p, &hint);
   141629   }
   141630 
   141631   sqlite3_free(pWriter);
   141632   sqlite3_free(hint.a);
   141633   return rc;
   141634 }
   141635 
   141636 /*
   141637 ** Convert the text beginning at *pz into an integer and return
   141638 ** its value.  Advance *pz to point to the first character past
   141639 ** the integer.
   141640 */
   141641 static int fts3Getint(const char **pz){
   141642   const char *z = *pz;
   141643   int i = 0;
   141644   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
   141645   *pz = z;
   141646   return i;
   141647 }
   141648 
   141649 /*
   141650 ** Process statements of the form:
   141651 **
   141652 **    INSERT INTO table(table) VALUES('merge=A,B');
   141653 **
   141654 ** A and B are integers that decode to be the number of leaf pages
   141655 ** written for the merge, and the minimum number of segments on a level
   141656 ** before it will be selected for a merge, respectively.
   141657 */
   141658 static int fts3DoIncrmerge(
   141659   Fts3Table *p,                   /* FTS3 table handle */
   141660   const char *zParam              /* Nul-terminated string containing "A,B" */
   141661 ){
   141662   int rc;
   141663   int nMin = (FTS3_MERGE_COUNT / 2);
   141664   int nMerge = 0;
   141665   const char *z = zParam;
   141666 
   141667   /* Read the first integer value */
   141668   nMerge = fts3Getint(&z);
   141669 
   141670   /* If the first integer value is followed by a ',',  read the second
   141671   ** integer value. */
   141672   if( z[0]==',' && z[1]!='\0' ){
   141673     z++;
   141674     nMin = fts3Getint(&z);
   141675   }
   141676 
   141677   if( z[0]!='\0' || nMin<2 ){
   141678     rc = SQLITE_ERROR;
   141679   }else{
   141680     rc = SQLITE_OK;
   141681     if( !p->bHasStat ){
   141682       assert( p->bFts4==0 );
   141683       sqlite3Fts3CreateStatTable(&rc, p);
   141684     }
   141685     if( rc==SQLITE_OK ){
   141686       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
   141687     }
   141688     sqlite3Fts3SegmentsClose(p);
   141689   }
   141690   return rc;
   141691 }
   141692 
   141693 /*
   141694 ** Process statements of the form:
   141695 **
   141696 **    INSERT INTO table(table) VALUES('automerge=X');
   141697 **
   141698 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
   141699 ** turn it on.  The setting is persistent.
   141700 */
   141701 static int fts3DoAutoincrmerge(
   141702   Fts3Table *p,                   /* FTS3 table handle */
   141703   const char *zParam              /* Nul-terminated string containing boolean */
   141704 ){
   141705   int rc = SQLITE_OK;
   141706   sqlite3_stmt *pStmt = 0;
   141707   p->nAutoincrmerge = fts3Getint(&zParam);
   141708   if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
   141709     p->nAutoincrmerge = 8;
   141710   }
   141711   if( !p->bHasStat ){
   141712     assert( p->bFts4==0 );
   141713     sqlite3Fts3CreateStatTable(&rc, p);
   141714     if( rc ) return rc;
   141715   }
   141716   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
   141717   if( rc ) return rc;
   141718   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
   141719   sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
   141720   sqlite3_step(pStmt);
   141721   rc = sqlite3_reset(pStmt);
   141722   return rc;
   141723 }
   141724 
   141725 /*
   141726 ** Return a 64-bit checksum for the FTS index entry specified by the
   141727 ** arguments to this function.
   141728 */
   141729 static u64 fts3ChecksumEntry(
   141730   const char *zTerm,              /* Pointer to buffer containing term */
   141731   int nTerm,                      /* Size of zTerm in bytes */
   141732   int iLangid,                    /* Language id for current row */
   141733   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
   141734   i64 iDocid,                     /* Docid for current row. */
   141735   int iCol,                       /* Column number */
   141736   int iPos                        /* Position */
   141737 ){
   141738   int i;
   141739   u64 ret = (u64)iDocid;
   141740 
   141741   ret += (ret<<3) + iLangid;
   141742   ret += (ret<<3) + iIndex;
   141743   ret += (ret<<3) + iCol;
   141744   ret += (ret<<3) + iPos;
   141745   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
   141746 
   141747   return ret;
   141748 }
   141749 
   141750 /*
   141751 ** Return a checksum of all entries in the FTS index that correspond to
   141752 ** language id iLangid. The checksum is calculated by XORing the checksums
   141753 ** of each individual entry (see fts3ChecksumEntry()) together.
   141754 **
   141755 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
   141756 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
   141757 ** return value is undefined in this case.
   141758 */
   141759 static u64 fts3ChecksumIndex(
   141760   Fts3Table *p,                   /* FTS3 table handle */
   141761   int iLangid,                    /* Language id to return cksum for */
   141762   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
   141763   int *pRc                        /* OUT: Return code */
   141764 ){
   141765   Fts3SegFilter filter;
   141766   Fts3MultiSegReader csr;
   141767   int rc;
   141768   u64 cksum = 0;
   141769 
   141770   assert( *pRc==SQLITE_OK );
   141771 
   141772   memset(&filter, 0, sizeof(filter));
   141773   memset(&csr, 0, sizeof(csr));
   141774   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
   141775   filter.flags |= FTS3_SEGMENT_SCAN;
   141776 
   141777   rc = sqlite3Fts3SegReaderCursor(
   141778       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
   141779   );
   141780   if( rc==SQLITE_OK ){
   141781     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
   141782   }
   141783 
   141784   if( rc==SQLITE_OK ){
   141785     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
   141786       char *pCsr = csr.aDoclist;
   141787       char *pEnd = &pCsr[csr.nDoclist];
   141788 
   141789       i64 iDocid = 0;
   141790       i64 iCol = 0;
   141791       i64 iPos = 0;
   141792 
   141793       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
   141794       while( pCsr<pEnd ){
   141795         i64 iVal = 0;
   141796         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
   141797         if( pCsr<pEnd ){
   141798           if( iVal==0 || iVal==1 ){
   141799             iCol = 0;
   141800             iPos = 0;
   141801             if( iVal ){
   141802               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
   141803             }else{
   141804               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
   141805               iDocid += iVal;
   141806             }
   141807           }else{
   141808             iPos += (iVal - 2);
   141809             cksum = cksum ^ fts3ChecksumEntry(
   141810                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
   141811                 (int)iCol, (int)iPos
   141812             );
   141813           }
   141814         }
   141815       }
   141816     }
   141817   }
   141818   sqlite3Fts3SegReaderFinish(&csr);
   141819 
   141820   *pRc = rc;
   141821   return cksum;
   141822 }
   141823 
   141824 /*
   141825 ** Check if the contents of the FTS index match the current contents of the
   141826 ** content table. If no error occurs and the contents do match, set *pbOk
   141827 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
   141828 ** to false before returning.
   141829 **
   141830 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
   141831 ** code. The final value of *pbOk is undefined in this case.
   141832 */
   141833 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
   141834   int rc = SQLITE_OK;             /* Return code */
   141835   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
   141836   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
   141837   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
   141838 
   141839   /* This block calculates the checksum according to the FTS index. */
   141840   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   141841   if( rc==SQLITE_OK ){
   141842     int rc2;
   141843     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
   141844     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
   141845       int iLangid = sqlite3_column_int(pAllLangid, 0);
   141846       int i;
   141847       for(i=0; i<p->nIndex; i++){
   141848         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
   141849       }
   141850     }
   141851     rc2 = sqlite3_reset(pAllLangid);
   141852     if( rc==SQLITE_OK ) rc = rc2;
   141853   }
   141854 
   141855   /* This block calculates the checksum according to the %_content table */
   141856   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   141857   if( rc==SQLITE_OK ){
   141858     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
   141859     sqlite3_stmt *pStmt = 0;
   141860     char *zSql;
   141861 
   141862     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
   141863     if( !zSql ){
   141864       rc = SQLITE_NOMEM;
   141865     }else{
   141866       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   141867       sqlite3_free(zSql);
   141868     }
   141869 
   141870     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   141871       i64 iDocid = sqlite3_column_int64(pStmt, 0);
   141872       int iLang = langidFromSelect(p, pStmt);
   141873       int iCol;
   141874 
   141875       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
   141876         if( p->abNotindexed[iCol]==0 ){
   141877           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
   141878           int nText = sqlite3_column_bytes(pStmt, iCol+1);
   141879           sqlite3_tokenizer_cursor *pT = 0;
   141880 
   141881           rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
   141882           while( rc==SQLITE_OK ){
   141883             char const *zToken;       /* Buffer containing token */
   141884             int nToken = 0;           /* Number of bytes in token */
   141885             int iDum1 = 0, iDum2 = 0; /* Dummy variables */
   141886             int iPos = 0;             /* Position of token in zText */
   141887 
   141888             rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   141889             if( rc==SQLITE_OK ){
   141890               int i;
   141891               cksum2 = cksum2 ^ fts3ChecksumEntry(
   141892                   zToken, nToken, iLang, 0, iDocid, iCol, iPos
   141893               );
   141894               for(i=1; i<p->nIndex; i++){
   141895                 if( p->aIndex[i].nPrefix<=nToken ){
   141896                   cksum2 = cksum2 ^ fts3ChecksumEntry(
   141897                       zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
   141898                   );
   141899                 }
   141900               }
   141901             }
   141902           }
   141903           if( pT ) pModule->xClose(pT);
   141904           if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   141905         }
   141906       }
   141907     }
   141908 
   141909     sqlite3_finalize(pStmt);
   141910   }
   141911 
   141912   *pbOk = (cksum1==cksum2);
   141913   return rc;
   141914 }
   141915 
   141916 /*
   141917 ** Run the integrity-check. If no error occurs and the current contents of
   141918 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
   141919 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
   141920 **
   141921 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
   141922 ** error code.
   141923 **
   141924 ** The integrity-check works as follows. For each token and indexed token
   141925 ** prefix in the document set, a 64-bit checksum is calculated (by code
   141926 ** in fts3ChecksumEntry()) based on the following:
   141927 **
   141928 **     + The index number (0 for the main index, 1 for the first prefix
   141929 **       index etc.),
   141930 **     + The token (or token prefix) text itself,
   141931 **     + The language-id of the row it appears in,
   141932 **     + The docid of the row it appears in,
   141933 **     + The column it appears in, and
   141934 **     + The tokens position within that column.
   141935 **
   141936 ** The checksums for all entries in the index are XORed together to create
   141937 ** a single checksum for the entire index.
   141938 **
   141939 ** The integrity-check code calculates the same checksum in two ways:
   141940 **
   141941 **     1. By scanning the contents of the FTS index, and
   141942 **     2. By scanning and tokenizing the content table.
   141943 **
   141944 ** If the two checksums are identical, the integrity-check is deemed to have
   141945 ** passed.
   141946 */
   141947 static int fts3DoIntegrityCheck(
   141948   Fts3Table *p                    /* FTS3 table handle */
   141949 ){
   141950   int rc;
   141951   int bOk = 0;
   141952   rc = fts3IntegrityCheck(p, &bOk);
   141953   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
   141954   return rc;
   141955 }
   141956 
   141957 /*
   141958 ** Handle a 'special' INSERT of the form:
   141959 **
   141960 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
   141961 **
   141962 ** Argument pVal contains the result of <expr>. Currently the only
   141963 ** meaningful value to insert is the text 'optimize'.
   141964 */
   141965 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
   141966   int rc;                         /* Return Code */
   141967   const char *zVal = (const char *)sqlite3_value_text(pVal);
   141968   int nVal = sqlite3_value_bytes(pVal);
   141969 
   141970   if( !zVal ){
   141971     return SQLITE_NOMEM;
   141972   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
   141973     rc = fts3DoOptimize(p, 0);
   141974   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
   141975     rc = fts3DoRebuild(p);
   141976   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
   141977     rc = fts3DoIntegrityCheck(p);
   141978   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
   141979     rc = fts3DoIncrmerge(p, &zVal[6]);
   141980   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
   141981     rc = fts3DoAutoincrmerge(p, &zVal[10]);
   141982 #ifdef SQLITE_TEST
   141983   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
   141984     p->nNodeSize = atoi(&zVal[9]);
   141985     rc = SQLITE_OK;
   141986   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
   141987     p->nMaxPendingData = atoi(&zVal[11]);
   141988     rc = SQLITE_OK;
   141989   }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
   141990     p->bNoIncrDoclist = atoi(&zVal[21]);
   141991     rc = SQLITE_OK;
   141992 #endif
   141993   }else{
   141994     rc = SQLITE_ERROR;
   141995   }
   141996 
   141997   return rc;
   141998 }
   141999 
   142000 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   142001 /*
   142002 ** Delete all cached deferred doclists. Deferred doclists are cached
   142003 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
   142004 */
   142005 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
   142006   Fts3DeferredToken *pDef;
   142007   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
   142008     fts3PendingListDelete(pDef->pList);
   142009     pDef->pList = 0;
   142010   }
   142011 }
   142012 
   142013 /*
   142014 ** Free all entries in the pCsr->pDeffered list. Entries are added to
   142015 ** this list using sqlite3Fts3DeferToken().
   142016 */
   142017 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
   142018   Fts3DeferredToken *pDef;
   142019   Fts3DeferredToken *pNext;
   142020   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
   142021     pNext = pDef->pNext;
   142022     fts3PendingListDelete(pDef->pList);
   142023     sqlite3_free(pDef);
   142024   }
   142025   pCsr->pDeferred = 0;
   142026 }
   142027 
   142028 /*
   142029 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
   142030 ** based on the row that pCsr currently points to.
   142031 **
   142032 ** A deferred-doclist is like any other doclist with position information
   142033 ** included, except that it only contains entries for a single row of the
   142034 ** table, not for all rows.
   142035 */
   142036 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
   142037   int rc = SQLITE_OK;             /* Return code */
   142038   if( pCsr->pDeferred ){
   142039     int i;                        /* Used to iterate through table columns */
   142040     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
   142041     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
   142042 
   142043     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   142044     sqlite3_tokenizer *pT = p->pTokenizer;
   142045     sqlite3_tokenizer_module const *pModule = pT->pModule;
   142046 
   142047     assert( pCsr->isRequireSeek==0 );
   142048     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
   142049 
   142050     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
   142051       if( p->abNotindexed[i]==0 ){
   142052         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
   142053         sqlite3_tokenizer_cursor *pTC = 0;
   142054 
   142055         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
   142056         while( rc==SQLITE_OK ){
   142057           char const *zToken;       /* Buffer containing token */
   142058           int nToken = 0;           /* Number of bytes in token */
   142059           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
   142060           int iPos = 0;             /* Position of token in zText */
   142061 
   142062           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   142063           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   142064             Fts3PhraseToken *pPT = pDef->pToken;
   142065             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
   142066                 && (pPT->bFirst==0 || iPos==0)
   142067                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
   142068                 && (0==memcmp(zToken, pPT->z, pPT->n))
   142069               ){
   142070               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
   142071             }
   142072           }
   142073         }
   142074         if( pTC ) pModule->xClose(pTC);
   142075         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   142076       }
   142077     }
   142078 
   142079     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   142080       if( pDef->pList ){
   142081         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
   142082       }
   142083     }
   142084   }
   142085 
   142086   return rc;
   142087 }
   142088 
   142089 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
   142090   Fts3DeferredToken *p,
   142091   char **ppData,
   142092   int *pnData
   142093 ){
   142094   char *pRet;
   142095   int nSkip;
   142096   sqlite3_int64 dummy;
   142097 
   142098   *ppData = 0;
   142099   *pnData = 0;
   142100 
   142101   if( p->pList==0 ){
   142102     return SQLITE_OK;
   142103   }
   142104 
   142105   pRet = (char *)sqlite3_malloc(p->pList->nData);
   142106   if( !pRet ) return SQLITE_NOMEM;
   142107 
   142108   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
   142109   *pnData = p->pList->nData - nSkip;
   142110   *ppData = pRet;
   142111 
   142112   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
   142113   return SQLITE_OK;
   142114 }
   142115 
   142116 /*
   142117 ** Add an entry for token pToken to the pCsr->pDeferred list.
   142118 */
   142119 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
   142120   Fts3Cursor *pCsr,               /* Fts3 table cursor */
   142121   Fts3PhraseToken *pToken,        /* Token to defer */
   142122   int iCol                        /* Column that token must appear in (or -1) */
   142123 ){
   142124   Fts3DeferredToken *pDeferred;
   142125   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
   142126   if( !pDeferred ){
   142127     return SQLITE_NOMEM;
   142128   }
   142129   memset(pDeferred, 0, sizeof(*pDeferred));
   142130   pDeferred->pToken = pToken;
   142131   pDeferred->pNext = pCsr->pDeferred;
   142132   pDeferred->iCol = iCol;
   142133   pCsr->pDeferred = pDeferred;
   142134 
   142135   assert( pToken->pDeferred==0 );
   142136   pToken->pDeferred = pDeferred;
   142137 
   142138   return SQLITE_OK;
   142139 }
   142140 #endif
   142141 
   142142 /*
   142143 ** SQLite value pRowid contains the rowid of a row that may or may not be
   142144 ** present in the FTS3 table. If it is, delete it and adjust the contents
   142145 ** of subsiduary data structures accordingly.
   142146 */
   142147 static int fts3DeleteByRowid(
   142148   Fts3Table *p,
   142149   sqlite3_value *pRowid,
   142150   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
   142151   u32 *aSzDel
   142152 ){
   142153   int rc = SQLITE_OK;             /* Return code */
   142154   int bFound = 0;                 /* True if *pRowid really is in the table */
   142155 
   142156   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
   142157   if( bFound && rc==SQLITE_OK ){
   142158     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
   142159     rc = fts3IsEmpty(p, pRowid, &isEmpty);
   142160     if( rc==SQLITE_OK ){
   142161       if( isEmpty ){
   142162         /* Deleting this row means the whole table is empty. In this case
   142163         ** delete the contents of all three tables and throw away any
   142164         ** data in the pendingTerms hash table.  */
   142165         rc = fts3DeleteAll(p, 1);
   142166         *pnChng = 0;
   142167         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
   142168       }else{
   142169         *pnChng = *pnChng - 1;
   142170         if( p->zContentTbl==0 ){
   142171           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
   142172         }
   142173         if( p->bHasDocsize ){
   142174           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
   142175         }
   142176       }
   142177     }
   142178   }
   142179 
   142180   return rc;
   142181 }
   142182 
   142183 /*
   142184 ** This function does the work for the xUpdate method of FTS3 virtual
   142185 ** tables. The schema of the virtual table being:
   142186 **
   142187 **     CREATE TABLE <table name>(
   142188 **       <user columns>,
   142189 **       <table name> HIDDEN,
   142190 **       docid HIDDEN,
   142191 **       <langid> HIDDEN
   142192 **     );
   142193 **
   142194 **
   142195 */
   142196 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   142197   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
   142198   int nArg,                       /* Size of argument array */
   142199   sqlite3_value **apVal,          /* Array of arguments */
   142200   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   142201 ){
   142202   Fts3Table *p = (Fts3Table *)pVtab;
   142203   int rc = SQLITE_OK;             /* Return Code */
   142204   int isRemove = 0;               /* True for an UPDATE or DELETE */
   142205   u32 *aSzIns = 0;                /* Sizes of inserted documents */
   142206   u32 *aSzDel = 0;                /* Sizes of deleted documents */
   142207   int nChng = 0;                  /* Net change in number of documents */
   142208   int bInsertDone = 0;
   142209 
   142210   /* At this point it must be known if the %_stat table exists or not.
   142211   ** So bHasStat may not be 2.  */
   142212   assert( p->bHasStat==0 || p->bHasStat==1 );
   142213 
   142214   assert( p->pSegments==0 );
   142215   assert(
   142216       nArg==1                     /* DELETE operations */
   142217    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
   142218   );
   142219 
   142220   /* Check for a "special" INSERT operation. One of the form:
   142221   **
   142222   **   INSERT INTO xyz(xyz) VALUES('command');
   142223   */
   142224   if( nArg>1
   142225    && sqlite3_value_type(apVal[0])==SQLITE_NULL
   142226    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
   142227   ){
   142228     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
   142229     goto update_out;
   142230   }
   142231 
   142232   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
   142233     rc = SQLITE_CONSTRAINT;
   142234     goto update_out;
   142235   }
   142236 
   142237   /* Allocate space to hold the change in document sizes */
   142238   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
   142239   if( aSzDel==0 ){
   142240     rc = SQLITE_NOMEM;
   142241     goto update_out;
   142242   }
   142243   aSzIns = &aSzDel[p->nColumn+1];
   142244   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
   142245 
   142246   rc = fts3Writelock(p);
   142247   if( rc!=SQLITE_OK ) goto update_out;
   142248 
   142249   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
   142250   ** value, then this operation requires constraint handling.
   142251   **
   142252   ** If the on-conflict mode is REPLACE, this means that the existing row
   142253   ** should be deleted from the database before inserting the new row. Or,
   142254   ** if the on-conflict mode is other than REPLACE, then this method must
   142255   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
   142256   ** modify the database file.
   142257   */
   142258   if( nArg>1 && p->zContentTbl==0 ){
   142259     /* Find the value object that holds the new rowid value. */
   142260     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
   142261     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
   142262       pNewRowid = apVal[1];
   142263     }
   142264 
   142265     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
   142266         sqlite3_value_type(apVal[0])==SQLITE_NULL
   142267      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
   142268     )){
   142269       /* The new rowid is not NULL (in this case the rowid will be
   142270       ** automatically assigned and there is no chance of a conflict), and
   142271       ** the statement is either an INSERT or an UPDATE that modifies the
   142272       ** rowid column. So if the conflict mode is REPLACE, then delete any
   142273       ** existing row with rowid=pNewRowid.
   142274       **
   142275       ** Or, if the conflict mode is not REPLACE, insert the new record into
   142276       ** the %_content table. If we hit the duplicate rowid constraint (or any
   142277       ** other error) while doing so, return immediately.
   142278       **
   142279       ** This branch may also run if pNewRowid contains a value that cannot
   142280       ** be losslessly converted to an integer. In this case, the eventual
   142281       ** call to fts3InsertData() (either just below or further on in this
   142282       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
   142283       ** invoked, it will delete zero rows (since no row will have
   142284       ** docid=$pNewRowid if $pNewRowid is not an integer value).
   142285       */
   142286       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
   142287         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
   142288       }else{
   142289         rc = fts3InsertData(p, apVal, pRowid);
   142290         bInsertDone = 1;
   142291       }
   142292     }
   142293   }
   142294   if( rc!=SQLITE_OK ){
   142295     goto update_out;
   142296   }
   142297 
   142298   /* If this is a DELETE or UPDATE operation, remove the old record. */
   142299   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   142300     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
   142301     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
   142302     isRemove = 1;
   142303   }
   142304 
   142305   /* If this is an INSERT or UPDATE operation, insert the new record. */
   142306   if( nArg>1 && rc==SQLITE_OK ){
   142307     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
   142308     if( bInsertDone==0 ){
   142309       rc = fts3InsertData(p, apVal, pRowid);
   142310       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
   142311         rc = FTS_CORRUPT_VTAB;
   142312       }
   142313     }
   142314     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
   142315       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
   142316     }
   142317     if( rc==SQLITE_OK ){
   142318       assert( p->iPrevDocid==*pRowid );
   142319       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
   142320     }
   142321     if( p->bHasDocsize ){
   142322       fts3InsertDocsize(&rc, p, aSzIns);
   142323     }
   142324     nChng++;
   142325   }
   142326 
   142327   if( p->bFts4 ){
   142328     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
   142329   }
   142330 
   142331  update_out:
   142332   sqlite3_free(aSzDel);
   142333   sqlite3Fts3SegmentsClose(p);
   142334   return rc;
   142335 }
   142336 
   142337 /*
   142338 ** Flush any data in the pending-terms hash table to disk. If successful,
   142339 ** merge all segments in the database (including the new segment, if
   142340 ** there was any data to flush) into a single segment.
   142341 */
   142342 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
   142343   int rc;
   142344   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
   142345   if( rc==SQLITE_OK ){
   142346     rc = fts3DoOptimize(p, 1);
   142347     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
   142348       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   142349       if( rc2!=SQLITE_OK ) rc = rc2;
   142350     }else{
   142351       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
   142352       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   142353     }
   142354   }
   142355   sqlite3Fts3SegmentsClose(p);
   142356   return rc;
   142357 }
   142358 
   142359 #endif
   142360 
   142361 /************** End of fts3_write.c ******************************************/
   142362 /************** Begin file fts3_snippet.c ************************************/
   142363 /*
   142364 ** 2009 Oct 23
   142365 **
   142366 ** The author disclaims copyright to this source code.  In place of
   142367 ** a legal notice, here is a blessing:
   142368 **
   142369 **    May you do good and not evil.
   142370 **    May you find forgiveness for yourself and forgive others.
   142371 **    May you share freely, never taking more than you give.
   142372 **
   142373 ******************************************************************************
   142374 */
   142375 
   142376 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   142377 
   142378 /* #include <string.h> */
   142379 /* #include <assert.h> */
   142380 
   142381 /*
   142382 ** Characters that may appear in the second argument to matchinfo().
   142383 */
   142384 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
   142385 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
   142386 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
   142387 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
   142388 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
   142389 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
   142390 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
   142391 
   142392 /*
   142393 ** The default value for the second argument to matchinfo().
   142394 */
   142395 #define FTS3_MATCHINFO_DEFAULT   "pcx"
   142396 
   142397 
   142398 /*
   142399 ** Used as an fts3ExprIterate() context when loading phrase doclists to
   142400 ** Fts3Expr.aDoclist[]/nDoclist.
   142401 */
   142402 typedef struct LoadDoclistCtx LoadDoclistCtx;
   142403 struct LoadDoclistCtx {
   142404   Fts3Cursor *pCsr;               /* FTS3 Cursor */
   142405   int nPhrase;                    /* Number of phrases seen so far */
   142406   int nToken;                     /* Number of tokens seen so far */
   142407 };
   142408 
   142409 /*
   142410 ** The following types are used as part of the implementation of the
   142411 ** fts3BestSnippet() routine.
   142412 */
   142413 typedef struct SnippetIter SnippetIter;
   142414 typedef struct SnippetPhrase SnippetPhrase;
   142415 typedef struct SnippetFragment SnippetFragment;
   142416 
   142417 struct SnippetIter {
   142418   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
   142419   int iCol;                       /* Extract snippet from this column */
   142420   int nSnippet;                   /* Requested snippet length (in tokens) */
   142421   int nPhrase;                    /* Number of phrases in query */
   142422   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
   142423   int iCurrent;                   /* First token of current snippet */
   142424 };
   142425 
   142426 struct SnippetPhrase {
   142427   int nToken;                     /* Number of tokens in phrase */
   142428   char *pList;                    /* Pointer to start of phrase position list */
   142429   int iHead;                      /* Next value in position list */
   142430   char *pHead;                    /* Position list data following iHead */
   142431   int iTail;                      /* Next value in trailing position list */
   142432   char *pTail;                    /* Position list data following iTail */
   142433 };
   142434 
   142435 struct SnippetFragment {
   142436   int iCol;                       /* Column snippet is extracted from */
   142437   int iPos;                       /* Index of first token in snippet */
   142438   u64 covered;                    /* Mask of query phrases covered */
   142439   u64 hlmask;                     /* Mask of snippet terms to highlight */
   142440 };
   142441 
   142442 /*
   142443 ** This type is used as an fts3ExprIterate() context object while
   142444 ** accumulating the data returned by the matchinfo() function.
   142445 */
   142446 typedef struct MatchInfo MatchInfo;
   142447 struct MatchInfo {
   142448   Fts3Cursor *pCursor;            /* FTS3 Cursor */
   142449   int nCol;                       /* Number of columns in table */
   142450   int nPhrase;                    /* Number of matchable phrases in query */
   142451   sqlite3_int64 nDoc;             /* Number of docs in database */
   142452   u32 *aMatchinfo;                /* Pre-allocated buffer */
   142453 };
   142454 
   142455 
   142456 
   142457 /*
   142458 ** The snippet() and offsets() functions both return text values. An instance
   142459 ** of the following structure is used to accumulate those values while the
   142460 ** functions are running. See fts3StringAppend() for details.
   142461 */
   142462 typedef struct StrBuffer StrBuffer;
   142463 struct StrBuffer {
   142464   char *z;                        /* Pointer to buffer containing string */
   142465   int n;                          /* Length of z in bytes (excl. nul-term) */
   142466   int nAlloc;                     /* Allocated size of buffer z in bytes */
   142467 };
   142468 
   142469 
   142470 /*
   142471 ** This function is used to help iterate through a position-list. A position
   142472 ** list is a list of unique integers, sorted from smallest to largest. Each
   142473 ** element of the list is represented by an FTS3 varint that takes the value
   142474 ** of the difference between the current element and the previous one plus
   142475 ** two. For example, to store the position-list:
   142476 **
   142477 **     4 9 113
   142478 **
   142479 ** the three varints:
   142480 **
   142481 **     6 7 106
   142482 **
   142483 ** are encoded.
   142484 **
   142485 ** When this function is called, *pp points to the start of an element of
   142486 ** the list. *piPos contains the value of the previous entry in the list.
   142487 ** After it returns, *piPos contains the value of the next element of the
   142488 ** list and *pp is advanced to the following varint.
   142489 */
   142490 static void fts3GetDeltaPosition(char **pp, int *piPos){
   142491   int iVal;
   142492   *pp += fts3GetVarint32(*pp, &iVal);
   142493   *piPos += (iVal-2);
   142494 }
   142495 
   142496 /*
   142497 ** Helper function for fts3ExprIterate() (see below).
   142498 */
   142499 static int fts3ExprIterate2(
   142500   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   142501   int *piPhrase,                  /* Pointer to phrase counter */
   142502   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   142503   void *pCtx                      /* Second argument to pass to callback */
   142504 ){
   142505   int rc;                         /* Return code */
   142506   int eType = pExpr->eType;       /* Type of expression node pExpr */
   142507 
   142508   if( eType!=FTSQUERY_PHRASE ){
   142509     assert( pExpr->pLeft && pExpr->pRight );
   142510     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
   142511     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
   142512       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
   142513     }
   142514   }else{
   142515     rc = x(pExpr, *piPhrase, pCtx);
   142516     (*piPhrase)++;
   142517   }
   142518   return rc;
   142519 }
   142520 
   142521 /*
   142522 ** Iterate through all phrase nodes in an FTS3 query, except those that
   142523 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
   142524 ** For each phrase node found, the supplied callback function is invoked.
   142525 **
   142526 ** If the callback function returns anything other than SQLITE_OK,
   142527 ** the iteration is abandoned and the error code returned immediately.
   142528 ** Otherwise, SQLITE_OK is returned after a callback has been made for
   142529 ** all eligible phrase nodes.
   142530 */
   142531 static int fts3ExprIterate(
   142532   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   142533   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   142534   void *pCtx                      /* Second argument to pass to callback */
   142535 ){
   142536   int iPhrase = 0;                /* Variable used as the phrase counter */
   142537   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
   142538 }
   142539 
   142540 /*
   142541 ** This is an fts3ExprIterate() callback used while loading the doclists
   142542 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
   142543 ** fts3ExprLoadDoclists().
   142544 */
   142545 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   142546   int rc = SQLITE_OK;
   142547   Fts3Phrase *pPhrase = pExpr->pPhrase;
   142548   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
   142549 
   142550   UNUSED_PARAMETER(iPhrase);
   142551 
   142552   p->nPhrase++;
   142553   p->nToken += pPhrase->nToken;
   142554 
   142555   return rc;
   142556 }
   142557 
   142558 /*
   142559 ** Load the doclists for each phrase in the query associated with FTS3 cursor
   142560 ** pCsr.
   142561 **
   142562 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
   142563 ** phrases in the expression (all phrases except those directly or
   142564 ** indirectly descended from the right-hand-side of a NOT operator). If
   142565 ** pnToken is not NULL, then it is set to the number of tokens in all
   142566 ** matchable phrases of the expression.
   142567 */
   142568 static int fts3ExprLoadDoclists(
   142569   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
   142570   int *pnPhrase,                  /* OUT: Number of phrases in query */
   142571   int *pnToken                    /* OUT: Number of tokens in query */
   142572 ){
   142573   int rc;                         /* Return Code */
   142574   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
   142575   sCtx.pCsr = pCsr;
   142576   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
   142577   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
   142578   if( pnToken ) *pnToken = sCtx.nToken;
   142579   return rc;
   142580 }
   142581 
   142582 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   142583   (*(int *)ctx)++;
   142584   UNUSED_PARAMETER(pExpr);
   142585   UNUSED_PARAMETER(iPhrase);
   142586   return SQLITE_OK;
   142587 }
   142588 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
   142589   int nPhrase = 0;
   142590   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
   142591   return nPhrase;
   142592 }
   142593 
   142594 /*
   142595 ** Advance the position list iterator specified by the first two
   142596 ** arguments so that it points to the first element with a value greater
   142597 ** than or equal to parameter iNext.
   142598 */
   142599 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
   142600   char *pIter = *ppIter;
   142601   if( pIter ){
   142602     int iIter = *piIter;
   142603 
   142604     while( iIter<iNext ){
   142605       if( 0==(*pIter & 0xFE) ){
   142606         iIter = -1;
   142607         pIter = 0;
   142608         break;
   142609       }
   142610       fts3GetDeltaPosition(&pIter, &iIter);
   142611     }
   142612 
   142613     *piIter = iIter;
   142614     *ppIter = pIter;
   142615   }
   142616 }
   142617 
   142618 /*
   142619 ** Advance the snippet iterator to the next candidate snippet.
   142620 */
   142621 static int fts3SnippetNextCandidate(SnippetIter *pIter){
   142622   int i;                          /* Loop counter */
   142623 
   142624   if( pIter->iCurrent<0 ){
   142625     /* The SnippetIter object has just been initialized. The first snippet
   142626     ** candidate always starts at offset 0 (even if this candidate has a
   142627     ** score of 0.0).
   142628     */
   142629     pIter->iCurrent = 0;
   142630 
   142631     /* Advance the 'head' iterator of each phrase to the first offset that
   142632     ** is greater than or equal to (iNext+nSnippet).
   142633     */
   142634     for(i=0; i<pIter->nPhrase; i++){
   142635       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   142636       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
   142637     }
   142638   }else{
   142639     int iStart;
   142640     int iEnd = 0x7FFFFFFF;
   142641 
   142642     for(i=0; i<pIter->nPhrase; i++){
   142643       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   142644       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
   142645         iEnd = pPhrase->iHead;
   142646       }
   142647     }
   142648     if( iEnd==0x7FFFFFFF ){
   142649       return 1;
   142650     }
   142651 
   142652     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
   142653     for(i=0; i<pIter->nPhrase; i++){
   142654       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   142655       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
   142656       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
   142657     }
   142658   }
   142659 
   142660   return 0;
   142661 }
   142662 
   142663 /*
   142664 ** Retrieve information about the current candidate snippet of snippet
   142665 ** iterator pIter.
   142666 */
   142667 static void fts3SnippetDetails(
   142668   SnippetIter *pIter,             /* Snippet iterator */
   142669   u64 mCovered,                   /* Bitmask of phrases already covered */
   142670   int *piToken,                   /* OUT: First token of proposed snippet */
   142671   int *piScore,                   /* OUT: "Score" for this snippet */
   142672   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
   142673   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
   142674 ){
   142675   int iStart = pIter->iCurrent;   /* First token of snippet */
   142676   int iScore = 0;                 /* Score of this snippet */
   142677   int i;                          /* Loop counter */
   142678   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
   142679   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
   142680 
   142681   for(i=0; i<pIter->nPhrase; i++){
   142682     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   142683     if( pPhrase->pTail ){
   142684       char *pCsr = pPhrase->pTail;
   142685       int iCsr = pPhrase->iTail;
   142686 
   142687       while( iCsr<(iStart+pIter->nSnippet) ){
   142688         int j;
   142689         u64 mPhrase = (u64)1 << i;
   142690         u64 mPos = (u64)1 << (iCsr - iStart);
   142691         assert( iCsr>=iStart );
   142692         if( (mCover|mCovered)&mPhrase ){
   142693           iScore++;
   142694         }else{
   142695           iScore += 1000;
   142696         }
   142697         mCover |= mPhrase;
   142698 
   142699         for(j=0; j<pPhrase->nToken; j++){
   142700           mHighlight |= (mPos>>j);
   142701         }
   142702 
   142703         if( 0==(*pCsr & 0x0FE) ) break;
   142704         fts3GetDeltaPosition(&pCsr, &iCsr);
   142705       }
   142706     }
   142707   }
   142708 
   142709   /* Set the output variables before returning. */
   142710   *piToken = iStart;
   142711   *piScore = iScore;
   142712   *pmCover = mCover;
   142713   *pmHighlight = mHighlight;
   142714 }
   142715 
   142716 /*
   142717 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
   142718 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
   142719 */
   142720 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
   142721   SnippetIter *p = (SnippetIter *)ctx;
   142722   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
   142723   char *pCsr;
   142724   int rc;
   142725 
   142726   pPhrase->nToken = pExpr->pPhrase->nToken;
   142727   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
   142728   assert( rc==SQLITE_OK || pCsr==0 );
   142729   if( pCsr ){
   142730     int iFirst = 0;
   142731     pPhrase->pList = pCsr;
   142732     fts3GetDeltaPosition(&pCsr, &iFirst);
   142733     assert( iFirst>=0 );
   142734     pPhrase->pHead = pCsr;
   142735     pPhrase->pTail = pCsr;
   142736     pPhrase->iHead = iFirst;
   142737     pPhrase->iTail = iFirst;
   142738   }else{
   142739     assert( rc!=SQLITE_OK || (
   142740        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
   142741     ));
   142742   }
   142743 
   142744   return rc;
   142745 }
   142746 
   142747 /*
   142748 ** Select the fragment of text consisting of nFragment contiguous tokens
   142749 ** from column iCol that represent the "best" snippet. The best snippet
   142750 ** is the snippet with the highest score, where scores are calculated
   142751 ** by adding:
   142752 **
   142753 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
   142754 **
   142755 **   (b) +1000 points for the first occurrence of each matchable phrase in
   142756 **       the snippet for which the corresponding mCovered bit is not set.
   142757 **
   142758 ** The selected snippet parameters are stored in structure *pFragment before
   142759 ** returning. The score of the selected snippet is stored in *piScore
   142760 ** before returning.
   142761 */
   142762 static int fts3BestSnippet(
   142763   int nSnippet,                   /* Desired snippet length */
   142764   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
   142765   int iCol,                       /* Index of column to create snippet from */
   142766   u64 mCovered,                   /* Mask of phrases already covered */
   142767   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
   142768   SnippetFragment *pFragment,     /* OUT: Best snippet found */
   142769   int *piScore                    /* OUT: Score of snippet pFragment */
   142770 ){
   142771   int rc;                         /* Return Code */
   142772   int nList;                      /* Number of phrases in expression */
   142773   SnippetIter sIter;              /* Iterates through snippet candidates */
   142774   int nByte;                      /* Number of bytes of space to allocate */
   142775   int iBestScore = -1;            /* Best snippet score found so far */
   142776   int i;                          /* Loop counter */
   142777 
   142778   memset(&sIter, 0, sizeof(sIter));
   142779 
   142780   /* Iterate through the phrases in the expression to count them. The same
   142781   ** callback makes sure the doclists are loaded for each phrase.
   142782   */
   142783   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
   142784   if( rc!=SQLITE_OK ){
   142785     return rc;
   142786   }
   142787 
   142788   /* Now that it is known how many phrases there are, allocate and zero
   142789   ** the required space using malloc().
   142790   */
   142791   nByte = sizeof(SnippetPhrase) * nList;
   142792   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
   142793   if( !sIter.aPhrase ){
   142794     return SQLITE_NOMEM;
   142795   }
   142796   memset(sIter.aPhrase, 0, nByte);
   142797 
   142798   /* Initialize the contents of the SnippetIter object. Then iterate through
   142799   ** the set of phrases in the expression to populate the aPhrase[] array.
   142800   */
   142801   sIter.pCsr = pCsr;
   142802   sIter.iCol = iCol;
   142803   sIter.nSnippet = nSnippet;
   142804   sIter.nPhrase = nList;
   142805   sIter.iCurrent = -1;
   142806   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
   142807 
   142808   /* Set the *pmSeen output variable. */
   142809   for(i=0; i<nList; i++){
   142810     if( sIter.aPhrase[i].pHead ){
   142811       *pmSeen |= (u64)1 << i;
   142812     }
   142813   }
   142814 
   142815   /* Loop through all candidate snippets. Store the best snippet in
   142816   ** *pFragment. Store its associated 'score' in iBestScore.
   142817   */
   142818   pFragment->iCol = iCol;
   142819   while( !fts3SnippetNextCandidate(&sIter) ){
   142820     int iPos;
   142821     int iScore;
   142822     u64 mCover;
   142823     u64 mHighlight;
   142824     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
   142825     assert( iScore>=0 );
   142826     if( iScore>iBestScore ){
   142827       pFragment->iPos = iPos;
   142828       pFragment->hlmask = mHighlight;
   142829       pFragment->covered = mCover;
   142830       iBestScore = iScore;
   142831     }
   142832   }
   142833 
   142834   sqlite3_free(sIter.aPhrase);
   142835   *piScore = iBestScore;
   142836   return SQLITE_OK;
   142837 }
   142838 
   142839 
   142840 /*
   142841 ** Append a string to the string-buffer passed as the first argument.
   142842 **
   142843 ** If nAppend is negative, then the length of the string zAppend is
   142844 ** determined using strlen().
   142845 */
   142846 static int fts3StringAppend(
   142847   StrBuffer *pStr,                /* Buffer to append to */
   142848   const char *zAppend,            /* Pointer to data to append to buffer */
   142849   int nAppend                     /* Size of zAppend in bytes (or -1) */
   142850 ){
   142851   if( nAppend<0 ){
   142852     nAppend = (int)strlen(zAppend);
   142853   }
   142854 
   142855   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
   142856   ** to grow the buffer until so that it is big enough to accomadate the
   142857   ** appended data.
   142858   */
   142859   if( pStr->n+nAppend+1>=pStr->nAlloc ){
   142860     int nAlloc = pStr->nAlloc+nAppend+100;
   142861     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
   142862     if( !zNew ){
   142863       return SQLITE_NOMEM;
   142864     }
   142865     pStr->z = zNew;
   142866     pStr->nAlloc = nAlloc;
   142867   }
   142868   assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
   142869 
   142870   /* Append the data to the string buffer. */
   142871   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
   142872   pStr->n += nAppend;
   142873   pStr->z[pStr->n] = '\0';
   142874 
   142875   return SQLITE_OK;
   142876 }
   142877 
   142878 /*
   142879 ** The fts3BestSnippet() function often selects snippets that end with a
   142880 ** query term. That is, the final term of the snippet is always a term
   142881 ** that requires highlighting. For example, if 'X' is a highlighted term
   142882 ** and '.' is a non-highlighted term, BestSnippet() may select:
   142883 **
   142884 **     ........X.....X
   142885 **
   142886 ** This function "shifts" the beginning of the snippet forward in the
   142887 ** document so that there are approximately the same number of
   142888 ** non-highlighted terms to the right of the final highlighted term as there
   142889 ** are to the left of the first highlighted term. For example, to this:
   142890 **
   142891 **     ....X.....X....
   142892 **
   142893 ** This is done as part of extracting the snippet text, not when selecting
   142894 ** the snippet. Snippet selection is done based on doclists only, so there
   142895 ** is no way for fts3BestSnippet() to know whether or not the document
   142896 ** actually contains terms that follow the final highlighted term.
   142897 */
   142898 static int fts3SnippetShift(
   142899   Fts3Table *pTab,                /* FTS3 table snippet comes from */
   142900   int iLangid,                    /* Language id to use in tokenizing */
   142901   int nSnippet,                   /* Number of tokens desired for snippet */
   142902   const char *zDoc,               /* Document text to extract snippet from */
   142903   int nDoc,                       /* Size of buffer zDoc in bytes */
   142904   int *piPos,                     /* IN/OUT: First token of snippet */
   142905   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
   142906 ){
   142907   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
   142908 
   142909   if( hlmask ){
   142910     int nLeft;                    /* Tokens to the left of first highlight */
   142911     int nRight;                   /* Tokens to the right of last highlight */
   142912     int nDesired;                 /* Ideal number of tokens to shift forward */
   142913 
   142914     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
   142915     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
   142916     nDesired = (nLeft-nRight)/2;
   142917 
   142918     /* Ideally, the start of the snippet should be pushed forward in the
   142919     ** document nDesired tokens. This block checks if there are actually
   142920     ** nDesired tokens to the right of the snippet. If so, *piPos and
   142921     ** *pHlMask are updated to shift the snippet nDesired tokens to the
   142922     ** right. Otherwise, the snippet is shifted by the number of tokens
   142923     ** available.
   142924     */
   142925     if( nDesired>0 ){
   142926       int nShift;                 /* Number of tokens to shift snippet by */
   142927       int iCurrent = 0;           /* Token counter */
   142928       int rc;                     /* Return Code */
   142929       sqlite3_tokenizer_module *pMod;
   142930       sqlite3_tokenizer_cursor *pC;
   142931       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   142932 
   142933       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
   142934       ** or more tokens in zDoc/nDoc.
   142935       */
   142936       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
   142937       if( rc!=SQLITE_OK ){
   142938         return rc;
   142939       }
   142940       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
   142941         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
   142942         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
   142943       }
   142944       pMod->xClose(pC);
   142945       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
   142946 
   142947       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
   142948       assert( nShift<=nDesired );
   142949       if( nShift>0 ){
   142950         *piPos += nShift;
   142951         *pHlmask = hlmask >> nShift;
   142952       }
   142953     }
   142954   }
   142955   return SQLITE_OK;
   142956 }
   142957 
   142958 /*
   142959 ** Extract the snippet text for fragment pFragment from cursor pCsr and
   142960 ** append it to string buffer pOut.
   142961 */
   142962 static int fts3SnippetText(
   142963   Fts3Cursor *pCsr,               /* FTS3 Cursor */
   142964   SnippetFragment *pFragment,     /* Snippet to extract */
   142965   int iFragment,                  /* Fragment number */
   142966   int isLast,                     /* True for final fragment in snippet */
   142967   int nSnippet,                   /* Number of tokens in extracted snippet */
   142968   const char *zOpen,              /* String inserted before highlighted term */
   142969   const char *zClose,             /* String inserted after highlighted term */
   142970   const char *zEllipsis,          /* String inserted between snippets */
   142971   StrBuffer *pOut                 /* Write output here */
   142972 ){
   142973   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   142974   int rc;                         /* Return code */
   142975   const char *zDoc;               /* Document text to extract snippet from */
   142976   int nDoc;                       /* Size of zDoc in bytes */
   142977   int iCurrent = 0;               /* Current token number of document */
   142978   int iEnd = 0;                   /* Byte offset of end of current token */
   142979   int isShiftDone = 0;            /* True after snippet is shifted */
   142980   int iPos = pFragment->iPos;     /* First token of snippet */
   142981   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
   142982   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
   142983   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
   142984   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
   142985 
   142986   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
   142987   if( zDoc==0 ){
   142988     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
   142989       return SQLITE_NOMEM;
   142990     }
   142991     return SQLITE_OK;
   142992   }
   142993   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
   142994 
   142995   /* Open a token cursor on the document. */
   142996   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   142997   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
   142998   if( rc!=SQLITE_OK ){
   142999     return rc;
   143000   }
   143001 
   143002   while( rc==SQLITE_OK ){
   143003     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
   143004     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
   143005     int iBegin = 0;               /* Offset in zDoc of start of token */
   143006     int iFin = 0;                 /* Offset in zDoc of end of token */
   143007     int isHighlight = 0;          /* True for highlighted terms */
   143008 
   143009     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
   143010     ** in the FTS code the variable that the third argument to xNext points to
   143011     ** is initialized to zero before the first (*but not necessarily
   143012     ** subsequent*) call to xNext(). This is done for a particular application
   143013     ** that needs to know whether or not the tokenizer is being used for
   143014     ** snippet generation or for some other purpose.
   143015     **
   143016     ** Extreme care is required when writing code to depend on this
   143017     ** initialization. It is not a documented part of the tokenizer interface.
   143018     ** If a tokenizer is used directly by any code outside of FTS, this
   143019     ** convention might not be respected.  */
   143020     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
   143021     if( rc!=SQLITE_OK ){
   143022       if( rc==SQLITE_DONE ){
   143023         /* Special case - the last token of the snippet is also the last token
   143024         ** of the column. Append any punctuation that occurred between the end
   143025         ** of the previous token and the end of the document to the output.
   143026         ** Then break out of the loop. */
   143027         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
   143028       }
   143029       break;
   143030     }
   143031     if( iCurrent<iPos ){ continue; }
   143032 
   143033     if( !isShiftDone ){
   143034       int n = nDoc - iBegin;
   143035       rc = fts3SnippetShift(
   143036           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
   143037       );
   143038       isShiftDone = 1;
   143039 
   143040       /* Now that the shift has been done, check if the initial "..." are
   143041       ** required. They are required if (a) this is not the first fragment,
   143042       ** or (b) this fragment does not begin at position 0 of its column.
   143043       */
   143044       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
   143045         rc = fts3StringAppend(pOut, zEllipsis, -1);
   143046       }
   143047       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
   143048     }
   143049 
   143050     if( iCurrent>=(iPos+nSnippet) ){
   143051       if( isLast ){
   143052         rc = fts3StringAppend(pOut, zEllipsis, -1);
   143053       }
   143054       break;
   143055     }
   143056 
   143057     /* Set isHighlight to true if this term should be highlighted. */
   143058     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
   143059 
   143060     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
   143061     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
   143062     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
   143063     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
   143064 
   143065     iEnd = iFin;
   143066   }
   143067 
   143068   pMod->xClose(pC);
   143069   return rc;
   143070 }
   143071 
   143072 
   143073 /*
   143074 ** This function is used to count the entries in a column-list (a
   143075 ** delta-encoded list of term offsets within a single column of a single
   143076 ** row). When this function is called, *ppCollist should point to the
   143077 ** beginning of the first varint in the column-list (the varint that
   143078 ** contains the position of the first matching term in the column data).
   143079 ** Before returning, *ppCollist is set to point to the first byte after
   143080 ** the last varint in the column-list (either the 0x00 signifying the end
   143081 ** of the position-list, or the 0x01 that precedes the column number of
   143082 ** the next column in the position-list).
   143083 **
   143084 ** The number of elements in the column-list is returned.
   143085 */
   143086 static int fts3ColumnlistCount(char **ppCollist){
   143087   char *pEnd = *ppCollist;
   143088   char c = 0;
   143089   int nEntry = 0;
   143090 
   143091   /* A column-list is terminated by either a 0x01 or 0x00. */
   143092   while( 0xFE & (*pEnd | c) ){
   143093     c = *pEnd++ & 0x80;
   143094     if( !c ) nEntry++;
   143095   }
   143096 
   143097   *ppCollist = pEnd;
   143098   return nEntry;
   143099 }
   143100 
   143101 /*
   143102 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
   143103 ** for a single query.
   143104 **
   143105 ** fts3ExprIterate() callback to load the 'global' elements of a
   143106 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
   143107 ** of the matchinfo array that are constant for all rows returned by the
   143108 ** current query.
   143109 **
   143110 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
   143111 ** function populates Matchinfo.aMatchinfo[] as follows:
   143112 **
   143113 **   for(iCol=0; iCol<nCol; iCol++){
   143114 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
   143115 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
   143116 **   }
   143117 **
   143118 ** where X is the number of matches for phrase iPhrase is column iCol of all
   143119 ** rows of the table. Y is the number of rows for which column iCol contains
   143120 ** at least one instance of phrase iPhrase.
   143121 **
   143122 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
   143123 ** Y values are set to nDoc, where nDoc is the number of documents in the
   143124 ** file system. This is done because the full-text index doclist is required
   143125 ** to calculate these values properly, and the full-text index doclist is
   143126 ** not available for deferred tokens.
   143127 */
   143128 static int fts3ExprGlobalHitsCb(
   143129   Fts3Expr *pExpr,                /* Phrase expression node */
   143130   int iPhrase,                    /* Phrase number (numbered from zero) */
   143131   void *pCtx                      /* Pointer to MatchInfo structure */
   143132 ){
   143133   MatchInfo *p = (MatchInfo *)pCtx;
   143134   return sqlite3Fts3EvalPhraseStats(
   143135       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
   143136   );
   143137 }
   143138 
   143139 /*
   143140 ** fts3ExprIterate() callback used to collect the "local" part of the
   143141 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
   143142 ** array that are different for each row returned by the query.
   143143 */
   143144 static int fts3ExprLocalHitsCb(
   143145   Fts3Expr *pExpr,                /* Phrase expression node */
   143146   int iPhrase,                    /* Phrase number */
   143147   void *pCtx                      /* Pointer to MatchInfo structure */
   143148 ){
   143149   int rc = SQLITE_OK;
   143150   MatchInfo *p = (MatchInfo *)pCtx;
   143151   int iStart = iPhrase * p->nCol * 3;
   143152   int i;
   143153 
   143154   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
   143155     char *pCsr;
   143156     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
   143157     if( pCsr ){
   143158       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
   143159     }else{
   143160       p->aMatchinfo[iStart+i*3] = 0;
   143161     }
   143162   }
   143163 
   143164   return rc;
   143165 }
   143166 
   143167 static int fts3MatchinfoCheck(
   143168   Fts3Table *pTab,
   143169   char cArg,
   143170   char **pzErr
   143171 ){
   143172   if( (cArg==FTS3_MATCHINFO_NPHRASE)
   143173    || (cArg==FTS3_MATCHINFO_NCOL)
   143174    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
   143175    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
   143176    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
   143177    || (cArg==FTS3_MATCHINFO_LCS)
   143178    || (cArg==FTS3_MATCHINFO_HITS)
   143179   ){
   143180     return SQLITE_OK;
   143181   }
   143182   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
   143183   return SQLITE_ERROR;
   143184 }
   143185 
   143186 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
   143187   int nVal;                       /* Number of integers output by cArg */
   143188 
   143189   switch( cArg ){
   143190     case FTS3_MATCHINFO_NDOC:
   143191     case FTS3_MATCHINFO_NPHRASE:
   143192     case FTS3_MATCHINFO_NCOL:
   143193       nVal = 1;
   143194       break;
   143195 
   143196     case FTS3_MATCHINFO_AVGLENGTH:
   143197     case FTS3_MATCHINFO_LENGTH:
   143198     case FTS3_MATCHINFO_LCS:
   143199       nVal = pInfo->nCol;
   143200       break;
   143201 
   143202     default:
   143203       assert( cArg==FTS3_MATCHINFO_HITS );
   143204       nVal = pInfo->nCol * pInfo->nPhrase * 3;
   143205       break;
   143206   }
   143207 
   143208   return nVal;
   143209 }
   143210 
   143211 static int fts3MatchinfoSelectDoctotal(
   143212   Fts3Table *pTab,
   143213   sqlite3_stmt **ppStmt,
   143214   sqlite3_int64 *pnDoc,
   143215   const char **paLen
   143216 ){
   143217   sqlite3_stmt *pStmt;
   143218   const char *a;
   143219   sqlite3_int64 nDoc;
   143220 
   143221   if( !*ppStmt ){
   143222     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
   143223     if( rc!=SQLITE_OK ) return rc;
   143224   }
   143225   pStmt = *ppStmt;
   143226   assert( sqlite3_data_count(pStmt)==1 );
   143227 
   143228   a = sqlite3_column_blob(pStmt, 0);
   143229   a += sqlite3Fts3GetVarint(a, &nDoc);
   143230   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
   143231   *pnDoc = (u32)nDoc;
   143232 
   143233   if( paLen ) *paLen = a;
   143234   return SQLITE_OK;
   143235 }
   143236 
   143237 /*
   143238 ** An instance of the following structure is used to store state while
   143239 ** iterating through a multi-column position-list corresponding to the
   143240 ** hits for a single phrase on a single row in order to calculate the
   143241 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
   143242 */
   143243 typedef struct LcsIterator LcsIterator;
   143244 struct LcsIterator {
   143245   Fts3Expr *pExpr;                /* Pointer to phrase expression */
   143246   int iPosOffset;                 /* Tokens count up to end of this phrase */
   143247   char *pRead;                    /* Cursor used to iterate through aDoclist */
   143248   int iPos;                       /* Current position */
   143249 };
   143250 
   143251 /*
   143252 ** If LcsIterator.iCol is set to the following value, the iterator has
   143253 ** finished iterating through all offsets for all columns.
   143254 */
   143255 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
   143256 
   143257 static int fts3MatchinfoLcsCb(
   143258   Fts3Expr *pExpr,                /* Phrase expression node */
   143259   int iPhrase,                    /* Phrase number (numbered from zero) */
   143260   void *pCtx                      /* Pointer to MatchInfo structure */
   143261 ){
   143262   LcsIterator *aIter = (LcsIterator *)pCtx;
   143263   aIter[iPhrase].pExpr = pExpr;
   143264   return SQLITE_OK;
   143265 }
   143266 
   143267 /*
   143268 ** Advance the iterator passed as an argument to the next position. Return
   143269 ** 1 if the iterator is at EOF or if it now points to the start of the
   143270 ** position list for the next column.
   143271 */
   143272 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
   143273   char *pRead = pIter->pRead;
   143274   sqlite3_int64 iRead;
   143275   int rc = 0;
   143276 
   143277   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   143278   if( iRead==0 || iRead==1 ){
   143279     pRead = 0;
   143280     rc = 1;
   143281   }else{
   143282     pIter->iPos += (int)(iRead-2);
   143283   }
   143284 
   143285   pIter->pRead = pRead;
   143286   return rc;
   143287 }
   143288 
   143289 /*
   143290 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
   143291 **
   143292 ** If the call is successful, the longest-common-substring lengths for each
   143293 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
   143294 ** array before returning. SQLITE_OK is returned in this case.
   143295 **
   143296 ** Otherwise, if an error occurs, an SQLite error code is returned and the
   143297 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
   143298 ** undefined.
   143299 */
   143300 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
   143301   LcsIterator *aIter;
   143302   int i;
   143303   int iCol;
   143304   int nToken = 0;
   143305 
   143306   /* Allocate and populate the array of LcsIterator objects. The array
   143307   ** contains one element for each matchable phrase in the query.
   143308   **/
   143309   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
   143310   if( !aIter ) return SQLITE_NOMEM;
   143311   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
   143312   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
   143313 
   143314   for(i=0; i<pInfo->nPhrase; i++){
   143315     LcsIterator *pIter = &aIter[i];
   143316     nToken -= pIter->pExpr->pPhrase->nToken;
   143317     pIter->iPosOffset = nToken;
   143318   }
   143319 
   143320   for(iCol=0; iCol<pInfo->nCol; iCol++){
   143321     int nLcs = 0;                 /* LCS value for this column */
   143322     int nLive = 0;                /* Number of iterators in aIter not at EOF */
   143323 
   143324     for(i=0; i<pInfo->nPhrase; i++){
   143325       int rc;
   143326       LcsIterator *pIt = &aIter[i];
   143327       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
   143328       if( rc!=SQLITE_OK ) return rc;
   143329       if( pIt->pRead ){
   143330         pIt->iPos = pIt->iPosOffset;
   143331         fts3LcsIteratorAdvance(&aIter[i]);
   143332         nLive++;
   143333       }
   143334     }
   143335 
   143336     while( nLive>0 ){
   143337       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
   143338       int nThisLcs = 0;           /* LCS for the current iterator positions */
   143339 
   143340       for(i=0; i<pInfo->nPhrase; i++){
   143341         LcsIterator *pIter = &aIter[i];
   143342         if( pIter->pRead==0 ){
   143343           /* This iterator is already at EOF for this column. */
   143344           nThisLcs = 0;
   143345         }else{
   143346           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
   143347             pAdv = pIter;
   143348           }
   143349           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
   143350             nThisLcs++;
   143351           }else{
   143352             nThisLcs = 1;
   143353           }
   143354           if( nThisLcs>nLcs ) nLcs = nThisLcs;
   143355         }
   143356       }
   143357       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
   143358     }
   143359 
   143360     pInfo->aMatchinfo[iCol] = nLcs;
   143361   }
   143362 
   143363   sqlite3_free(aIter);
   143364   return SQLITE_OK;
   143365 }
   143366 
   143367 /*
   143368 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
   143369 ** be returned by the matchinfo() function. Argument zArg contains the
   143370 ** format string passed as the second argument to matchinfo (or the
   143371 ** default value "pcx" if no second argument was specified). The format
   143372 ** string has already been validated and the pInfo->aMatchinfo[] array
   143373 ** is guaranteed to be large enough for the output.
   143374 **
   143375 ** If bGlobal is true, then populate all fields of the matchinfo() output.
   143376 ** If it is false, then assume that those fields that do not change between
   143377 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
   143378 ** have already been populated.
   143379 **
   143380 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   143381 ** occurs. If a value other than SQLITE_OK is returned, the state the
   143382 ** pInfo->aMatchinfo[] buffer is left in is undefined.
   143383 */
   143384 static int fts3MatchinfoValues(
   143385   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   143386   int bGlobal,                    /* True to grab the global stats */
   143387   MatchInfo *pInfo,               /* Matchinfo context object */
   143388   const char *zArg                /* Matchinfo format string */
   143389 ){
   143390   int rc = SQLITE_OK;
   143391   int i;
   143392   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143393   sqlite3_stmt *pSelect = 0;
   143394 
   143395   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
   143396 
   143397     switch( zArg[i] ){
   143398       case FTS3_MATCHINFO_NPHRASE:
   143399         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
   143400         break;
   143401 
   143402       case FTS3_MATCHINFO_NCOL:
   143403         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
   143404         break;
   143405 
   143406       case FTS3_MATCHINFO_NDOC:
   143407         if( bGlobal ){
   143408           sqlite3_int64 nDoc = 0;
   143409           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
   143410           pInfo->aMatchinfo[0] = (u32)nDoc;
   143411         }
   143412         break;
   143413 
   143414       case FTS3_MATCHINFO_AVGLENGTH:
   143415         if( bGlobal ){
   143416           sqlite3_int64 nDoc;     /* Number of rows in table */
   143417           const char *a;          /* Aggregate column length array */
   143418 
   143419           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
   143420           if( rc==SQLITE_OK ){
   143421             int iCol;
   143422             for(iCol=0; iCol<pInfo->nCol; iCol++){
   143423               u32 iVal;
   143424               sqlite3_int64 nToken;
   143425               a += sqlite3Fts3GetVarint(a, &nToken);
   143426               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
   143427               pInfo->aMatchinfo[iCol] = iVal;
   143428             }
   143429           }
   143430         }
   143431         break;
   143432 
   143433       case FTS3_MATCHINFO_LENGTH: {
   143434         sqlite3_stmt *pSelectDocsize = 0;
   143435         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
   143436         if( rc==SQLITE_OK ){
   143437           int iCol;
   143438           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
   143439           for(iCol=0; iCol<pInfo->nCol; iCol++){
   143440             sqlite3_int64 nToken;
   143441             a += sqlite3Fts3GetVarint(a, &nToken);
   143442             pInfo->aMatchinfo[iCol] = (u32)nToken;
   143443           }
   143444         }
   143445         sqlite3_reset(pSelectDocsize);
   143446         break;
   143447       }
   143448 
   143449       case FTS3_MATCHINFO_LCS:
   143450         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   143451         if( rc==SQLITE_OK ){
   143452           rc = fts3MatchinfoLcs(pCsr, pInfo);
   143453         }
   143454         break;
   143455 
   143456       default: {
   143457         Fts3Expr *pExpr;
   143458         assert( zArg[i]==FTS3_MATCHINFO_HITS );
   143459         pExpr = pCsr->pExpr;
   143460         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   143461         if( rc!=SQLITE_OK ) break;
   143462         if( bGlobal ){
   143463           if( pCsr->pDeferred ){
   143464             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
   143465             if( rc!=SQLITE_OK ) break;
   143466           }
   143467           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
   143468           if( rc!=SQLITE_OK ) break;
   143469         }
   143470         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
   143471         break;
   143472       }
   143473     }
   143474 
   143475     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
   143476   }
   143477 
   143478   sqlite3_reset(pSelect);
   143479   return rc;
   143480 }
   143481 
   143482 
   143483 /*
   143484 ** Populate pCsr->aMatchinfo[] with data for the current row. The
   143485 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
   143486 */
   143487 static int fts3GetMatchinfo(
   143488   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
   143489   const char *zArg                /* Second argument to matchinfo() function */
   143490 ){
   143491   MatchInfo sInfo;
   143492   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143493   int rc = SQLITE_OK;
   143494   int bGlobal = 0;                /* Collect 'global' stats as well as local */
   143495 
   143496   memset(&sInfo, 0, sizeof(MatchInfo));
   143497   sInfo.pCursor = pCsr;
   143498   sInfo.nCol = pTab->nColumn;
   143499 
   143500   /* If there is cached matchinfo() data, but the format string for the
   143501   ** cache does not match the format string for this request, discard
   143502   ** the cached data. */
   143503   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
   143504     assert( pCsr->aMatchinfo );
   143505     sqlite3_free(pCsr->aMatchinfo);
   143506     pCsr->zMatchinfo = 0;
   143507     pCsr->aMatchinfo = 0;
   143508   }
   143509 
   143510   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
   143511   ** matchinfo function has been called for this query. In this case
   143512   ** allocate the array used to accumulate the matchinfo data and
   143513   ** initialize those elements that are constant for every row.
   143514   */
   143515   if( pCsr->aMatchinfo==0 ){
   143516     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
   143517     int nArg;                     /* Bytes in zArg */
   143518     int i;                        /* Used to iterate through zArg */
   143519 
   143520     /* Determine the number of phrases in the query */
   143521     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
   143522     sInfo.nPhrase = pCsr->nPhrase;
   143523 
   143524     /* Determine the number of integers in the buffer returned by this call. */
   143525     for(i=0; zArg[i]; i++){
   143526       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
   143527     }
   143528 
   143529     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
   143530     nArg = (int)strlen(zArg);
   143531     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
   143532     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
   143533 
   143534     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
   143535     pCsr->nMatchinfo = nMatchinfo;
   143536     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
   143537     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
   143538     pCsr->isMatchinfoNeeded = 1;
   143539     bGlobal = 1;
   143540   }
   143541 
   143542   sInfo.aMatchinfo = pCsr->aMatchinfo;
   143543   sInfo.nPhrase = pCsr->nPhrase;
   143544   if( pCsr->isMatchinfoNeeded ){
   143545     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
   143546     pCsr->isMatchinfoNeeded = 0;
   143547   }
   143548 
   143549   return rc;
   143550 }
   143551 
   143552 /*
   143553 ** Implementation of snippet() function.
   143554 */
   143555 SQLITE_PRIVATE void sqlite3Fts3Snippet(
   143556   sqlite3_context *pCtx,          /* SQLite function call context */
   143557   Fts3Cursor *pCsr,               /* Cursor object */
   143558   const char *zStart,             /* Snippet start text - "<b>" */
   143559   const char *zEnd,               /* Snippet end text - "</b>" */
   143560   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
   143561   int iCol,                       /* Extract snippet from this column */
   143562   int nToken                      /* Approximate number of tokens in snippet */
   143563 ){
   143564   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143565   int rc = SQLITE_OK;
   143566   int i;
   143567   StrBuffer res = {0, 0, 0};
   143568 
   143569   /* The returned text includes up to four fragments of text extracted from
   143570   ** the data in the current row. The first iteration of the for(...) loop
   143571   ** below attempts to locate a single fragment of text nToken tokens in
   143572   ** size that contains at least one instance of all phrases in the query
   143573   ** expression that appear in the current row. If such a fragment of text
   143574   ** cannot be found, the second iteration of the loop attempts to locate
   143575   ** a pair of fragments, and so on.
   143576   */
   143577   int nSnippet = 0;               /* Number of fragments in this snippet */
   143578   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
   143579   int nFToken = -1;               /* Number of tokens in each fragment */
   143580 
   143581   if( !pCsr->pExpr ){
   143582     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   143583     return;
   143584   }
   143585 
   143586   for(nSnippet=1; 1; nSnippet++){
   143587 
   143588     int iSnip;                    /* Loop counter 0..nSnippet-1 */
   143589     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
   143590     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
   143591 
   143592     if( nToken>=0 ){
   143593       nFToken = (nToken+nSnippet-1) / nSnippet;
   143594     }else{
   143595       nFToken = -1 * nToken;
   143596     }
   143597 
   143598     for(iSnip=0; iSnip<nSnippet; iSnip++){
   143599       int iBestScore = -1;        /* Best score of columns checked so far */
   143600       int iRead;                  /* Used to iterate through columns */
   143601       SnippetFragment *pFragment = &aSnippet[iSnip];
   143602 
   143603       memset(pFragment, 0, sizeof(*pFragment));
   143604 
   143605       /* Loop through all columns of the table being considered for snippets.
   143606       ** If the iCol argument to this function was negative, this means all
   143607       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
   143608       */
   143609       for(iRead=0; iRead<pTab->nColumn; iRead++){
   143610         SnippetFragment sF = {0, 0, 0, 0};
   143611         int iS;
   143612         if( iCol>=0 && iRead!=iCol ) continue;
   143613 
   143614         /* Find the best snippet of nFToken tokens in column iRead. */
   143615         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
   143616         if( rc!=SQLITE_OK ){
   143617           goto snippet_out;
   143618         }
   143619         if( iS>iBestScore ){
   143620           *pFragment = sF;
   143621           iBestScore = iS;
   143622         }
   143623       }
   143624 
   143625       mCovered |= pFragment->covered;
   143626     }
   143627 
   143628     /* If all query phrases seen by fts3BestSnippet() are present in at least
   143629     ** one of the nSnippet snippet fragments, break out of the loop.
   143630     */
   143631     assert( (mCovered&mSeen)==mCovered );
   143632     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
   143633   }
   143634 
   143635   assert( nFToken>0 );
   143636 
   143637   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
   143638     rc = fts3SnippetText(pCsr, &aSnippet[i],
   143639         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
   143640     );
   143641   }
   143642 
   143643  snippet_out:
   143644   sqlite3Fts3SegmentsClose(pTab);
   143645   if( rc!=SQLITE_OK ){
   143646     sqlite3_result_error_code(pCtx, rc);
   143647     sqlite3_free(res.z);
   143648   }else{
   143649     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
   143650   }
   143651 }
   143652 
   143653 
   143654 typedef struct TermOffset TermOffset;
   143655 typedef struct TermOffsetCtx TermOffsetCtx;
   143656 
   143657 struct TermOffset {
   143658   char *pList;                    /* Position-list */
   143659   int iPos;                       /* Position just read from pList */
   143660   int iOff;                       /* Offset of this term from read positions */
   143661 };
   143662 
   143663 struct TermOffsetCtx {
   143664   Fts3Cursor *pCsr;
   143665   int iCol;                       /* Column of table to populate aTerm for */
   143666   int iTerm;
   143667   sqlite3_int64 iDocid;
   143668   TermOffset *aTerm;
   143669 };
   143670 
   143671 /*
   143672 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
   143673 */
   143674 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
   143675   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
   143676   int nTerm;                      /* Number of tokens in phrase */
   143677   int iTerm;                      /* For looping through nTerm phrase terms */
   143678   char *pList;                    /* Pointer to position list for phrase */
   143679   int iPos = 0;                   /* First position in position-list */
   143680   int rc;
   143681 
   143682   UNUSED_PARAMETER(iPhrase);
   143683   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
   143684   nTerm = pExpr->pPhrase->nToken;
   143685   if( pList ){
   143686     fts3GetDeltaPosition(&pList, &iPos);
   143687     assert( iPos>=0 );
   143688   }
   143689 
   143690   for(iTerm=0; iTerm<nTerm; iTerm++){
   143691     TermOffset *pT = &p->aTerm[p->iTerm++];
   143692     pT->iOff = nTerm-iTerm-1;
   143693     pT->pList = pList;
   143694     pT->iPos = iPos;
   143695   }
   143696 
   143697   return rc;
   143698 }
   143699 
   143700 /*
   143701 ** Implementation of offsets() function.
   143702 */
   143703 SQLITE_PRIVATE void sqlite3Fts3Offsets(
   143704   sqlite3_context *pCtx,          /* SQLite function call context */
   143705   Fts3Cursor *pCsr                /* Cursor object */
   143706 ){
   143707   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143708   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
   143709   int rc;                         /* Return Code */
   143710   int nToken;                     /* Number of tokens in query */
   143711   int iCol;                       /* Column currently being processed */
   143712   StrBuffer res = {0, 0, 0};      /* Result string */
   143713   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
   143714 
   143715   if( !pCsr->pExpr ){
   143716     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   143717     return;
   143718   }
   143719 
   143720   memset(&sCtx, 0, sizeof(sCtx));
   143721   assert( pCsr->isRequireSeek==0 );
   143722 
   143723   /* Count the number of terms in the query */
   143724   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
   143725   if( rc!=SQLITE_OK ) goto offsets_out;
   143726 
   143727   /* Allocate the array of TermOffset iterators. */
   143728   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
   143729   if( 0==sCtx.aTerm ){
   143730     rc = SQLITE_NOMEM;
   143731     goto offsets_out;
   143732   }
   143733   sCtx.iDocid = pCsr->iPrevId;
   143734   sCtx.pCsr = pCsr;
   143735 
   143736   /* Loop through the table columns, appending offset information to
   143737   ** string-buffer res for each column.
   143738   */
   143739   for(iCol=0; iCol<pTab->nColumn; iCol++){
   143740     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
   143741     const char *ZDUMMY;           /* Dummy argument used with xNext() */
   143742     int NDUMMY = 0;               /* Dummy argument used with xNext() */
   143743     int iStart = 0;
   143744     int iEnd = 0;
   143745     int iCurrent = 0;
   143746     const char *zDoc;
   143747     int nDoc;
   143748 
   143749     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
   143750     ** no way that this operation can fail, so the return code from
   143751     ** fts3ExprIterate() can be discarded.
   143752     */
   143753     sCtx.iCol = iCol;
   143754     sCtx.iTerm = 0;
   143755     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
   143756 
   143757     /* Retreive the text stored in column iCol. If an SQL NULL is stored
   143758     ** in column iCol, jump immediately to the next iteration of the loop.
   143759     ** If an OOM occurs while retrieving the data (this can happen if SQLite
   143760     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
   143761     ** to the caller.
   143762     */
   143763     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
   143764     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
   143765     if( zDoc==0 ){
   143766       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
   143767         continue;
   143768       }
   143769       rc = SQLITE_NOMEM;
   143770       goto offsets_out;
   143771     }
   143772 
   143773     /* Initialize a tokenizer iterator to iterate through column iCol. */
   143774     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
   143775         zDoc, nDoc, &pC
   143776     );
   143777     if( rc!=SQLITE_OK ) goto offsets_out;
   143778 
   143779     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   143780     while( rc==SQLITE_OK ){
   143781       int i;                      /* Used to loop through terms */
   143782       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
   143783       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
   143784 
   143785       for(i=0; i<nToken; i++){
   143786         TermOffset *pT = &sCtx.aTerm[i];
   143787         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
   143788           iMinPos = pT->iPos-pT->iOff;
   143789           pTerm = pT;
   143790         }
   143791       }
   143792 
   143793       if( !pTerm ){
   143794         /* All offsets for this column have been gathered. */
   143795         rc = SQLITE_DONE;
   143796       }else{
   143797         assert( iCurrent<=iMinPos );
   143798         if( 0==(0xFE&*pTerm->pList) ){
   143799           pTerm->pList = 0;
   143800         }else{
   143801           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
   143802         }
   143803         while( rc==SQLITE_OK && iCurrent<iMinPos ){
   143804           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   143805         }
   143806         if( rc==SQLITE_OK ){
   143807           char aBuffer[64];
   143808           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
   143809               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
   143810           );
   143811           rc = fts3StringAppend(&res, aBuffer, -1);
   143812         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
   143813           rc = FTS_CORRUPT_VTAB;
   143814         }
   143815       }
   143816     }
   143817     if( rc==SQLITE_DONE ){
   143818       rc = SQLITE_OK;
   143819     }
   143820 
   143821     pMod->xClose(pC);
   143822     if( rc!=SQLITE_OK ) goto offsets_out;
   143823   }
   143824 
   143825  offsets_out:
   143826   sqlite3_free(sCtx.aTerm);
   143827   assert( rc!=SQLITE_DONE );
   143828   sqlite3Fts3SegmentsClose(pTab);
   143829   if( rc!=SQLITE_OK ){
   143830     sqlite3_result_error_code(pCtx,  rc);
   143831     sqlite3_free(res.z);
   143832   }else{
   143833     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
   143834   }
   143835   return;
   143836 }
   143837 
   143838 /*
   143839 ** Implementation of matchinfo() function.
   143840 */
   143841 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
   143842   sqlite3_context *pContext,      /* Function call context */
   143843   Fts3Cursor *pCsr,               /* FTS3 table cursor */
   143844   const char *zArg                /* Second arg to matchinfo() function */
   143845 ){
   143846   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   143847   int rc;
   143848   int i;
   143849   const char *zFormat;
   143850 
   143851   if( zArg ){
   143852     for(i=0; zArg[i]; i++){
   143853       char *zErr = 0;
   143854       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
   143855         sqlite3_result_error(pContext, zErr, -1);
   143856         sqlite3_free(zErr);
   143857         return;
   143858       }
   143859     }
   143860     zFormat = zArg;
   143861   }else{
   143862     zFormat = FTS3_MATCHINFO_DEFAULT;
   143863   }
   143864 
   143865   if( !pCsr->pExpr ){
   143866     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
   143867     return;
   143868   }
   143869 
   143870   /* Retrieve matchinfo() data. */
   143871   rc = fts3GetMatchinfo(pCsr, zFormat);
   143872   sqlite3Fts3SegmentsClose(pTab);
   143873 
   143874   if( rc!=SQLITE_OK ){
   143875     sqlite3_result_error_code(pContext, rc);
   143876   }else{
   143877     int n = pCsr->nMatchinfo * sizeof(u32);
   143878     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
   143879   }
   143880 }
   143881 
   143882 #endif
   143883 
   143884 /************** End of fts3_snippet.c ****************************************/
   143885 /************** Begin file fts3_unicode.c ************************************/
   143886 /*
   143887 ** 2012 May 24
   143888 **
   143889 ** The author disclaims copyright to this source code.  In place of
   143890 ** a legal notice, here is a blessing:
   143891 **
   143892 **    May you do good and not evil.
   143893 **    May you find forgiveness for yourself and forgive others.
   143894 **    May you share freely, never taking more than you give.
   143895 **
   143896 ******************************************************************************
   143897 **
   143898 ** Implementation of the "unicode" full-text-search tokenizer.
   143899 */
   143900 
   143901 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   143902 
   143903 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   143904 
   143905 /* #include <assert.h> */
   143906 /* #include <stdlib.h> */
   143907 /* #include <stdio.h> */
   143908 /* #include <string.h> */
   143909 
   143910 
   143911 /*
   143912 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
   143913 ** from the sqlite3 source file utf.c. If this file is compiled as part
   143914 ** of the amalgamation, they are not required.
   143915 */
   143916 #ifndef SQLITE_AMALGAMATION
   143917 
   143918 static const unsigned char sqlite3Utf8Trans1[] = {
   143919   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   143920   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   143921   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   143922   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   143923   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   143924   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   143925   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   143926   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   143927 };
   143928 
   143929 #define READ_UTF8(zIn, zTerm, c)                           \
   143930   c = *(zIn++);                                            \
   143931   if( c>=0xc0 ){                                           \
   143932     c = sqlite3Utf8Trans1[c-0xc0];                         \
   143933     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   143934       c = (c<<6) + (0x3f & *(zIn++));                      \
   143935     }                                                      \
   143936     if( c<0x80                                             \
   143937         || (c&0xFFFFF800)==0xD800                          \
   143938         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   143939   }
   143940 
   143941 #define WRITE_UTF8(zOut, c) {                          \
   143942   if( c<0x00080 ){                                     \
   143943     *zOut++ = (u8)(c&0xFF);                            \
   143944   }                                                    \
   143945   else if( c<0x00800 ){                                \
   143946     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
   143947     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   143948   }                                                    \
   143949   else if( c<0x10000 ){                                \
   143950     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
   143951     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   143952     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   143953   }else{                                               \
   143954     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
   143955     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
   143956     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   143957     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   143958   }                                                    \
   143959 }
   143960 
   143961 #endif /* ifndef SQLITE_AMALGAMATION */
   143962 
   143963 typedef struct unicode_tokenizer unicode_tokenizer;
   143964 typedef struct unicode_cursor unicode_cursor;
   143965 
   143966 struct unicode_tokenizer {
   143967   sqlite3_tokenizer base;
   143968   int bRemoveDiacritic;
   143969   int nException;
   143970   int *aiException;
   143971 };
   143972 
   143973 struct unicode_cursor {
   143974   sqlite3_tokenizer_cursor base;
   143975   const unsigned char *aInput;    /* Input text being tokenized */
   143976   int nInput;                     /* Size of aInput[] in bytes */
   143977   int iOff;                       /* Current offset within aInput[] */
   143978   int iToken;                     /* Index of next token to be returned */
   143979   char *zToken;                   /* storage for current token */
   143980   int nAlloc;                     /* space allocated at zToken */
   143981 };
   143982 
   143983 
   143984 /*
   143985 ** Destroy a tokenizer allocated by unicodeCreate().
   143986 */
   143987 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
   143988   if( pTokenizer ){
   143989     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
   143990     sqlite3_free(p->aiException);
   143991     sqlite3_free(p);
   143992   }
   143993   return SQLITE_OK;
   143994 }
   143995 
   143996 /*
   143997 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
   143998 ** statement has specified that the tokenizer for this table shall consider
   143999 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
   144000 ** token characters (if bAlnum==1).
   144001 **
   144002 ** For each codepoint in the zIn/nIn string, this function checks if the
   144003 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
   144004 ** If so, no action is taken. Otherwise, the codepoint is added to the
   144005 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
   144006 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
   144007 ** codepoints in the aiException[] array.
   144008 **
   144009 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
   144010 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
   144011 ** It is not possible to change the behavior of the tokenizer with respect
   144012 ** to these codepoints.
   144013 */
   144014 static int unicodeAddExceptions(
   144015   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
   144016   int bAlnum,                     /* Replace Isalnum() return value with this */
   144017   const char *zIn,                /* Array of characters to make exceptions */
   144018   int nIn                         /* Length of z in bytes */
   144019 ){
   144020   const unsigned char *z = (const unsigned char *)zIn;
   144021   const unsigned char *zTerm = &z[nIn];
   144022   int iCode;
   144023   int nEntry = 0;
   144024 
   144025   assert( bAlnum==0 || bAlnum==1 );
   144026 
   144027   while( z<zTerm ){
   144028     READ_UTF8(z, zTerm, iCode);
   144029     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
   144030     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
   144031      && sqlite3FtsUnicodeIsdiacritic(iCode)==0
   144032     ){
   144033       nEntry++;
   144034     }
   144035   }
   144036 
   144037   if( nEntry ){
   144038     int *aNew;                    /* New aiException[] array */
   144039     int nNew;                     /* Number of valid entries in array aNew[] */
   144040 
   144041     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
   144042     if( aNew==0 ) return SQLITE_NOMEM;
   144043     nNew = p->nException;
   144044 
   144045     z = (const unsigned char *)zIn;
   144046     while( z<zTerm ){
   144047       READ_UTF8(z, zTerm, iCode);
   144048       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
   144049        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
   144050       ){
   144051         int i, j;
   144052         for(i=0; i<nNew && aNew[i]<iCode; i++);
   144053         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
   144054         aNew[i] = iCode;
   144055         nNew++;
   144056       }
   144057     }
   144058     p->aiException = aNew;
   144059     p->nException = nNew;
   144060   }
   144061 
   144062   return SQLITE_OK;
   144063 }
   144064 
   144065 /*
   144066 ** Return true if the p->aiException[] array contains the value iCode.
   144067 */
   144068 static int unicodeIsException(unicode_tokenizer *p, int iCode){
   144069   if( p->nException>0 ){
   144070     int *a = p->aiException;
   144071     int iLo = 0;
   144072     int iHi = p->nException-1;
   144073 
   144074     while( iHi>=iLo ){
   144075       int iTest = (iHi + iLo) / 2;
   144076       if( iCode==a[iTest] ){
   144077         return 1;
   144078       }else if( iCode>a[iTest] ){
   144079         iLo = iTest+1;
   144080       }else{
   144081         iHi = iTest-1;
   144082       }
   144083     }
   144084   }
   144085 
   144086   return 0;
   144087 }
   144088 
   144089 /*
   144090 ** Return true if, for the purposes of tokenization, codepoint iCode is
   144091 ** considered a token character (not a separator).
   144092 */
   144093 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
   144094   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
   144095   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
   144096 }
   144097 
   144098 /*
   144099 ** Create a new tokenizer instance.
   144100 */
   144101 static int unicodeCreate(
   144102   int nArg,                       /* Size of array argv[] */
   144103   const char * const *azArg,      /* Tokenizer creation arguments */
   144104   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
   144105 ){
   144106   unicode_tokenizer *pNew;        /* New tokenizer object */
   144107   int i;
   144108   int rc = SQLITE_OK;
   144109 
   144110   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
   144111   if( pNew==NULL ) return SQLITE_NOMEM;
   144112   memset(pNew, 0, sizeof(unicode_tokenizer));
   144113   pNew->bRemoveDiacritic = 1;
   144114 
   144115   for(i=0; rc==SQLITE_OK && i<nArg; i++){
   144116     const char *z = azArg[i];
   144117     int n = (int)strlen(z);
   144118 
   144119     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
   144120       pNew->bRemoveDiacritic = 1;
   144121     }
   144122     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
   144123       pNew->bRemoveDiacritic = 0;
   144124     }
   144125     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
   144126       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
   144127     }
   144128     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
   144129       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
   144130     }
   144131     else{
   144132       /* Unrecognized argument */
   144133       rc  = SQLITE_ERROR;
   144134     }
   144135   }
   144136 
   144137   if( rc!=SQLITE_OK ){
   144138     unicodeDestroy((sqlite3_tokenizer *)pNew);
   144139     pNew = 0;
   144140   }
   144141   *pp = (sqlite3_tokenizer *)pNew;
   144142   return rc;
   144143 }
   144144 
   144145 /*
   144146 ** Prepare to begin tokenizing a particular string.  The input
   144147 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   144148 ** used to incrementally tokenize this string is returned in
   144149 ** *ppCursor.
   144150 */
   144151 static int unicodeOpen(
   144152   sqlite3_tokenizer *p,           /* The tokenizer */
   144153   const char *aInput,             /* Input string */
   144154   int nInput,                     /* Size of string aInput in bytes */
   144155   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
   144156 ){
   144157   unicode_cursor *pCsr;
   144158 
   144159   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
   144160   if( pCsr==0 ){
   144161     return SQLITE_NOMEM;
   144162   }
   144163   memset(pCsr, 0, sizeof(unicode_cursor));
   144164 
   144165   pCsr->aInput = (const unsigned char *)aInput;
   144166   if( aInput==0 ){
   144167     pCsr->nInput = 0;
   144168   }else if( nInput<0 ){
   144169     pCsr->nInput = (int)strlen(aInput);
   144170   }else{
   144171     pCsr->nInput = nInput;
   144172   }
   144173 
   144174   *pp = &pCsr->base;
   144175   UNUSED_PARAMETER(p);
   144176   return SQLITE_OK;
   144177 }
   144178 
   144179 /*
   144180 ** Close a tokenization cursor previously opened by a call to
   144181 ** simpleOpen() above.
   144182 */
   144183 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
   144184   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
   144185   sqlite3_free(pCsr->zToken);
   144186   sqlite3_free(pCsr);
   144187   return SQLITE_OK;
   144188 }
   144189 
   144190 /*
   144191 ** Extract the next token from a tokenization cursor.  The cursor must
   144192 ** have been opened by a prior call to simpleOpen().
   144193 */
   144194 static int unicodeNext(
   144195   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
   144196   const char **paToken,           /* OUT: Token text */
   144197   int *pnToken,                   /* OUT: Number of bytes at *paToken */
   144198   int *piStart,                   /* OUT: Starting offset of token */
   144199   int *piEnd,                     /* OUT: Ending offset of token */
   144200   int *piPos                      /* OUT: Position integer of token */
   144201 ){
   144202   unicode_cursor *pCsr = (unicode_cursor *)pC;
   144203   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
   144204   int iCode = 0;
   144205   char *zOut;
   144206   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
   144207   const unsigned char *zStart = z;
   144208   const unsigned char *zEnd;
   144209   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
   144210 
   144211   /* Scan past any delimiter characters before the start of the next token.
   144212   ** Return SQLITE_DONE early if this takes us all the way to the end of
   144213   ** the input.  */
   144214   while( z<zTerm ){
   144215     READ_UTF8(z, zTerm, iCode);
   144216     if( unicodeIsAlnum(p, iCode) ) break;
   144217     zStart = z;
   144218   }
   144219   if( zStart>=zTerm ) return SQLITE_DONE;
   144220 
   144221   zOut = pCsr->zToken;
   144222   do {
   144223     int iOut;
   144224 
   144225     /* Grow the output buffer if required. */
   144226     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
   144227       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
   144228       if( !zNew ) return SQLITE_NOMEM;
   144229       zOut = &zNew[zOut - pCsr->zToken];
   144230       pCsr->zToken = zNew;
   144231       pCsr->nAlloc += 64;
   144232     }
   144233 
   144234     /* Write the folded case of the last character read to the output */
   144235     zEnd = z;
   144236     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
   144237     if( iOut ){
   144238       WRITE_UTF8(zOut, iOut);
   144239     }
   144240 
   144241     /* If the cursor is not at EOF, read the next character */
   144242     if( z>=zTerm ) break;
   144243     READ_UTF8(z, zTerm, iCode);
   144244   }while( unicodeIsAlnum(p, iCode)
   144245        || sqlite3FtsUnicodeIsdiacritic(iCode)
   144246   );
   144247 
   144248   /* Set the output variables and return. */
   144249   pCsr->iOff = (int)(z - pCsr->aInput);
   144250   *paToken = pCsr->zToken;
   144251   *pnToken = (int)(zOut - pCsr->zToken);
   144252   *piStart = (int)(zStart - pCsr->aInput);
   144253   *piEnd = (int)(zEnd - pCsr->aInput);
   144254   *piPos = pCsr->iToken++;
   144255   return SQLITE_OK;
   144256 }
   144257 
   144258 /*
   144259 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
   144260 ** structure for the unicode tokenizer.
   144261 */
   144262 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
   144263   static const sqlite3_tokenizer_module module = {
   144264     0,
   144265     unicodeCreate,
   144266     unicodeDestroy,
   144267     unicodeOpen,
   144268     unicodeClose,
   144269     unicodeNext,
   144270     0,
   144271   };
   144272   *ppModule = &module;
   144273 }
   144274 
   144275 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   144276 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
   144277 
   144278 /************** End of fts3_unicode.c ****************************************/
   144279 /************** Begin file fts3_unicode2.c ***********************************/
   144280 /*
   144281 ** 2012 May 25
   144282 **
   144283 ** The author disclaims copyright to this source code.  In place of
   144284 ** a legal notice, here is a blessing:
   144285 **
   144286 **    May you do good and not evil.
   144287 **    May you find forgiveness for yourself and forgive others.
   144288 **    May you share freely, never taking more than you give.
   144289 **
   144290 ******************************************************************************
   144291 */
   144292 
   144293 /*
   144294 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
   144295 */
   144296 
   144297 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   144298 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
   144299 
   144300 /* #include <assert.h> */
   144301 
   144302 /*
   144303 ** Return true if the argument corresponds to a unicode codepoint
   144304 ** classified as either a letter or a number. Otherwise false.
   144305 **
   144306 ** The results are undefined if the value passed to this function
   144307 ** is less than zero.
   144308 */
   144309 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
   144310   /* Each unsigned integer in the following array corresponds to a contiguous
   144311   ** range of unicode codepoints that are not either letters or numbers (i.e.
   144312   ** codepoints for which this function should return 0).
   144313   **
   144314   ** The most significant 22 bits in each 32-bit value contain the first
   144315   ** codepoint in the range. The least significant 10 bits are used to store
   144316   ** the size of the range (always at least 1). In other words, the value
   144317   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
   144318   ** C. It is not possible to represent a range larger than 1023 codepoints
   144319   ** using this format.
   144320   */
   144321   static const unsigned int aEntry[] = {
   144322     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
   144323     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
   144324     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
   144325     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
   144326     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
   144327     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
   144328     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
   144329     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
   144330     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
   144331     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
   144332     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
   144333     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
   144334     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
   144335     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
   144336     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
   144337     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
   144338     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
   144339     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
   144340     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
   144341     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
   144342     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
   144343     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
   144344     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
   144345     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
   144346     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
   144347     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
   144348     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
   144349     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
   144350     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
   144351     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
   144352     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
   144353     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
   144354     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
   144355     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
   144356     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
   144357     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
   144358     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
   144359     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
   144360     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
   144361     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
   144362     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
   144363     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
   144364     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
   144365     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
   144366     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
   144367     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
   144368     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
   144369     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
   144370     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
   144371     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
   144372     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
   144373     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
   144374     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
   144375     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
   144376     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
   144377     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
   144378     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
   144379     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
   144380     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
   144381     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
   144382     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
   144383     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
   144384     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
   144385     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
   144386     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
   144387     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
   144388     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
   144389     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
   144390     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
   144391     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
   144392     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
   144393     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
   144394     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
   144395     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
   144396     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
   144397     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
   144398     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
   144399     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
   144400     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
   144401     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
   144402     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
   144403     0x380400F0,
   144404   };
   144405   static const unsigned int aAscii[4] = {
   144406     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
   144407   };
   144408 
   144409   if( c<128 ){
   144410     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
   144411   }else if( c<(1<<22) ){
   144412     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
   144413     int iRes = 0;
   144414     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   144415     int iLo = 0;
   144416     while( iHi>=iLo ){
   144417       int iTest = (iHi + iLo) / 2;
   144418       if( key >= aEntry[iTest] ){
   144419         iRes = iTest;
   144420         iLo = iTest+1;
   144421       }else{
   144422         iHi = iTest-1;
   144423       }
   144424     }
   144425     assert( aEntry[0]<key );
   144426     assert( key>=aEntry[iRes] );
   144427     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
   144428   }
   144429   return 1;
   144430 }
   144431 
   144432 
   144433 /*
   144434 ** If the argument is a codepoint corresponding to a lowercase letter
   144435 ** in the ASCII range with a diacritic added, return the codepoint
   144436 ** of the ASCII letter only. For example, if passed 235 - "LATIN
   144437 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
   144438 ** E"). The resuls of passing a codepoint that corresponds to an
   144439 ** uppercase letter are undefined.
   144440 */
   144441 static int remove_diacritic(int c){
   144442   unsigned short aDia[] = {
   144443         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
   144444      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
   144445      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
   144446      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
   144447      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
   144448      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
   144449      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
   144450      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
   144451     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
   144452     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
   144453     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
   144454     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
   144455     62924, 63050, 63082, 63274, 63390,
   144456   };
   144457   char aChar[] = {
   144458     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
   144459     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
   144460     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
   144461     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
   144462     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
   144463     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
   144464     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
   144465     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
   144466     'e',  'i',  'o',  'u',  'y',
   144467   };
   144468 
   144469   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
   144470   int iRes = 0;
   144471   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
   144472   int iLo = 0;
   144473   while( iHi>=iLo ){
   144474     int iTest = (iHi + iLo) / 2;
   144475     if( key >= aDia[iTest] ){
   144476       iRes = iTest;
   144477       iLo = iTest+1;
   144478     }else{
   144479       iHi = iTest-1;
   144480     }
   144481   }
   144482   assert( key>=aDia[iRes] );
   144483   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
   144484 }
   144485 
   144486 
   144487 /*
   144488 ** Return true if the argument interpreted as a unicode codepoint
   144489 ** is a diacritical modifier character.
   144490 */
   144491 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
   144492   unsigned int mask0 = 0x08029FDF;
   144493   unsigned int mask1 = 0x000361F8;
   144494   if( c<768 || c>817 ) return 0;
   144495   return (c < 768+32) ?
   144496       (mask0 & (1 << (c-768))) :
   144497       (mask1 & (1 << (c-768-32)));
   144498 }
   144499 
   144500 
   144501 /*
   144502 ** Interpret the argument as a unicode codepoint. If the codepoint
   144503 ** is an upper case character that has a lower case equivalent,
   144504 ** return the codepoint corresponding to the lower case version.
   144505 ** Otherwise, return a copy of the argument.
   144506 **
   144507 ** The results are undefined if the value passed to this function
   144508 ** is less than zero.
   144509 */
   144510 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
   144511   /* Each entry in the following array defines a rule for folding a range
   144512   ** of codepoints to lower case. The rule applies to a range of nRange
   144513   ** codepoints starting at codepoint iCode.
   144514   **
   144515   ** If the least significant bit in flags is clear, then the rule applies
   144516   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
   144517   ** need to be folded). Or, if it is set, then the rule only applies to
   144518   ** every second codepoint in the range, starting with codepoint C.
   144519   **
   144520   ** The 7 most significant bits in flags are an index into the aiOff[]
   144521   ** array. If a specific codepoint C does require folding, then its lower
   144522   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
   144523   **
   144524   ** The contents of this array are generated by parsing the CaseFolding.txt
   144525   ** file distributed as part of the "Unicode Character Database". See
   144526   ** http://www.unicode.org for details.
   144527   */
   144528   static const struct TableEntry {
   144529     unsigned short iCode;
   144530     unsigned char flags;
   144531     unsigned char nRange;
   144532   } aEntry[] = {
   144533     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
   144534     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
   144535     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
   144536     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
   144537     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
   144538     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
   144539     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
   144540     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
   144541     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
   144542     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
   144543     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
   144544     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
   144545     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
   144546     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
   144547     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
   144548     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
   144549     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
   144550     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
   144551     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
   144552     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
   144553     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
   144554     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
   144555     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
   144556     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
   144557     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
   144558     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
   144559     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
   144560     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
   144561     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
   144562     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
   144563     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
   144564     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
   144565     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
   144566     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
   144567     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
   144568     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
   144569     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
   144570     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
   144571     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
   144572     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
   144573     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
   144574     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
   144575     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
   144576     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
   144577     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
   144578     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
   144579     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
   144580     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
   144581     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
   144582     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
   144583     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
   144584     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
   144585     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
   144586     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
   144587     {65313, 14, 26},
   144588   };
   144589   static const unsigned short aiOff[] = {
   144590    1,     2,     8,     15,    16,    26,    28,    32,
   144591    37,    38,    40,    48,    63,    64,    69,    71,
   144592    79,    80,    116,   202,   203,   205,   206,   207,
   144593    209,   210,   211,   213,   214,   217,   218,   219,
   144594    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
   144595    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
   144596    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
   144597    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
   144598    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
   144599    65514, 65521, 65527, 65528, 65529,
   144600   };
   144601 
   144602   int ret = c;
   144603 
   144604   assert( c>=0 );
   144605   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
   144606 
   144607   if( c<128 ){
   144608     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
   144609   }else if( c<65536 ){
   144610     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   144611     int iLo = 0;
   144612     int iRes = -1;
   144613 
   144614     while( iHi>=iLo ){
   144615       int iTest = (iHi + iLo) / 2;
   144616       int cmp = (c - aEntry[iTest].iCode);
   144617       if( cmp>=0 ){
   144618         iRes = iTest;
   144619         iLo = iTest+1;
   144620       }else{
   144621         iHi = iTest-1;
   144622       }
   144623     }
   144624     assert( iRes<0 || c>=aEntry[iRes].iCode );
   144625 
   144626     if( iRes>=0 ){
   144627       const struct TableEntry *p = &aEntry[iRes];
   144628       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
   144629         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
   144630         assert( ret>0 );
   144631       }
   144632     }
   144633 
   144634     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
   144635   }
   144636 
   144637   else if( c>=66560 && c<66600 ){
   144638     ret = c + 40;
   144639   }
   144640 
   144641   return ret;
   144642 }
   144643 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
   144644 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
   144645 
   144646 /************** End of fts3_unicode2.c ***************************************/
   144647 /************** Begin file rtree.c *******************************************/
   144648 /*
   144649 ** 2001 September 15
   144650 **
   144651 ** The author disclaims copyright to this source code.  In place of
   144652 ** a legal notice, here is a blessing:
   144653 **
   144654 **    May you do good and not evil.
   144655 **    May you find forgiveness for yourself and forgive others.
   144656 **    May you share freely, never taking more than you give.
   144657 **
   144658 *************************************************************************
   144659 ** This file contains code for implementations of the r-tree and r*-tree
   144660 ** algorithms packaged as an SQLite virtual table module.
   144661 */
   144662 
   144663 /*
   144664 ** Database Format of R-Tree Tables
   144665 ** --------------------------------
   144666 **
   144667 ** The data structure for a single virtual r-tree table is stored in three
   144668 ** native SQLite tables declared as follows. In each case, the '%' character
   144669 ** in the table name is replaced with the user-supplied name of the r-tree
   144670 ** table.
   144671 **
   144672 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
   144673 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
   144674 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
   144675 **
   144676 ** The data for each node of the r-tree structure is stored in the %_node
   144677 ** table. For each node that is not the root node of the r-tree, there is
   144678 ** an entry in the %_parent table associating the node with its parent.
   144679 ** And for each row of data in the table, there is an entry in the %_rowid
   144680 ** table that maps from the entries rowid to the id of the node that it
   144681 ** is stored on.
   144682 **
   144683 ** The root node of an r-tree always exists, even if the r-tree table is
   144684 ** empty. The nodeno of the root node is always 1. All other nodes in the
   144685 ** table must be the same size as the root node. The content of each node
   144686 ** is formatted as follows:
   144687 **
   144688 **   1. If the node is the root node (node 1), then the first 2 bytes
   144689 **      of the node contain the tree depth as a big-endian integer.
   144690 **      For non-root nodes, the first 2 bytes are left unused.
   144691 **
   144692 **   2. The next 2 bytes contain the number of entries currently
   144693 **      stored in the node.
   144694 **
   144695 **   3. The remainder of the node contains the node entries. Each entry
   144696 **      consists of a single 8-byte integer followed by an even number
   144697 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
   144698 **      of a record. For internal nodes it is the node number of a
   144699 **      child page.
   144700 */
   144701 
   144702 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
   144703 
   144704 #ifndef SQLITE_CORE
   144705   SQLITE_EXTENSION_INIT1
   144706 #else
   144707 #endif
   144708 
   144709 /* #include <string.h> */
   144710 /* #include <assert.h> */
   144711 /* #include <stdio.h> */
   144712 
   144713 #ifndef SQLITE_AMALGAMATION
   144714 #include "sqlite3rtree.h"
   144715 typedef sqlite3_int64 i64;
   144716 typedef unsigned char u8;
   144717 typedef unsigned short u16;
   144718 typedef unsigned int u32;
   144719 #endif
   144720 
   144721 /*  The following macro is used to suppress compiler warnings.
   144722 */
   144723 #ifndef UNUSED_PARAMETER
   144724 # define UNUSED_PARAMETER(x) (void)(x)
   144725 #endif
   144726 
   144727 typedef struct Rtree Rtree;
   144728 typedef struct RtreeCursor RtreeCursor;
   144729 typedef struct RtreeNode RtreeNode;
   144730 typedef struct RtreeCell RtreeCell;
   144731 typedef struct RtreeConstraint RtreeConstraint;
   144732 typedef struct RtreeMatchArg RtreeMatchArg;
   144733 typedef struct RtreeGeomCallback RtreeGeomCallback;
   144734 typedef union RtreeCoord RtreeCoord;
   144735 typedef struct RtreeSearchPoint RtreeSearchPoint;
   144736 
   144737 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
   144738 #define RTREE_MAX_DIMENSIONS 5
   144739 
   144740 /* Size of hash table Rtree.aHash. This hash table is not expected to
   144741 ** ever contain very many entries, so a fixed number of buckets is
   144742 ** used.
   144743 */
   144744 #define HASHSIZE 97
   144745 
   144746 /* The xBestIndex method of this virtual table requires an estimate of
   144747 ** the number of rows in the virtual table to calculate the costs of
   144748 ** various strategies. If possible, this estimate is loaded from the
   144749 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
   144750 ** Otherwise, if no sqlite_stat1 entry is available, use
   144751 ** RTREE_DEFAULT_ROWEST.
   144752 */
   144753 #define RTREE_DEFAULT_ROWEST 1048576
   144754 #define RTREE_MIN_ROWEST         100
   144755 
   144756 /*
   144757 ** An rtree virtual-table object.
   144758 */
   144759 struct Rtree {
   144760   sqlite3_vtab base;          /* Base class.  Must be first */
   144761   sqlite3 *db;                /* Host database connection */
   144762   int iNodeSize;              /* Size in bytes of each node in the node table */
   144763   u8 nDim;                    /* Number of dimensions */
   144764   u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
   144765   u8 nBytesPerCell;           /* Bytes consumed per cell */
   144766   int iDepth;                 /* Current depth of the r-tree structure */
   144767   char *zDb;                  /* Name of database containing r-tree table */
   144768   char *zName;                /* Name of r-tree table */
   144769   int nBusy;                  /* Current number of users of this structure */
   144770   i64 nRowEst;                /* Estimated number of rows in this table */
   144771 
   144772   /* List of nodes removed during a CondenseTree operation. List is
   144773   ** linked together via the pointer normally used for hash chains -
   144774   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
   144775   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
   144776   */
   144777   RtreeNode *pDeleted;
   144778   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
   144779 
   144780   /* Statements to read/write/delete a record from xxx_node */
   144781   sqlite3_stmt *pReadNode;
   144782   sqlite3_stmt *pWriteNode;
   144783   sqlite3_stmt *pDeleteNode;
   144784 
   144785   /* Statements to read/write/delete a record from xxx_rowid */
   144786   sqlite3_stmt *pReadRowid;
   144787   sqlite3_stmt *pWriteRowid;
   144788   sqlite3_stmt *pDeleteRowid;
   144789 
   144790   /* Statements to read/write/delete a record from xxx_parent */
   144791   sqlite3_stmt *pReadParent;
   144792   sqlite3_stmt *pWriteParent;
   144793   sqlite3_stmt *pDeleteParent;
   144794 
   144795   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
   144796 };
   144797 
   144798 /* Possible values for Rtree.eCoordType: */
   144799 #define RTREE_COORD_REAL32 0
   144800 #define RTREE_COORD_INT32  1
   144801 
   144802 /*
   144803 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
   144804 ** only deal with integer coordinates.  No floating point operations
   144805 ** will be done.
   144806 */
   144807 #ifdef SQLITE_RTREE_INT_ONLY
   144808   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
   144809   typedef int RtreeValue;                  /* Low accuracy coordinate */
   144810 # define RTREE_ZERO 0
   144811 #else
   144812   typedef double RtreeDValue;              /* High accuracy coordinate */
   144813   typedef float RtreeValue;                /* Low accuracy coordinate */
   144814 # define RTREE_ZERO 0.0
   144815 #endif
   144816 
   144817 /*
   144818 ** When doing a search of an r-tree, instances of the following structure
   144819 ** record intermediate results from the tree walk.
   144820 **
   144821 ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
   144822 ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
   144823 ** the id is of the parent node and the cell that RtreeSearchPoint
   144824 ** represents is the iCell-th entry in the parent node.
   144825 */
   144826 struct RtreeSearchPoint {
   144827   RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
   144828   sqlite3_int64 id;      /* Node ID */
   144829   u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
   144830   u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
   144831   u8 iCell;              /* Cell index within the node */
   144832 };
   144833 
   144834 /*
   144835 ** The minimum number of cells allowed for a node is a third of the
   144836 ** maximum. In Gutman's notation:
   144837 **
   144838 **     m = M/3
   144839 **
   144840 ** If an R*-tree "Reinsert" operation is required, the same number of
   144841 ** cells are removed from the overfull node and reinserted into the tree.
   144842 */
   144843 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
   144844 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
   144845 #define RTREE_MAXCELLS 51
   144846 
   144847 /*
   144848 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
   144849 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
   144850 ** Therefore all non-root nodes must contain at least 3 entries. Since
   144851 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
   144852 ** 40 or less.
   144853 */
   144854 #define RTREE_MAX_DEPTH 40
   144855 
   144856 
   144857 /*
   144858 ** Number of entries in the cursor RtreeNode cache.  The first entry is
   144859 ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
   144860 ** entries cache the RtreeNode for the first elements of the priority queue.
   144861 */
   144862 #define RTREE_CACHE_SZ  5
   144863 
   144864 /*
   144865 ** An rtree cursor object.
   144866 */
   144867 struct RtreeCursor {
   144868   sqlite3_vtab_cursor base;         /* Base class.  Must be first */
   144869   u8 atEOF;                         /* True if at end of search */
   144870   u8 bPoint;                        /* True if sPoint is valid */
   144871   int iStrategy;                    /* Copy of idxNum search parameter */
   144872   int nConstraint;                  /* Number of entries in aConstraint */
   144873   RtreeConstraint *aConstraint;     /* Search constraints. */
   144874   int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
   144875   int nPoint;                       /* Number of slots used in aPoint[] */
   144876   int mxLevel;                      /* iLevel value for root of the tree */
   144877   RtreeSearchPoint *aPoint;         /* Priority queue for search points */
   144878   RtreeSearchPoint sPoint;          /* Cached next search point */
   144879   RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
   144880   u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
   144881 };
   144882 
   144883 /* Return the Rtree of a RtreeCursor */
   144884 #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
   144885 
   144886 /*
   144887 ** A coordinate can be either a floating point number or a integer.  All
   144888 ** coordinates within a single R-Tree are always of the same time.
   144889 */
   144890 union RtreeCoord {
   144891   RtreeValue f;      /* Floating point value */
   144892   int i;             /* Integer value */
   144893   u32 u;             /* Unsigned for byte-order conversions */
   144894 };
   144895 
   144896 /*
   144897 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
   144898 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
   144899 ** variable pRtree points to the Rtree structure associated with the
   144900 ** RtreeCoord.
   144901 */
   144902 #ifdef SQLITE_RTREE_INT_ONLY
   144903 # define DCOORD(coord) ((RtreeDValue)coord.i)
   144904 #else
   144905 # define DCOORD(coord) (                           \
   144906     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
   144907       ((double)coord.f) :                           \
   144908       ((double)coord.i)                             \
   144909   )
   144910 #endif
   144911 
   144912 /*
   144913 ** A search constraint.
   144914 */
   144915 struct RtreeConstraint {
   144916   int iCoord;                     /* Index of constrained coordinate */
   144917   int op;                         /* Constraining operation */
   144918   union {
   144919     RtreeDValue rValue;             /* Constraint value. */
   144920     int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
   144921     int (*xQueryFunc)(sqlite3_rtree_query_info*);
   144922   } u;
   144923   sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
   144924 };
   144925 
   144926 /* Possible values for RtreeConstraint.op */
   144927 #define RTREE_EQ    0x41  /* A */
   144928 #define RTREE_LE    0x42  /* B */
   144929 #define RTREE_LT    0x43  /* C */
   144930 #define RTREE_GE    0x44  /* D */
   144931 #define RTREE_GT    0x45  /* E */
   144932 #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
   144933 #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
   144934 
   144935 
   144936 /*
   144937 ** An rtree structure node.
   144938 */
   144939 struct RtreeNode {
   144940   RtreeNode *pParent;         /* Parent node */
   144941   i64 iNode;                  /* The node number */
   144942   int nRef;                   /* Number of references to this node */
   144943   int isDirty;                /* True if the node needs to be written to disk */
   144944   u8 *zData;                  /* Content of the node, as should be on disk */
   144945   RtreeNode *pNext;           /* Next node in this hash collision chain */
   144946 };
   144947 
   144948 /* Return the number of cells in a node  */
   144949 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
   144950 
   144951 /*
   144952 ** A single cell from a node, deserialized
   144953 */
   144954 struct RtreeCell {
   144955   i64 iRowid;                                 /* Node or entry ID */
   144956   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
   144957 };
   144958 
   144959 
   144960 /*
   144961 ** This object becomes the sqlite3_user_data() for the SQL functions
   144962 ** that are created by sqlite3_rtree_geometry_callback() and
   144963 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
   144964 ** operators in order to constrain a search.
   144965 **
   144966 ** xGeom and xQueryFunc are the callback functions.  Exactly one of
   144967 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
   144968 ** SQL function was created using sqlite3_rtree_geometry_callback() or
   144969 ** sqlite3_rtree_query_callback().
   144970 **
   144971 ** This object is deleted automatically by the destructor mechanism in
   144972 ** sqlite3_create_function_v2().
   144973 */
   144974 struct RtreeGeomCallback {
   144975   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
   144976   int (*xQueryFunc)(sqlite3_rtree_query_info*);
   144977   void (*xDestructor)(void*);
   144978   void *pContext;
   144979 };
   144980 
   144981 
   144982 /*
   144983 ** Value for the first field of every RtreeMatchArg object. The MATCH
   144984 ** operator tests that the first field of a blob operand matches this
   144985 ** value to avoid operating on invalid blobs (which could cause a segfault).
   144986 */
   144987 #define RTREE_GEOMETRY_MAGIC 0x891245AB
   144988 
   144989 /*
   144990 ** An instance of this structure (in the form of a BLOB) is returned by
   144991 ** the SQL functions that sqlite3_rtree_geometry_callback() and
   144992 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
   144993 ** operand to the MATCH operator of an R-Tree.
   144994 */
   144995 struct RtreeMatchArg {
   144996   u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
   144997   RtreeGeomCallback cb;       /* Info about the callback functions */
   144998   int nParam;                 /* Number of parameters to the SQL function */
   144999   RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
   145000 };
   145001 
   145002 #ifndef MAX
   145003 # define MAX(x,y) ((x) < (y) ? (y) : (x))
   145004 #endif
   145005 #ifndef MIN
   145006 # define MIN(x,y) ((x) > (y) ? (y) : (x))
   145007 #endif
   145008 
   145009 /*
   145010 ** Functions to deserialize a 16 bit integer, 32 bit real number and
   145011 ** 64 bit integer. The deserialized value is returned.
   145012 */
   145013 static int readInt16(u8 *p){
   145014   return (p[0]<<8) + p[1];
   145015 }
   145016 static void readCoord(u8 *p, RtreeCoord *pCoord){
   145017   u32 i = (
   145018     (((u32)p[0]) << 24) +
   145019     (((u32)p[1]) << 16) +
   145020     (((u32)p[2]) <<  8) +
   145021     (((u32)p[3]) <<  0)
   145022   );
   145023   *(u32 *)pCoord = i;
   145024 }
   145025 static i64 readInt64(u8 *p){
   145026   return (
   145027     (((i64)p[0]) << 56) +
   145028     (((i64)p[1]) << 48) +
   145029     (((i64)p[2]) << 40) +
   145030     (((i64)p[3]) << 32) +
   145031     (((i64)p[4]) << 24) +
   145032     (((i64)p[5]) << 16) +
   145033     (((i64)p[6]) <<  8) +
   145034     (((i64)p[7]) <<  0)
   145035   );
   145036 }
   145037 
   145038 /*
   145039 ** Functions to serialize a 16 bit integer, 32 bit real number and
   145040 ** 64 bit integer. The value returned is the number of bytes written
   145041 ** to the argument buffer (always 2, 4 and 8 respectively).
   145042 */
   145043 static int writeInt16(u8 *p, int i){
   145044   p[0] = (i>> 8)&0xFF;
   145045   p[1] = (i>> 0)&0xFF;
   145046   return 2;
   145047 }
   145048 static int writeCoord(u8 *p, RtreeCoord *pCoord){
   145049   u32 i;
   145050   assert( sizeof(RtreeCoord)==4 );
   145051   assert( sizeof(u32)==4 );
   145052   i = *(u32 *)pCoord;
   145053   p[0] = (i>>24)&0xFF;
   145054   p[1] = (i>>16)&0xFF;
   145055   p[2] = (i>> 8)&0xFF;
   145056   p[3] = (i>> 0)&0xFF;
   145057   return 4;
   145058 }
   145059 static int writeInt64(u8 *p, i64 i){
   145060   p[0] = (i>>56)&0xFF;
   145061   p[1] = (i>>48)&0xFF;
   145062   p[2] = (i>>40)&0xFF;
   145063   p[3] = (i>>32)&0xFF;
   145064   p[4] = (i>>24)&0xFF;
   145065   p[5] = (i>>16)&0xFF;
   145066   p[6] = (i>> 8)&0xFF;
   145067   p[7] = (i>> 0)&0xFF;
   145068   return 8;
   145069 }
   145070 
   145071 /*
   145072 ** Increment the reference count of node p.
   145073 */
   145074 static void nodeReference(RtreeNode *p){
   145075   if( p ){
   145076     p->nRef++;
   145077   }
   145078 }
   145079 
   145080 /*
   145081 ** Clear the content of node p (set all bytes to 0x00).
   145082 */
   145083 static void nodeZero(Rtree *pRtree, RtreeNode *p){
   145084   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
   145085   p->isDirty = 1;
   145086 }
   145087 
   145088 /*
   145089 ** Given a node number iNode, return the corresponding key to use
   145090 ** in the Rtree.aHash table.
   145091 */
   145092 static int nodeHash(i64 iNode){
   145093   return iNode % HASHSIZE;
   145094 }
   145095 
   145096 /*
   145097 ** Search the node hash table for node iNode. If found, return a pointer
   145098 ** to it. Otherwise, return 0.
   145099 */
   145100 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
   145101   RtreeNode *p;
   145102   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
   145103   return p;
   145104 }
   145105 
   145106 /*
   145107 ** Add node pNode to the node hash table.
   145108 */
   145109 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
   145110   int iHash;
   145111   assert( pNode->pNext==0 );
   145112   iHash = nodeHash(pNode->iNode);
   145113   pNode->pNext = pRtree->aHash[iHash];
   145114   pRtree->aHash[iHash] = pNode;
   145115 }
   145116 
   145117 /*
   145118 ** Remove node pNode from the node hash table.
   145119 */
   145120 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
   145121   RtreeNode **pp;
   145122   if( pNode->iNode!=0 ){
   145123     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
   145124     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
   145125     *pp = pNode->pNext;
   145126     pNode->pNext = 0;
   145127   }
   145128 }
   145129 
   145130 /*
   145131 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
   145132 ** indicating that node has not yet been assigned a node number. It is
   145133 ** assigned a node number when nodeWrite() is called to write the
   145134 ** node contents out to the database.
   145135 */
   145136 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
   145137   RtreeNode *pNode;
   145138   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
   145139   if( pNode ){
   145140     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
   145141     pNode->zData = (u8 *)&pNode[1];
   145142     pNode->nRef = 1;
   145143     pNode->pParent = pParent;
   145144     pNode->isDirty = 1;
   145145     nodeReference(pParent);
   145146   }
   145147   return pNode;
   145148 }
   145149 
   145150 /*
   145151 ** Obtain a reference to an r-tree node.
   145152 */
   145153 static int nodeAcquire(
   145154   Rtree *pRtree,             /* R-tree structure */
   145155   i64 iNode,                 /* Node number to load */
   145156   RtreeNode *pParent,        /* Either the parent node or NULL */
   145157   RtreeNode **ppNode         /* OUT: Acquired node */
   145158 ){
   145159   int rc;
   145160   int rc2 = SQLITE_OK;
   145161   RtreeNode *pNode;
   145162 
   145163   /* Check if the requested node is already in the hash table. If so,
   145164   ** increase its reference count and return it.
   145165   */
   145166   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
   145167     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
   145168     if( pParent && !pNode->pParent ){
   145169       nodeReference(pParent);
   145170       pNode->pParent = pParent;
   145171     }
   145172     pNode->nRef++;
   145173     *ppNode = pNode;
   145174     return SQLITE_OK;
   145175   }
   145176 
   145177   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
   145178   rc = sqlite3_step(pRtree->pReadNode);
   145179   if( rc==SQLITE_ROW ){
   145180     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
   145181     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
   145182       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
   145183       if( !pNode ){
   145184         rc2 = SQLITE_NOMEM;
   145185       }else{
   145186         pNode->pParent = pParent;
   145187         pNode->zData = (u8 *)&pNode[1];
   145188         pNode->nRef = 1;
   145189         pNode->iNode = iNode;
   145190         pNode->isDirty = 0;
   145191         pNode->pNext = 0;
   145192         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
   145193         nodeReference(pParent);
   145194       }
   145195     }
   145196   }
   145197   rc = sqlite3_reset(pRtree->pReadNode);
   145198   if( rc==SQLITE_OK ) rc = rc2;
   145199 
   145200   /* If the root node was just loaded, set pRtree->iDepth to the height
   145201   ** of the r-tree structure. A height of zero means all data is stored on
   145202   ** the root node. A height of one means the children of the root node
   145203   ** are the leaves, and so on. If the depth as specified on the root node
   145204   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
   145205   */
   145206   if( pNode && iNode==1 ){
   145207     pRtree->iDepth = readInt16(pNode->zData);
   145208     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
   145209       rc = SQLITE_CORRUPT_VTAB;
   145210     }
   145211   }
   145212 
   145213   /* If no error has occurred so far, check if the "number of entries"
   145214   ** field on the node is too large. If so, set the return code to
   145215   ** SQLITE_CORRUPT_VTAB.
   145216   */
   145217   if( pNode && rc==SQLITE_OK ){
   145218     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
   145219       rc = SQLITE_CORRUPT_VTAB;
   145220     }
   145221   }
   145222 
   145223   if( rc==SQLITE_OK ){
   145224     if( pNode!=0 ){
   145225       nodeHashInsert(pRtree, pNode);
   145226     }else{
   145227       rc = SQLITE_CORRUPT_VTAB;
   145228     }
   145229     *ppNode = pNode;
   145230   }else{
   145231     sqlite3_free(pNode);
   145232     *ppNode = 0;
   145233   }
   145234 
   145235   return rc;
   145236 }
   145237 
   145238 /*
   145239 ** Overwrite cell iCell of node pNode with the contents of pCell.
   145240 */
   145241 static void nodeOverwriteCell(
   145242   Rtree *pRtree,             /* The overall R-Tree */
   145243   RtreeNode *pNode,          /* The node into which the cell is to be written */
   145244   RtreeCell *pCell,          /* The cell to write */
   145245   int iCell                  /* Index into pNode into which pCell is written */
   145246 ){
   145247   int ii;
   145248   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   145249   p += writeInt64(p, pCell->iRowid);
   145250   for(ii=0; ii<(pRtree->nDim*2); ii++){
   145251     p += writeCoord(p, &pCell->aCoord[ii]);
   145252   }
   145253   pNode->isDirty = 1;
   145254 }
   145255 
   145256 /*
   145257 ** Remove the cell with index iCell from node pNode.
   145258 */
   145259 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
   145260   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   145261   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
   145262   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
   145263   memmove(pDst, pSrc, nByte);
   145264   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
   145265   pNode->isDirty = 1;
   145266 }
   145267 
   145268 /*
   145269 ** Insert the contents of cell pCell into node pNode. If the insert
   145270 ** is successful, return SQLITE_OK.
   145271 **
   145272 ** If there is not enough free space in pNode, return SQLITE_FULL.
   145273 */
   145274 static int nodeInsertCell(
   145275   Rtree *pRtree,                /* The overall R-Tree */
   145276   RtreeNode *pNode,             /* Write new cell into this node */
   145277   RtreeCell *pCell              /* The cell to be inserted */
   145278 ){
   145279   int nCell;                    /* Current number of cells in pNode */
   145280   int nMaxCell;                 /* Maximum number of cells for pNode */
   145281 
   145282   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
   145283   nCell = NCELL(pNode);
   145284 
   145285   assert( nCell<=nMaxCell );
   145286   if( nCell<nMaxCell ){
   145287     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
   145288     writeInt16(&pNode->zData[2], nCell+1);
   145289     pNode->isDirty = 1;
   145290   }
   145291 
   145292   return (nCell==nMaxCell);
   145293 }
   145294 
   145295 /*
   145296 ** If the node is dirty, write it out to the database.
   145297 */
   145298 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
   145299   int rc = SQLITE_OK;
   145300   if( pNode->isDirty ){
   145301     sqlite3_stmt *p = pRtree->pWriteNode;
   145302     if( pNode->iNode ){
   145303       sqlite3_bind_int64(p, 1, pNode->iNode);
   145304     }else{
   145305       sqlite3_bind_null(p, 1);
   145306     }
   145307     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
   145308     sqlite3_step(p);
   145309     pNode->isDirty = 0;
   145310     rc = sqlite3_reset(p);
   145311     if( pNode->iNode==0 && rc==SQLITE_OK ){
   145312       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
   145313       nodeHashInsert(pRtree, pNode);
   145314     }
   145315   }
   145316   return rc;
   145317 }
   145318 
   145319 /*
   145320 ** Release a reference to a node. If the node is dirty and the reference
   145321 ** count drops to zero, the node data is written to the database.
   145322 */
   145323 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
   145324   int rc = SQLITE_OK;
   145325   if( pNode ){
   145326     assert( pNode->nRef>0 );
   145327     pNode->nRef--;
   145328     if( pNode->nRef==0 ){
   145329       if( pNode->iNode==1 ){
   145330         pRtree->iDepth = -1;
   145331       }
   145332       if( pNode->pParent ){
   145333         rc = nodeRelease(pRtree, pNode->pParent);
   145334       }
   145335       if( rc==SQLITE_OK ){
   145336         rc = nodeWrite(pRtree, pNode);
   145337       }
   145338       nodeHashDelete(pRtree, pNode);
   145339       sqlite3_free(pNode);
   145340     }
   145341   }
   145342   return rc;
   145343 }
   145344 
   145345 /*
   145346 ** Return the 64-bit integer value associated with cell iCell of
   145347 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
   145348 ** an internal node, then the 64-bit integer is a child page number.
   145349 */
   145350 static i64 nodeGetRowid(
   145351   Rtree *pRtree,       /* The overall R-Tree */
   145352   RtreeNode *pNode,    /* The node from which to extract the ID */
   145353   int iCell            /* The cell index from which to extract the ID */
   145354 ){
   145355   assert( iCell<NCELL(pNode) );
   145356   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
   145357 }
   145358 
   145359 /*
   145360 ** Return coordinate iCoord from cell iCell in node pNode.
   145361 */
   145362 static void nodeGetCoord(
   145363   Rtree *pRtree,               /* The overall R-Tree */
   145364   RtreeNode *pNode,            /* The node from which to extract a coordinate */
   145365   int iCell,                   /* The index of the cell within the node */
   145366   int iCoord,                  /* Which coordinate to extract */
   145367   RtreeCoord *pCoord           /* OUT: Space to write result to */
   145368 ){
   145369   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
   145370 }
   145371 
   145372 /*
   145373 ** Deserialize cell iCell of node pNode. Populate the structure pointed
   145374 ** to by pCell with the results.
   145375 */
   145376 static void nodeGetCell(
   145377   Rtree *pRtree,               /* The overall R-Tree */
   145378   RtreeNode *pNode,            /* The node containing the cell to be read */
   145379   int iCell,                   /* Index of the cell within the node */
   145380   RtreeCell *pCell             /* OUT: Write the cell contents here */
   145381 ){
   145382   u8 *pData;
   145383   u8 *pEnd;
   145384   RtreeCoord *pCoord;
   145385   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
   145386   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
   145387   pEnd = pData + pRtree->nDim*8;
   145388   pCoord = pCell->aCoord;
   145389   for(; pData<pEnd; pData+=4, pCoord++){
   145390     readCoord(pData, pCoord);
   145391   }
   145392 }
   145393 
   145394 
   145395 /* Forward declaration for the function that does the work of
   145396 ** the virtual table module xCreate() and xConnect() methods.
   145397 */
   145398 static int rtreeInit(
   145399   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
   145400 );
   145401 
   145402 /*
   145403 ** Rtree virtual table module xCreate method.
   145404 */
   145405 static int rtreeCreate(
   145406   sqlite3 *db,
   145407   void *pAux,
   145408   int argc, const char *const*argv,
   145409   sqlite3_vtab **ppVtab,
   145410   char **pzErr
   145411 ){
   145412   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
   145413 }
   145414 
   145415 /*
   145416 ** Rtree virtual table module xConnect method.
   145417 */
   145418 static int rtreeConnect(
   145419   sqlite3 *db,
   145420   void *pAux,
   145421   int argc, const char *const*argv,
   145422   sqlite3_vtab **ppVtab,
   145423   char **pzErr
   145424 ){
   145425   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
   145426 }
   145427 
   145428 /*
   145429 ** Increment the r-tree reference count.
   145430 */
   145431 static void rtreeReference(Rtree *pRtree){
   145432   pRtree->nBusy++;
   145433 }
   145434 
   145435 /*
   145436 ** Decrement the r-tree reference count. When the reference count reaches
   145437 ** zero the structure is deleted.
   145438 */
   145439 static void rtreeRelease(Rtree *pRtree){
   145440   pRtree->nBusy--;
   145441   if( pRtree->nBusy==0 ){
   145442     sqlite3_finalize(pRtree->pReadNode);
   145443     sqlite3_finalize(pRtree->pWriteNode);
   145444     sqlite3_finalize(pRtree->pDeleteNode);
   145445     sqlite3_finalize(pRtree->pReadRowid);
   145446     sqlite3_finalize(pRtree->pWriteRowid);
   145447     sqlite3_finalize(pRtree->pDeleteRowid);
   145448     sqlite3_finalize(pRtree->pReadParent);
   145449     sqlite3_finalize(pRtree->pWriteParent);
   145450     sqlite3_finalize(pRtree->pDeleteParent);
   145451     sqlite3_free(pRtree);
   145452   }
   145453 }
   145454 
   145455 /*
   145456 ** Rtree virtual table module xDisconnect method.
   145457 */
   145458 static int rtreeDisconnect(sqlite3_vtab *pVtab){
   145459   rtreeRelease((Rtree *)pVtab);
   145460   return SQLITE_OK;
   145461 }
   145462 
   145463 /*
   145464 ** Rtree virtual table module xDestroy method.
   145465 */
   145466 static int rtreeDestroy(sqlite3_vtab *pVtab){
   145467   Rtree *pRtree = (Rtree *)pVtab;
   145468   int rc;
   145469   char *zCreate = sqlite3_mprintf(
   145470     "DROP TABLE '%q'.'%q_node';"
   145471     "DROP TABLE '%q'.'%q_rowid';"
   145472     "DROP TABLE '%q'.'%q_parent';",
   145473     pRtree->zDb, pRtree->zName,
   145474     pRtree->zDb, pRtree->zName,
   145475     pRtree->zDb, pRtree->zName
   145476   );
   145477   if( !zCreate ){
   145478     rc = SQLITE_NOMEM;
   145479   }else{
   145480     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
   145481     sqlite3_free(zCreate);
   145482   }
   145483   if( rc==SQLITE_OK ){
   145484     rtreeRelease(pRtree);
   145485   }
   145486 
   145487   return rc;
   145488 }
   145489 
   145490 /*
   145491 ** Rtree virtual table module xOpen method.
   145492 */
   145493 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   145494   int rc = SQLITE_NOMEM;
   145495   RtreeCursor *pCsr;
   145496 
   145497   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
   145498   if( pCsr ){
   145499     memset(pCsr, 0, sizeof(RtreeCursor));
   145500     pCsr->base.pVtab = pVTab;
   145501     rc = SQLITE_OK;
   145502   }
   145503   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   145504 
   145505   return rc;
   145506 }
   145507 
   145508 
   145509 /*
   145510 ** Free the RtreeCursor.aConstraint[] array and its contents.
   145511 */
   145512 static void freeCursorConstraints(RtreeCursor *pCsr){
   145513   if( pCsr->aConstraint ){
   145514     int i;                        /* Used to iterate through constraint array */
   145515     for(i=0; i<pCsr->nConstraint; i++){
   145516       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
   145517       if( pInfo ){
   145518         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
   145519         sqlite3_free(pInfo);
   145520       }
   145521     }
   145522     sqlite3_free(pCsr->aConstraint);
   145523     pCsr->aConstraint = 0;
   145524   }
   145525 }
   145526 
   145527 /*
   145528 ** Rtree virtual table module xClose method.
   145529 */
   145530 static int rtreeClose(sqlite3_vtab_cursor *cur){
   145531   Rtree *pRtree = (Rtree *)(cur->pVtab);
   145532   int ii;
   145533   RtreeCursor *pCsr = (RtreeCursor *)cur;
   145534   freeCursorConstraints(pCsr);
   145535   sqlite3_free(pCsr->aPoint);
   145536   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
   145537   sqlite3_free(pCsr);
   145538   return SQLITE_OK;
   145539 }
   145540 
   145541 /*
   145542 ** Rtree virtual table module xEof method.
   145543 **
   145544 ** Return non-zero if the cursor does not currently point to a valid
   145545 ** record (i.e if the scan has finished), or zero otherwise.
   145546 */
   145547 static int rtreeEof(sqlite3_vtab_cursor *cur){
   145548   RtreeCursor *pCsr = (RtreeCursor *)cur;
   145549   return pCsr->atEOF;
   145550 }
   145551 
   145552 /*
   145553 ** Convert raw bits from the on-disk RTree record into a coordinate value.
   145554 ** The on-disk format is big-endian and needs to be converted for little-
   145555 ** endian platforms.  The on-disk record stores integer coordinates if
   145556 ** eInt is true and it stores 32-bit floating point records if eInt is
   145557 ** false.  a[] is the four bytes of the on-disk record to be decoded.
   145558 ** Store the results in "r".
   145559 **
   145560 ** There are three versions of this macro, one each for little-endian and
   145561 ** big-endian processors and a third generic implementation.  The endian-
   145562 ** specific implementations are much faster and are preferred if the
   145563 ** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
   145564 ** macro is part of sqliteInt.h and hence the endian-specific
   145565 ** implementation will only be used if this module is compiled as part
   145566 ** of the amalgamation.
   145567 */
   145568 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
   145569 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   145570     RtreeCoord c;    /* Coordinate decoded */                   \
   145571     memcpy(&c.u,a,4);                                           \
   145572     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
   145573           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
   145574     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   145575 }
   145576 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
   145577 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   145578     RtreeCoord c;    /* Coordinate decoded */                   \
   145579     memcpy(&c.u,a,4);                                           \
   145580     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   145581 }
   145582 #else
   145583 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   145584     RtreeCoord c;    /* Coordinate decoded */                   \
   145585     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
   145586            +((u32)a[2]<<8) + a[3];                              \
   145587     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   145588 }
   145589 #endif
   145590 
   145591 /*
   145592 ** Check the RTree node or entry given by pCellData and p against the MATCH
   145593 ** constraint pConstraint.
   145594 */
   145595 static int rtreeCallbackConstraint(
   145596   RtreeConstraint *pConstraint,  /* The constraint to test */
   145597   int eInt,                      /* True if RTree holding integer coordinates */
   145598   u8 *pCellData,                 /* Raw cell content */
   145599   RtreeSearchPoint *pSearch,     /* Container of this cell */
   145600   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
   145601   int *peWithin                  /* OUT: visibility of the cell */
   145602 ){
   145603   int i;                                                /* Loop counter */
   145604   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
   145605   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
   145606   int rc;                                             /* Callback return code */
   145607   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
   145608 
   145609   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
   145610   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
   145611 
   145612   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
   145613     pInfo->iRowid = readInt64(pCellData);
   145614   }
   145615   pCellData += 8;
   145616   for(i=0; i<nCoord; i++, pCellData += 4){
   145617     RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
   145618   }
   145619   if( pConstraint->op==RTREE_MATCH ){
   145620     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
   145621                               nCoord, aCoord, &i);
   145622     if( i==0 ) *peWithin = NOT_WITHIN;
   145623     *prScore = RTREE_ZERO;
   145624   }else{
   145625     pInfo->aCoord = aCoord;
   145626     pInfo->iLevel = pSearch->iLevel - 1;
   145627     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
   145628     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
   145629     rc = pConstraint->u.xQueryFunc(pInfo);
   145630     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
   145631     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
   145632       *prScore = pInfo->rScore;
   145633     }
   145634   }
   145635   return rc;
   145636 }
   145637 
   145638 /*
   145639 ** Check the internal RTree node given by pCellData against constraint p.
   145640 ** If this constraint cannot be satisfied by any child within the node,
   145641 ** set *peWithin to NOT_WITHIN.
   145642 */
   145643 static void rtreeNonleafConstraint(
   145644   RtreeConstraint *p,        /* The constraint to test */
   145645   int eInt,                  /* True if RTree holds integer coordinates */
   145646   u8 *pCellData,             /* Raw cell content as appears on disk */
   145647   int *peWithin              /* Adjust downward, as appropriate */
   145648 ){
   145649   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
   145650 
   145651   /* p->iCoord might point to either a lower or upper bound coordinate
   145652   ** in a coordinate pair.  But make pCellData point to the lower bound.
   145653   */
   145654   pCellData += 8 + 4*(p->iCoord&0xfe);
   145655 
   145656   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   145657       || p->op==RTREE_GT || p->op==RTREE_EQ );
   145658   switch( p->op ){
   145659     case RTREE_LE:
   145660     case RTREE_LT:
   145661     case RTREE_EQ:
   145662       RTREE_DECODE_COORD(eInt, pCellData, val);
   145663       /* val now holds the lower bound of the coordinate pair */
   145664       if( p->u.rValue>=val ) return;
   145665       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
   145666       /* Fall through for the RTREE_EQ case */
   145667 
   145668     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
   145669       pCellData += 4;
   145670       RTREE_DECODE_COORD(eInt, pCellData, val);
   145671       /* val now holds the upper bound of the coordinate pair */
   145672       if( p->u.rValue<=val ) return;
   145673   }
   145674   *peWithin = NOT_WITHIN;
   145675 }
   145676 
   145677 /*
   145678 ** Check the leaf RTree cell given by pCellData against constraint p.
   145679 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
   145680 ** If the constraint is satisfied, leave *peWithin unchanged.
   145681 **
   145682 ** The constraint is of the form:  xN op $val
   145683 **
   145684 ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
   145685 ** pCellData.  $val is given by p->u.rValue.
   145686 */
   145687 static void rtreeLeafConstraint(
   145688   RtreeConstraint *p,        /* The constraint to test */
   145689   int eInt,                  /* True if RTree holds integer coordinates */
   145690   u8 *pCellData,             /* Raw cell content as appears on disk */
   145691   int *peWithin              /* Adjust downward, as appropriate */
   145692 ){
   145693   RtreeDValue xN;      /* Coordinate value converted to a double */
   145694 
   145695   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   145696       || p->op==RTREE_GT || p->op==RTREE_EQ );
   145697   pCellData += 8 + p->iCoord*4;
   145698   RTREE_DECODE_COORD(eInt, pCellData, xN);
   145699   switch( p->op ){
   145700     case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
   145701     case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
   145702     case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
   145703     case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
   145704     default:       if( xN == p->u.rValue ) return;  break;
   145705   }
   145706   *peWithin = NOT_WITHIN;
   145707 }
   145708 
   145709 /*
   145710 ** One of the cells in node pNode is guaranteed to have a 64-bit
   145711 ** integer value equal to iRowid. Return the index of this cell.
   145712 */
   145713 static int nodeRowidIndex(
   145714   Rtree *pRtree,
   145715   RtreeNode *pNode,
   145716   i64 iRowid,
   145717   int *piIndex
   145718 ){
   145719   int ii;
   145720   int nCell = NCELL(pNode);
   145721   assert( nCell<200 );
   145722   for(ii=0; ii<nCell; ii++){
   145723     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
   145724       *piIndex = ii;
   145725       return SQLITE_OK;
   145726     }
   145727   }
   145728   return SQLITE_CORRUPT_VTAB;
   145729 }
   145730 
   145731 /*
   145732 ** Return the index of the cell containing a pointer to node pNode
   145733 ** in its parent. If pNode is the root node, return -1.
   145734 */
   145735 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
   145736   RtreeNode *pParent = pNode->pParent;
   145737   if( pParent ){
   145738     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
   145739   }
   145740   *piIndex = -1;
   145741   return SQLITE_OK;
   145742 }
   145743 
   145744 /*
   145745 ** Compare two search points.  Return negative, zero, or positive if the first
   145746 ** is less than, equal to, or greater than the second.
   145747 **
   145748 ** The rScore is the primary key.  Smaller rScore values come first.
   145749 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
   145750 ** iLevel values coming first.  In this way, if rScore is the same for all
   145751 ** SearchPoints, then iLevel becomes the deciding factor and the result
   145752 ** is a depth-first search, which is the desired default behavior.
   145753 */
   145754 static int rtreeSearchPointCompare(
   145755   const RtreeSearchPoint *pA,
   145756   const RtreeSearchPoint *pB
   145757 ){
   145758   if( pA->rScore<pB->rScore ) return -1;
   145759   if( pA->rScore>pB->rScore ) return +1;
   145760   if( pA->iLevel<pB->iLevel ) return -1;
   145761   if( pA->iLevel>pB->iLevel ) return +1;
   145762   return 0;
   145763 }
   145764 
   145765 /*
   145766 ** Interchange to search points in a cursor.
   145767 */
   145768 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
   145769   RtreeSearchPoint t = p->aPoint[i];
   145770   assert( i<j );
   145771   p->aPoint[i] = p->aPoint[j];
   145772   p->aPoint[j] = t;
   145773   i++; j++;
   145774   if( i<RTREE_CACHE_SZ ){
   145775     if( j>=RTREE_CACHE_SZ ){
   145776       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
   145777       p->aNode[i] = 0;
   145778     }else{
   145779       RtreeNode *pTemp = p->aNode[i];
   145780       p->aNode[i] = p->aNode[j];
   145781       p->aNode[j] = pTemp;
   145782     }
   145783   }
   145784 }
   145785 
   145786 /*
   145787 ** Return the search point with the lowest current score.
   145788 */
   145789 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
   145790   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
   145791 }
   145792 
   145793 /*
   145794 ** Get the RtreeNode for the search point with the lowest score.
   145795 */
   145796 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
   145797   sqlite3_int64 id;
   145798   int ii = 1 - pCur->bPoint;
   145799   assert( ii==0 || ii==1 );
   145800   assert( pCur->bPoint || pCur->nPoint );
   145801   if( pCur->aNode[ii]==0 ){
   145802     assert( pRC!=0 );
   145803     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
   145804     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
   145805   }
   145806   return pCur->aNode[ii];
   145807 }
   145808 
   145809 /*
   145810 ** Push a new element onto the priority queue
   145811 */
   145812 static RtreeSearchPoint *rtreeEnqueue(
   145813   RtreeCursor *pCur,    /* The cursor */
   145814   RtreeDValue rScore,   /* Score for the new search point */
   145815   u8 iLevel             /* Level for the new search point */
   145816 ){
   145817   int i, j;
   145818   RtreeSearchPoint *pNew;
   145819   if( pCur->nPoint>=pCur->nPointAlloc ){
   145820     int nNew = pCur->nPointAlloc*2 + 8;
   145821     pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
   145822     if( pNew==0 ) return 0;
   145823     pCur->aPoint = pNew;
   145824     pCur->nPointAlloc = nNew;
   145825   }
   145826   i = pCur->nPoint++;
   145827   pNew = pCur->aPoint + i;
   145828   pNew->rScore = rScore;
   145829   pNew->iLevel = iLevel;
   145830   assert( iLevel>=0 && iLevel<=RTREE_MAX_DEPTH );
   145831   while( i>0 ){
   145832     RtreeSearchPoint *pParent;
   145833     j = (i-1)/2;
   145834     pParent = pCur->aPoint + j;
   145835     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
   145836     rtreeSearchPointSwap(pCur, j, i);
   145837     i = j;
   145838     pNew = pParent;
   145839   }
   145840   return pNew;
   145841 }
   145842 
   145843 /*
   145844 ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
   145845 ** NULL if malloc fails.
   145846 */
   145847 static RtreeSearchPoint *rtreeSearchPointNew(
   145848   RtreeCursor *pCur,    /* The cursor */
   145849   RtreeDValue rScore,   /* Score for the new search point */
   145850   u8 iLevel             /* Level for the new search point */
   145851 ){
   145852   RtreeSearchPoint *pNew, *pFirst;
   145853   pFirst = rtreeSearchPointFirst(pCur);
   145854   pCur->anQueue[iLevel]++;
   145855   if( pFirst==0
   145856    || pFirst->rScore>rScore
   145857    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
   145858   ){
   145859     if( pCur->bPoint ){
   145860       int ii;
   145861       pNew = rtreeEnqueue(pCur, rScore, iLevel);
   145862       if( pNew==0 ) return 0;
   145863       ii = (int)(pNew - pCur->aPoint) + 1;
   145864       if( ii<RTREE_CACHE_SZ ){
   145865         assert( pCur->aNode[ii]==0 );
   145866         pCur->aNode[ii] = pCur->aNode[0];
   145867        }else{
   145868         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
   145869       }
   145870       pCur->aNode[0] = 0;
   145871       *pNew = pCur->sPoint;
   145872     }
   145873     pCur->sPoint.rScore = rScore;
   145874     pCur->sPoint.iLevel = iLevel;
   145875     pCur->bPoint = 1;
   145876     return &pCur->sPoint;
   145877   }else{
   145878     return rtreeEnqueue(pCur, rScore, iLevel);
   145879   }
   145880 }
   145881 
   145882 #if 0
   145883 /* Tracing routines for the RtreeSearchPoint queue */
   145884 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
   145885   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
   145886   printf(" %d.%05lld.%02d %g %d",
   145887     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
   145888   );
   145889   idx++;
   145890   if( idx<RTREE_CACHE_SZ ){
   145891     printf(" %p\n", pCur->aNode[idx]);
   145892   }else{
   145893     printf("\n");
   145894   }
   145895 }
   145896 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
   145897   int ii;
   145898   printf("=== %9s ", zPrefix);
   145899   if( pCur->bPoint ){
   145900     tracePoint(&pCur->sPoint, -1, pCur);
   145901   }
   145902   for(ii=0; ii<pCur->nPoint; ii++){
   145903     if( ii>0 || pCur->bPoint ) printf("              ");
   145904     tracePoint(&pCur->aPoint[ii], ii, pCur);
   145905   }
   145906 }
   145907 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
   145908 #else
   145909 # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
   145910 #endif
   145911 
   145912 /* Remove the search point with the lowest current score.
   145913 */
   145914 static void rtreeSearchPointPop(RtreeCursor *p){
   145915   int i, j, k, n;
   145916   i = 1 - p->bPoint;
   145917   assert( i==0 || i==1 );
   145918   if( p->aNode[i] ){
   145919     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
   145920     p->aNode[i] = 0;
   145921   }
   145922   if( p->bPoint ){
   145923     p->anQueue[p->sPoint.iLevel]--;
   145924     p->bPoint = 0;
   145925   }else if( p->nPoint ){
   145926     p->anQueue[p->aPoint[0].iLevel]--;
   145927     n = --p->nPoint;
   145928     p->aPoint[0] = p->aPoint[n];
   145929     if( n<RTREE_CACHE_SZ-1 ){
   145930       p->aNode[1] = p->aNode[n+1];
   145931       p->aNode[n+1] = 0;
   145932     }
   145933     i = 0;
   145934     while( (j = i*2+1)<n ){
   145935       k = j+1;
   145936       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
   145937         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
   145938           rtreeSearchPointSwap(p, i, k);
   145939           i = k;
   145940         }else{
   145941           break;
   145942         }
   145943       }else{
   145944         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
   145945           rtreeSearchPointSwap(p, i, j);
   145946           i = j;
   145947         }else{
   145948           break;
   145949         }
   145950       }
   145951     }
   145952   }
   145953 }
   145954 
   145955 
   145956 /*
   145957 ** Continue the search on cursor pCur until the front of the queue
   145958 ** contains an entry suitable for returning as a result-set row,
   145959 ** or until the RtreeSearchPoint queue is empty, indicating that the
   145960 ** query has completed.
   145961 */
   145962 static int rtreeStepToLeaf(RtreeCursor *pCur){
   145963   RtreeSearchPoint *p;
   145964   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
   145965   RtreeNode *pNode;
   145966   int eWithin;
   145967   int rc = SQLITE_OK;
   145968   int nCell;
   145969   int nConstraint = pCur->nConstraint;
   145970   int ii;
   145971   int eInt;
   145972   RtreeSearchPoint x;
   145973 
   145974   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
   145975   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
   145976     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
   145977     if( rc ) return rc;
   145978     nCell = NCELL(pNode);
   145979     assert( nCell<200 );
   145980     while( p->iCell<nCell ){
   145981       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
   145982       u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
   145983       eWithin = FULLY_WITHIN;
   145984       for(ii=0; ii<nConstraint; ii++){
   145985         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
   145986         if( pConstraint->op>=RTREE_MATCH ){
   145987           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
   145988                                        &rScore, &eWithin);
   145989           if( rc ) return rc;
   145990         }else if( p->iLevel==1 ){
   145991           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
   145992         }else{
   145993           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
   145994         }
   145995         if( eWithin==NOT_WITHIN ) break;
   145996       }
   145997       p->iCell++;
   145998       if( eWithin==NOT_WITHIN ) continue;
   145999       x.iLevel = p->iLevel - 1;
   146000       if( x.iLevel ){
   146001         x.id = readInt64(pCellData);
   146002         x.iCell = 0;
   146003       }else{
   146004         x.id = p->id;
   146005         x.iCell = p->iCell - 1;
   146006       }
   146007       if( p->iCell>=nCell ){
   146008         RTREE_QUEUE_TRACE(pCur, "POP-S:");
   146009         rtreeSearchPointPop(pCur);
   146010       }
   146011       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
   146012       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
   146013       if( p==0 ) return SQLITE_NOMEM;
   146014       p->eWithin = eWithin;
   146015       p->id = x.id;
   146016       p->iCell = x.iCell;
   146017       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
   146018       break;
   146019     }
   146020     if( p->iCell>=nCell ){
   146021       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
   146022       rtreeSearchPointPop(pCur);
   146023     }
   146024   }
   146025   pCur->atEOF = p==0;
   146026   return SQLITE_OK;
   146027 }
   146028 
   146029 /*
   146030 ** Rtree virtual table module xNext method.
   146031 */
   146032 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
   146033   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   146034   int rc = SQLITE_OK;
   146035 
   146036   /* Move to the next entry that matches the configured constraints. */
   146037   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
   146038   rtreeSearchPointPop(pCsr);
   146039   rc = rtreeStepToLeaf(pCsr);
   146040   return rc;
   146041 }
   146042 
   146043 /*
   146044 ** Rtree virtual table module xRowid method.
   146045 */
   146046 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   146047   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   146048   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
   146049   int rc = SQLITE_OK;
   146050   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
   146051   if( rc==SQLITE_OK && p ){
   146052     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
   146053   }
   146054   return rc;
   146055 }
   146056 
   146057 /*
   146058 ** Rtree virtual table module xColumn method.
   146059 */
   146060 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   146061   Rtree *pRtree = (Rtree *)cur->pVtab;
   146062   RtreeCursor *pCsr = (RtreeCursor *)cur;
   146063   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
   146064   RtreeCoord c;
   146065   int rc = SQLITE_OK;
   146066   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
   146067 
   146068   if( rc ) return rc;
   146069   if( p==0 ) return SQLITE_OK;
   146070   if( i==0 ){
   146071     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
   146072   }else{
   146073     if( rc ) return rc;
   146074     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
   146075 #ifndef SQLITE_RTREE_INT_ONLY
   146076     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   146077       sqlite3_result_double(ctx, c.f);
   146078     }else
   146079 #endif
   146080     {
   146081       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
   146082       sqlite3_result_int(ctx, c.i);
   146083     }
   146084   }
   146085   return SQLITE_OK;
   146086 }
   146087 
   146088 /*
   146089 ** Use nodeAcquire() to obtain the leaf node containing the record with
   146090 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
   146091 ** return SQLITE_OK. If there is no such record in the table, set
   146092 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
   146093 ** to zero and return an SQLite error code.
   146094 */
   146095 static int findLeafNode(
   146096   Rtree *pRtree,              /* RTree to search */
   146097   i64 iRowid,                 /* The rowid searching for */
   146098   RtreeNode **ppLeaf,         /* Write the node here */
   146099   sqlite3_int64 *piNode       /* Write the node-id here */
   146100 ){
   146101   int rc;
   146102   *ppLeaf = 0;
   146103   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
   146104   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
   146105     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
   146106     if( piNode ) *piNode = iNode;
   146107     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
   146108     sqlite3_reset(pRtree->pReadRowid);
   146109   }else{
   146110     rc = sqlite3_reset(pRtree->pReadRowid);
   146111   }
   146112   return rc;
   146113 }
   146114 
   146115 /*
   146116 ** This function is called to configure the RtreeConstraint object passed
   146117 ** as the second argument for a MATCH constraint. The value passed as the
   146118 ** first argument to this function is the right-hand operand to the MATCH
   146119 ** operator.
   146120 */
   146121 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
   146122   RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
   146123   sqlite3_rtree_query_info *pInfo;   /* Callback information */
   146124   int nBlob;                         /* Size of the geometry function blob */
   146125   int nExpected;                     /* Expected size of the BLOB */
   146126 
   146127   /* Check that value is actually a blob. */
   146128   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
   146129 
   146130   /* Check that the blob is roughly the right size. */
   146131   nBlob = sqlite3_value_bytes(pValue);
   146132   if( nBlob<(int)sizeof(RtreeMatchArg)
   146133    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
   146134   ){
   146135     return SQLITE_ERROR;
   146136   }
   146137 
   146138   pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
   146139   if( !pInfo ) return SQLITE_NOMEM;
   146140   memset(pInfo, 0, sizeof(*pInfo));
   146141   pBlob = (RtreeMatchArg*)&pInfo[1];
   146142 
   146143   memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
   146144   nExpected = (int)(sizeof(RtreeMatchArg) +
   146145                     (pBlob->nParam-1)*sizeof(RtreeDValue));
   146146   if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
   146147     sqlite3_free(pInfo);
   146148     return SQLITE_ERROR;
   146149   }
   146150   pInfo->pContext = pBlob->cb.pContext;
   146151   pInfo->nParam = pBlob->nParam;
   146152   pInfo->aParam = pBlob->aParam;
   146153 
   146154   if( pBlob->cb.xGeom ){
   146155     pCons->u.xGeom = pBlob->cb.xGeom;
   146156   }else{
   146157     pCons->op = RTREE_QUERY;
   146158     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
   146159   }
   146160   pCons->pInfo = pInfo;
   146161   return SQLITE_OK;
   146162 }
   146163 
   146164 /*
   146165 ** Rtree virtual table module xFilter method.
   146166 */
   146167 static int rtreeFilter(
   146168   sqlite3_vtab_cursor *pVtabCursor,
   146169   int idxNum, const char *idxStr,
   146170   int argc, sqlite3_value **argv
   146171 ){
   146172   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   146173   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   146174   RtreeNode *pRoot = 0;
   146175   int ii;
   146176   int rc = SQLITE_OK;
   146177   int iCell = 0;
   146178 
   146179   rtreeReference(pRtree);
   146180 
   146181   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
   146182   freeCursorConstraints(pCsr);
   146183   sqlite3_free(pCsr->aPoint);
   146184   memset(pCsr, 0, sizeof(RtreeCursor));
   146185   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
   146186 
   146187   pCsr->iStrategy = idxNum;
   146188   if( idxNum==1 ){
   146189     /* Special case - lookup by rowid. */
   146190     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
   146191     RtreeSearchPoint *p;     /* Search point for the the leaf */
   146192     i64 iRowid = sqlite3_value_int64(argv[0]);
   146193     i64 iNode = 0;
   146194     rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
   146195     if( rc==SQLITE_OK && pLeaf!=0 ){
   146196       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
   146197       assert( p!=0 );  /* Always returns pCsr->sPoint */
   146198       pCsr->aNode[0] = pLeaf;
   146199       p->id = iNode;
   146200       p->eWithin = PARTLY_WITHIN;
   146201       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
   146202       p->iCell = iCell;
   146203       RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
   146204     }else{
   146205       pCsr->atEOF = 1;
   146206     }
   146207   }else{
   146208     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
   146209     ** with the configured constraints.
   146210     */
   146211     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   146212     if( rc==SQLITE_OK && argc>0 ){
   146213       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
   146214       pCsr->nConstraint = argc;
   146215       if( !pCsr->aConstraint ){
   146216         rc = SQLITE_NOMEM;
   146217       }else{
   146218         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
   146219         memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
   146220         assert( (idxStr==0 && argc==0)
   146221                 || (idxStr && (int)strlen(idxStr)==argc*2) );
   146222         for(ii=0; ii<argc; ii++){
   146223           RtreeConstraint *p = &pCsr->aConstraint[ii];
   146224           p->op = idxStr[ii*2];
   146225           p->iCoord = idxStr[ii*2+1]-'0';
   146226           if( p->op>=RTREE_MATCH ){
   146227             /* A MATCH operator. The right-hand-side must be a blob that
   146228             ** can be cast into an RtreeMatchArg object. One created using
   146229             ** an sqlite3_rtree_geometry_callback() SQL user function.
   146230             */
   146231             rc = deserializeGeometry(argv[ii], p);
   146232             if( rc!=SQLITE_OK ){
   146233               break;
   146234             }
   146235             p->pInfo->nCoord = pRtree->nDim*2;
   146236             p->pInfo->anQueue = pCsr->anQueue;
   146237             p->pInfo->mxLevel = pRtree->iDepth + 1;
   146238           }else{
   146239 #ifdef SQLITE_RTREE_INT_ONLY
   146240             p->u.rValue = sqlite3_value_int64(argv[ii]);
   146241 #else
   146242             p->u.rValue = sqlite3_value_double(argv[ii]);
   146243 #endif
   146244           }
   146245         }
   146246       }
   146247     }
   146248     if( rc==SQLITE_OK ){
   146249       RtreeSearchPoint *pNew;
   146250       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
   146251       if( pNew==0 ) return SQLITE_NOMEM;
   146252       pNew->id = 1;
   146253       pNew->iCell = 0;
   146254       pNew->eWithin = PARTLY_WITHIN;
   146255       assert( pCsr->bPoint==1 );
   146256       pCsr->aNode[0] = pRoot;
   146257       pRoot = 0;
   146258       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
   146259       rc = rtreeStepToLeaf(pCsr);
   146260     }
   146261   }
   146262 
   146263   nodeRelease(pRtree, pRoot);
   146264   rtreeRelease(pRtree);
   146265   return rc;
   146266 }
   146267 
   146268 /*
   146269 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
   146270 ** extension is currently being used by a version of SQLite too old to
   146271 ** support estimatedRows. In that case this function is a no-op.
   146272 */
   146273 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
   146274 #if SQLITE_VERSION_NUMBER>=3008002
   146275   if( sqlite3_libversion_number()>=3008002 ){
   146276     pIdxInfo->estimatedRows = nRow;
   146277   }
   146278 #endif
   146279 }
   146280 
   146281 /*
   146282 ** Rtree virtual table module xBestIndex method. There are three
   146283 ** table scan strategies to choose from (in order from most to
   146284 ** least desirable):
   146285 **
   146286 **   idxNum     idxStr        Strategy
   146287 **   ------------------------------------------------
   146288 **     1        Unused        Direct lookup by rowid.
   146289 **     2        See below     R-tree query or full-table scan.
   146290 **   ------------------------------------------------
   146291 **
   146292 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
   146293 ** 2 is used, idxStr is formatted to contain 2 bytes for each
   146294 ** constraint used. The first two bytes of idxStr correspond to
   146295 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
   146296 ** (argvIndex==1) etc.
   146297 **
   146298 ** The first of each pair of bytes in idxStr identifies the constraint
   146299 ** operator as follows:
   146300 **
   146301 **   Operator    Byte Value
   146302 **   ----------------------
   146303 **      =        0x41 ('A')
   146304 **     <=        0x42 ('B')
   146305 **      <        0x43 ('C')
   146306 **     >=        0x44 ('D')
   146307 **      >        0x45 ('E')
   146308 **   MATCH       0x46 ('F')
   146309 **   ----------------------
   146310 **
   146311 ** The second of each pair of bytes identifies the coordinate column
   146312 ** to which the constraint applies. The leftmost coordinate column
   146313 ** is 'a', the second from the left 'b' etc.
   146314 */
   146315 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   146316   Rtree *pRtree = (Rtree*)tab;
   146317   int rc = SQLITE_OK;
   146318   int ii;
   146319   i64 nRow;                       /* Estimated rows returned by this scan */
   146320 
   146321   int iIdx = 0;
   146322   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
   146323   memset(zIdxStr, 0, sizeof(zIdxStr));
   146324 
   146325   assert( pIdxInfo->idxStr==0 );
   146326   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
   146327     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
   146328 
   146329     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   146330       /* We have an equality constraint on the rowid. Use strategy 1. */
   146331       int jj;
   146332       for(jj=0; jj<ii; jj++){
   146333         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
   146334         pIdxInfo->aConstraintUsage[jj].omit = 0;
   146335       }
   146336       pIdxInfo->idxNum = 1;
   146337       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
   146338       pIdxInfo->aConstraintUsage[jj].omit = 1;
   146339 
   146340       /* This strategy involves a two rowid lookups on an B-Tree structures
   146341       ** and then a linear search of an R-Tree node. This should be
   146342       ** considered almost as quick as a direct rowid lookup (for which
   146343       ** sqlite uses an internal cost of 0.0). It is expected to return
   146344       ** a single row.
   146345       */
   146346       pIdxInfo->estimatedCost = 30.0;
   146347       setEstimatedRows(pIdxInfo, 1);
   146348       return SQLITE_OK;
   146349     }
   146350 
   146351     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
   146352       u8 op;
   146353       switch( p->op ){
   146354         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
   146355         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
   146356         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
   146357         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
   146358         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
   146359         default:
   146360           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
   146361           op = RTREE_MATCH;
   146362           break;
   146363       }
   146364       zIdxStr[iIdx++] = op;
   146365       zIdxStr[iIdx++] = p->iColumn - 1 + '0';
   146366       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
   146367       pIdxInfo->aConstraintUsage[ii].omit = 1;
   146368     }
   146369   }
   146370 
   146371   pIdxInfo->idxNum = 2;
   146372   pIdxInfo->needToFreeIdxStr = 1;
   146373   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
   146374     return SQLITE_NOMEM;
   146375   }
   146376 
   146377   nRow = pRtree->nRowEst / (iIdx + 1);
   146378   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
   146379   setEstimatedRows(pIdxInfo, nRow);
   146380 
   146381   return rc;
   146382 }
   146383 
   146384 /*
   146385 ** Return the N-dimensional volumn of the cell stored in *p.
   146386 */
   146387 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
   146388   RtreeDValue area = (RtreeDValue)1;
   146389   int ii;
   146390   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146391     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
   146392   }
   146393   return area;
   146394 }
   146395 
   146396 /*
   146397 ** Return the margin length of cell p. The margin length is the sum
   146398 ** of the objects size in each dimension.
   146399 */
   146400 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
   146401   RtreeDValue margin = (RtreeDValue)0;
   146402   int ii;
   146403   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146404     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   146405   }
   146406   return margin;
   146407 }
   146408 
   146409 /*
   146410 ** Store the union of cells p1 and p2 in p1.
   146411 */
   146412 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   146413   int ii;
   146414   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   146415     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146416       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
   146417       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
   146418     }
   146419   }else{
   146420     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146421       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
   146422       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
   146423     }
   146424   }
   146425 }
   146426 
   146427 /*
   146428 ** Return true if the area covered by p2 is a subset of the area covered
   146429 ** by p1. False otherwise.
   146430 */
   146431 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   146432   int ii;
   146433   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
   146434   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   146435     RtreeCoord *a1 = &p1->aCoord[ii];
   146436     RtreeCoord *a2 = &p2->aCoord[ii];
   146437     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
   146438      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
   146439     ){
   146440       return 0;
   146441     }
   146442   }
   146443   return 1;
   146444 }
   146445 
   146446 /*
   146447 ** Return the amount cell p would grow by if it were unioned with pCell.
   146448 */
   146449 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
   146450   RtreeDValue area;
   146451   RtreeCell cell;
   146452   memcpy(&cell, p, sizeof(RtreeCell));
   146453   area = cellArea(pRtree, &cell);
   146454   cellUnion(pRtree, &cell, pCell);
   146455   return (cellArea(pRtree, &cell)-area);
   146456 }
   146457 
   146458 static RtreeDValue cellOverlap(
   146459   Rtree *pRtree,
   146460   RtreeCell *p,
   146461   RtreeCell *aCell,
   146462   int nCell
   146463 ){
   146464   int ii;
   146465   RtreeDValue overlap = RTREE_ZERO;
   146466   for(ii=0; ii<nCell; ii++){
   146467     int jj;
   146468     RtreeDValue o = (RtreeDValue)1;
   146469     for(jj=0; jj<(pRtree->nDim*2); jj+=2){
   146470       RtreeDValue x1, x2;
   146471       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
   146472       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
   146473       if( x2<x1 ){
   146474         o = (RtreeDValue)0;
   146475         break;
   146476       }else{
   146477         o = o * (x2-x1);
   146478       }
   146479     }
   146480     overlap += o;
   146481   }
   146482   return overlap;
   146483 }
   146484 
   146485 
   146486 /*
   146487 ** This function implements the ChooseLeaf algorithm from Gutman[84].
   146488 ** ChooseSubTree in r*tree terminology.
   146489 */
   146490 static int ChooseLeaf(
   146491   Rtree *pRtree,               /* Rtree table */
   146492   RtreeCell *pCell,            /* Cell to insert into rtree */
   146493   int iHeight,                 /* Height of sub-tree rooted at pCell */
   146494   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
   146495 ){
   146496   int rc;
   146497   int ii;
   146498   RtreeNode *pNode;
   146499   rc = nodeAcquire(pRtree, 1, 0, &pNode);
   146500 
   146501   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
   146502     int iCell;
   146503     sqlite3_int64 iBest = 0;
   146504 
   146505     RtreeDValue fMinGrowth = RTREE_ZERO;
   146506     RtreeDValue fMinArea = RTREE_ZERO;
   146507 
   146508     int nCell = NCELL(pNode);
   146509     RtreeCell cell;
   146510     RtreeNode *pChild;
   146511 
   146512     RtreeCell *aCell = 0;
   146513 
   146514     /* Select the child node which will be enlarged the least if pCell
   146515     ** is inserted into it. Resolve ties by choosing the entry with
   146516     ** the smallest area.
   146517     */
   146518     for(iCell=0; iCell<nCell; iCell++){
   146519       int bBest = 0;
   146520       RtreeDValue growth;
   146521       RtreeDValue area;
   146522       nodeGetCell(pRtree, pNode, iCell, &cell);
   146523       growth = cellGrowth(pRtree, &cell, pCell);
   146524       area = cellArea(pRtree, &cell);
   146525       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
   146526         bBest = 1;
   146527       }
   146528       if( bBest ){
   146529         fMinGrowth = growth;
   146530         fMinArea = area;
   146531         iBest = cell.iRowid;
   146532       }
   146533     }
   146534 
   146535     sqlite3_free(aCell);
   146536     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
   146537     nodeRelease(pRtree, pNode);
   146538     pNode = pChild;
   146539   }
   146540 
   146541   *ppLeaf = pNode;
   146542   return rc;
   146543 }
   146544 
   146545 /*
   146546 ** A cell with the same content as pCell has just been inserted into
   146547 ** the node pNode. This function updates the bounding box cells in
   146548 ** all ancestor elements.
   146549 */
   146550 static int AdjustTree(
   146551   Rtree *pRtree,                    /* Rtree table */
   146552   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
   146553   RtreeCell *pCell                  /* This cell was just inserted */
   146554 ){
   146555   RtreeNode *p = pNode;
   146556   while( p->pParent ){
   146557     RtreeNode *pParent = p->pParent;
   146558     RtreeCell cell;
   146559     int iCell;
   146560 
   146561     if( nodeParentIndex(pRtree, p, &iCell) ){
   146562       return SQLITE_CORRUPT_VTAB;
   146563     }
   146564 
   146565     nodeGetCell(pRtree, pParent, iCell, &cell);
   146566     if( !cellContains(pRtree, &cell, pCell) ){
   146567       cellUnion(pRtree, &cell, pCell);
   146568       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
   146569     }
   146570 
   146571     p = pParent;
   146572   }
   146573   return SQLITE_OK;
   146574 }
   146575 
   146576 /*
   146577 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
   146578 */
   146579 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
   146580   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
   146581   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
   146582   sqlite3_step(pRtree->pWriteRowid);
   146583   return sqlite3_reset(pRtree->pWriteRowid);
   146584 }
   146585 
   146586 /*
   146587 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
   146588 */
   146589 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
   146590   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
   146591   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
   146592   sqlite3_step(pRtree->pWriteParent);
   146593   return sqlite3_reset(pRtree->pWriteParent);
   146594 }
   146595 
   146596 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
   146597 
   146598 
   146599 /*
   146600 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
   146601 ** nIdx. The aIdx array contains the set of integers from 0 to
   146602 ** (nIdx-1) in no particular order. This function sorts the values
   146603 ** in aIdx according to the indexed values in aDistance. For
   146604 ** example, assuming the inputs:
   146605 **
   146606 **   aIdx      = { 0,   1,   2,   3 }
   146607 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
   146608 **
   146609 ** this function sets the aIdx array to contain:
   146610 **
   146611 **   aIdx      = { 0,   1,   2,   3 }
   146612 **
   146613 ** The aSpare array is used as temporary working space by the
   146614 ** sorting algorithm.
   146615 */
   146616 static void SortByDistance(
   146617   int *aIdx,
   146618   int nIdx,
   146619   RtreeDValue *aDistance,
   146620   int *aSpare
   146621 ){
   146622   if( nIdx>1 ){
   146623     int iLeft = 0;
   146624     int iRight = 0;
   146625 
   146626     int nLeft = nIdx/2;
   146627     int nRight = nIdx-nLeft;
   146628     int *aLeft = aIdx;
   146629     int *aRight = &aIdx[nLeft];
   146630 
   146631     SortByDistance(aLeft, nLeft, aDistance, aSpare);
   146632     SortByDistance(aRight, nRight, aDistance, aSpare);
   146633 
   146634     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   146635     aLeft = aSpare;
   146636 
   146637     while( iLeft<nLeft || iRight<nRight ){
   146638       if( iLeft==nLeft ){
   146639         aIdx[iLeft+iRight] = aRight[iRight];
   146640         iRight++;
   146641       }else if( iRight==nRight ){
   146642         aIdx[iLeft+iRight] = aLeft[iLeft];
   146643         iLeft++;
   146644       }else{
   146645         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
   146646         RtreeDValue fRight = aDistance[aRight[iRight]];
   146647         if( fLeft<fRight ){
   146648           aIdx[iLeft+iRight] = aLeft[iLeft];
   146649           iLeft++;
   146650         }else{
   146651           aIdx[iLeft+iRight] = aRight[iRight];
   146652           iRight++;
   146653         }
   146654       }
   146655     }
   146656 
   146657 #if 0
   146658     /* Check that the sort worked */
   146659     {
   146660       int jj;
   146661       for(jj=1; jj<nIdx; jj++){
   146662         RtreeDValue left = aDistance[aIdx[jj-1]];
   146663         RtreeDValue right = aDistance[aIdx[jj]];
   146664         assert( left<=right );
   146665       }
   146666     }
   146667 #endif
   146668   }
   146669 }
   146670 
   146671 /*
   146672 ** Arguments aIdx, aCell and aSpare all point to arrays of size
   146673 ** nIdx. The aIdx array contains the set of integers from 0 to
   146674 ** (nIdx-1) in no particular order. This function sorts the values
   146675 ** in aIdx according to dimension iDim of the cells in aCell. The
   146676 ** minimum value of dimension iDim is considered first, the
   146677 ** maximum used to break ties.
   146678 **
   146679 ** The aSpare array is used as temporary working space by the
   146680 ** sorting algorithm.
   146681 */
   146682 static void SortByDimension(
   146683   Rtree *pRtree,
   146684   int *aIdx,
   146685   int nIdx,
   146686   int iDim,
   146687   RtreeCell *aCell,
   146688   int *aSpare
   146689 ){
   146690   if( nIdx>1 ){
   146691 
   146692     int iLeft = 0;
   146693     int iRight = 0;
   146694 
   146695     int nLeft = nIdx/2;
   146696     int nRight = nIdx-nLeft;
   146697     int *aLeft = aIdx;
   146698     int *aRight = &aIdx[nLeft];
   146699 
   146700     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
   146701     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
   146702 
   146703     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   146704     aLeft = aSpare;
   146705     while( iLeft<nLeft || iRight<nRight ){
   146706       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
   146707       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
   146708       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
   146709       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
   146710       if( (iLeft!=nLeft) && ((iRight==nRight)
   146711        || (xleft1<xright1)
   146712        || (xleft1==xright1 && xleft2<xright2)
   146713       )){
   146714         aIdx[iLeft+iRight] = aLeft[iLeft];
   146715         iLeft++;
   146716       }else{
   146717         aIdx[iLeft+iRight] = aRight[iRight];
   146718         iRight++;
   146719       }
   146720     }
   146721 
   146722 #if 0
   146723     /* Check that the sort worked */
   146724     {
   146725       int jj;
   146726       for(jj=1; jj<nIdx; jj++){
   146727         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
   146728         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
   146729         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
   146730         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
   146731         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
   146732       }
   146733     }
   146734 #endif
   146735   }
   146736 }
   146737 
   146738 /*
   146739 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
   146740 */
   146741 static int splitNodeStartree(
   146742   Rtree *pRtree,
   146743   RtreeCell *aCell,
   146744   int nCell,
   146745   RtreeNode *pLeft,
   146746   RtreeNode *pRight,
   146747   RtreeCell *pBboxLeft,
   146748   RtreeCell *pBboxRight
   146749 ){
   146750   int **aaSorted;
   146751   int *aSpare;
   146752   int ii;
   146753 
   146754   int iBestDim = 0;
   146755   int iBestSplit = 0;
   146756   RtreeDValue fBestMargin = RTREE_ZERO;
   146757 
   146758   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
   146759 
   146760   aaSorted = (int **)sqlite3_malloc(nByte);
   146761   if( !aaSorted ){
   146762     return SQLITE_NOMEM;
   146763   }
   146764 
   146765   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
   146766   memset(aaSorted, 0, nByte);
   146767   for(ii=0; ii<pRtree->nDim; ii++){
   146768     int jj;
   146769     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
   146770     for(jj=0; jj<nCell; jj++){
   146771       aaSorted[ii][jj] = jj;
   146772     }
   146773     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
   146774   }
   146775 
   146776   for(ii=0; ii<pRtree->nDim; ii++){
   146777     RtreeDValue margin = RTREE_ZERO;
   146778     RtreeDValue fBestOverlap = RTREE_ZERO;
   146779     RtreeDValue fBestArea = RTREE_ZERO;
   146780     int iBestLeft = 0;
   146781     int nLeft;
   146782 
   146783     for(
   146784       nLeft=RTREE_MINCELLS(pRtree);
   146785       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
   146786       nLeft++
   146787     ){
   146788       RtreeCell left;
   146789       RtreeCell right;
   146790       int kk;
   146791       RtreeDValue overlap;
   146792       RtreeDValue area;
   146793 
   146794       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
   146795       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
   146796       for(kk=1; kk<(nCell-1); kk++){
   146797         if( kk<nLeft ){
   146798           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
   146799         }else{
   146800           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
   146801         }
   146802       }
   146803       margin += cellMargin(pRtree, &left);
   146804       margin += cellMargin(pRtree, &right);
   146805       overlap = cellOverlap(pRtree, &left, &right, 1);
   146806       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
   146807       if( (nLeft==RTREE_MINCELLS(pRtree))
   146808        || (overlap<fBestOverlap)
   146809        || (overlap==fBestOverlap && area<fBestArea)
   146810       ){
   146811         iBestLeft = nLeft;
   146812         fBestOverlap = overlap;
   146813         fBestArea = area;
   146814       }
   146815     }
   146816 
   146817     if( ii==0 || margin<fBestMargin ){
   146818       iBestDim = ii;
   146819       fBestMargin = margin;
   146820       iBestSplit = iBestLeft;
   146821     }
   146822   }
   146823 
   146824   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
   146825   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
   146826   for(ii=0; ii<nCell; ii++){
   146827     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
   146828     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
   146829     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
   146830     nodeInsertCell(pRtree, pTarget, pCell);
   146831     cellUnion(pRtree, pBbox, pCell);
   146832   }
   146833 
   146834   sqlite3_free(aaSorted);
   146835   return SQLITE_OK;
   146836 }
   146837 
   146838 
   146839 static int updateMapping(
   146840   Rtree *pRtree,
   146841   i64 iRowid,
   146842   RtreeNode *pNode,
   146843   int iHeight
   146844 ){
   146845   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
   146846   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
   146847   if( iHeight>0 ){
   146848     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
   146849     if( pChild ){
   146850       nodeRelease(pRtree, pChild->pParent);
   146851       nodeReference(pNode);
   146852       pChild->pParent = pNode;
   146853     }
   146854   }
   146855   return xSetMapping(pRtree, iRowid, pNode->iNode);
   146856 }
   146857 
   146858 static int SplitNode(
   146859   Rtree *pRtree,
   146860   RtreeNode *pNode,
   146861   RtreeCell *pCell,
   146862   int iHeight
   146863 ){
   146864   int i;
   146865   int newCellIsRight = 0;
   146866 
   146867   int rc = SQLITE_OK;
   146868   int nCell = NCELL(pNode);
   146869   RtreeCell *aCell;
   146870   int *aiUsed;
   146871 
   146872   RtreeNode *pLeft = 0;
   146873   RtreeNode *pRight = 0;
   146874 
   146875   RtreeCell leftbbox;
   146876   RtreeCell rightbbox;
   146877 
   146878   /* Allocate an array and populate it with a copy of pCell and
   146879   ** all cells from node pLeft. Then zero the original node.
   146880   */
   146881   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
   146882   if( !aCell ){
   146883     rc = SQLITE_NOMEM;
   146884     goto splitnode_out;
   146885   }
   146886   aiUsed = (int *)&aCell[nCell+1];
   146887   memset(aiUsed, 0, sizeof(int)*(nCell+1));
   146888   for(i=0; i<nCell; i++){
   146889     nodeGetCell(pRtree, pNode, i, &aCell[i]);
   146890   }
   146891   nodeZero(pRtree, pNode);
   146892   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
   146893   nCell++;
   146894 
   146895   if( pNode->iNode==1 ){
   146896     pRight = nodeNew(pRtree, pNode);
   146897     pLeft = nodeNew(pRtree, pNode);
   146898     pRtree->iDepth++;
   146899     pNode->isDirty = 1;
   146900     writeInt16(pNode->zData, pRtree->iDepth);
   146901   }else{
   146902     pLeft = pNode;
   146903     pRight = nodeNew(pRtree, pLeft->pParent);
   146904     nodeReference(pLeft);
   146905   }
   146906 
   146907   if( !pLeft || !pRight ){
   146908     rc = SQLITE_NOMEM;
   146909     goto splitnode_out;
   146910   }
   146911 
   146912   memset(pLeft->zData, 0, pRtree->iNodeSize);
   146913   memset(pRight->zData, 0, pRtree->iNodeSize);
   146914 
   146915   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
   146916                          &leftbbox, &rightbbox);
   146917   if( rc!=SQLITE_OK ){
   146918     goto splitnode_out;
   146919   }
   146920 
   146921   /* Ensure both child nodes have node numbers assigned to them by calling
   146922   ** nodeWrite(). Node pRight always needs a node number, as it was created
   146923   ** by nodeNew() above. But node pLeft sometimes already has a node number.
   146924   ** In this case avoid the all to nodeWrite().
   146925   */
   146926   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
   146927    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
   146928   ){
   146929     goto splitnode_out;
   146930   }
   146931 
   146932   rightbbox.iRowid = pRight->iNode;
   146933   leftbbox.iRowid = pLeft->iNode;
   146934 
   146935   if( pNode->iNode==1 ){
   146936     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
   146937     if( rc!=SQLITE_OK ){
   146938       goto splitnode_out;
   146939     }
   146940   }else{
   146941     RtreeNode *pParent = pLeft->pParent;
   146942     int iCell;
   146943     rc = nodeParentIndex(pRtree, pLeft, &iCell);
   146944     if( rc==SQLITE_OK ){
   146945       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
   146946       rc = AdjustTree(pRtree, pParent, &leftbbox);
   146947     }
   146948     if( rc!=SQLITE_OK ){
   146949       goto splitnode_out;
   146950     }
   146951   }
   146952   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
   146953     goto splitnode_out;
   146954   }
   146955 
   146956   for(i=0; i<NCELL(pRight); i++){
   146957     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
   146958     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
   146959     if( iRowid==pCell->iRowid ){
   146960       newCellIsRight = 1;
   146961     }
   146962     if( rc!=SQLITE_OK ){
   146963       goto splitnode_out;
   146964     }
   146965   }
   146966   if( pNode->iNode==1 ){
   146967     for(i=0; i<NCELL(pLeft); i++){
   146968       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
   146969       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
   146970       if( rc!=SQLITE_OK ){
   146971         goto splitnode_out;
   146972       }
   146973     }
   146974   }else if( newCellIsRight==0 ){
   146975     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
   146976   }
   146977 
   146978   if( rc==SQLITE_OK ){
   146979     rc = nodeRelease(pRtree, pRight);
   146980     pRight = 0;
   146981   }
   146982   if( rc==SQLITE_OK ){
   146983     rc = nodeRelease(pRtree, pLeft);
   146984     pLeft = 0;
   146985   }
   146986 
   146987 splitnode_out:
   146988   nodeRelease(pRtree, pRight);
   146989   nodeRelease(pRtree, pLeft);
   146990   sqlite3_free(aCell);
   146991   return rc;
   146992 }
   146993 
   146994 /*
   146995 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
   146996 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
   146997 ** the pLeaf->pParent chain all the way up to the root node.
   146998 **
   146999 ** This operation is required when a row is deleted (or updated - an update
   147000 ** is implemented as a delete followed by an insert). SQLite provides the
   147001 ** rowid of the row to delete, which can be used to find the leaf on which
   147002 ** the entry resides (argument pLeaf). Once the leaf is located, this
   147003 ** function is called to determine its ancestry.
   147004 */
   147005 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
   147006   int rc = SQLITE_OK;
   147007   RtreeNode *pChild = pLeaf;
   147008   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
   147009     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
   147010     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
   147011     rc = sqlite3_step(pRtree->pReadParent);
   147012     if( rc==SQLITE_ROW ){
   147013       RtreeNode *pTest;           /* Used to test for reference loops */
   147014       i64 iNode;                  /* Node number of parent node */
   147015 
   147016       /* Before setting pChild->pParent, test that we are not creating a
   147017       ** loop of references (as we would if, say, pChild==pParent). We don't
   147018       ** want to do this as it leads to a memory leak when trying to delete
   147019       ** the referenced counted node structures.
   147020       */
   147021       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
   147022       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
   147023       if( !pTest ){
   147024         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
   147025       }
   147026     }
   147027     rc = sqlite3_reset(pRtree->pReadParent);
   147028     if( rc==SQLITE_OK ) rc = rc2;
   147029     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
   147030     pChild = pChild->pParent;
   147031   }
   147032   return rc;
   147033 }
   147034 
   147035 static int deleteCell(Rtree *, RtreeNode *, int, int);
   147036 
   147037 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
   147038   int rc;
   147039   int rc2;
   147040   RtreeNode *pParent = 0;
   147041   int iCell;
   147042 
   147043   assert( pNode->nRef==1 );
   147044 
   147045   /* Remove the entry in the parent cell. */
   147046   rc = nodeParentIndex(pRtree, pNode, &iCell);
   147047   if( rc==SQLITE_OK ){
   147048     pParent = pNode->pParent;
   147049     pNode->pParent = 0;
   147050     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
   147051   }
   147052   rc2 = nodeRelease(pRtree, pParent);
   147053   if( rc==SQLITE_OK ){
   147054     rc = rc2;
   147055   }
   147056   if( rc!=SQLITE_OK ){
   147057     return rc;
   147058   }
   147059 
   147060   /* Remove the xxx_node entry. */
   147061   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
   147062   sqlite3_step(pRtree->pDeleteNode);
   147063   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
   147064     return rc;
   147065   }
   147066 
   147067   /* Remove the xxx_parent entry. */
   147068   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
   147069   sqlite3_step(pRtree->pDeleteParent);
   147070   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
   147071     return rc;
   147072   }
   147073 
   147074   /* Remove the node from the in-memory hash table and link it into
   147075   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
   147076   */
   147077   nodeHashDelete(pRtree, pNode);
   147078   pNode->iNode = iHeight;
   147079   pNode->pNext = pRtree->pDeleted;
   147080   pNode->nRef++;
   147081   pRtree->pDeleted = pNode;
   147082 
   147083   return SQLITE_OK;
   147084 }
   147085 
   147086 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
   147087   RtreeNode *pParent = pNode->pParent;
   147088   int rc = SQLITE_OK;
   147089   if( pParent ){
   147090     int ii;
   147091     int nCell = NCELL(pNode);
   147092     RtreeCell box;                            /* Bounding box for pNode */
   147093     nodeGetCell(pRtree, pNode, 0, &box);
   147094     for(ii=1; ii<nCell; ii++){
   147095       RtreeCell cell;
   147096       nodeGetCell(pRtree, pNode, ii, &cell);
   147097       cellUnion(pRtree, &box, &cell);
   147098     }
   147099     box.iRowid = pNode->iNode;
   147100     rc = nodeParentIndex(pRtree, pNode, &ii);
   147101     if( rc==SQLITE_OK ){
   147102       nodeOverwriteCell(pRtree, pParent, &box, ii);
   147103       rc = fixBoundingBox(pRtree, pParent);
   147104     }
   147105   }
   147106   return rc;
   147107 }
   147108 
   147109 /*
   147110 ** Delete the cell at index iCell of node pNode. After removing the
   147111 ** cell, adjust the r-tree data structure if required.
   147112 */
   147113 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
   147114   RtreeNode *pParent;
   147115   int rc;
   147116 
   147117   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
   147118     return rc;
   147119   }
   147120 
   147121   /* Remove the cell from the node. This call just moves bytes around
   147122   ** the in-memory node image, so it cannot fail.
   147123   */
   147124   nodeDeleteCell(pRtree, pNode, iCell);
   147125 
   147126   /* If the node is not the tree root and now has less than the minimum
   147127   ** number of cells, remove it from the tree. Otherwise, update the
   147128   ** cell in the parent node so that it tightly contains the updated
   147129   ** node.
   147130   */
   147131   pParent = pNode->pParent;
   147132   assert( pParent || pNode->iNode==1 );
   147133   if( pParent ){
   147134     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
   147135       rc = removeNode(pRtree, pNode, iHeight);
   147136     }else{
   147137       rc = fixBoundingBox(pRtree, pNode);
   147138     }
   147139   }
   147140 
   147141   return rc;
   147142 }
   147143 
   147144 static int Reinsert(
   147145   Rtree *pRtree,
   147146   RtreeNode *pNode,
   147147   RtreeCell *pCell,
   147148   int iHeight
   147149 ){
   147150   int *aOrder;
   147151   int *aSpare;
   147152   RtreeCell *aCell;
   147153   RtreeDValue *aDistance;
   147154   int nCell;
   147155   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
   147156   int iDim;
   147157   int ii;
   147158   int rc = SQLITE_OK;
   147159   int n;
   147160 
   147161   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
   147162 
   147163   nCell = NCELL(pNode)+1;
   147164   n = (nCell+1)&(~1);
   147165 
   147166   /* Allocate the buffers used by this operation. The allocation is
   147167   ** relinquished before this function returns.
   147168   */
   147169   aCell = (RtreeCell *)sqlite3_malloc(n * (
   147170     sizeof(RtreeCell)     +         /* aCell array */
   147171     sizeof(int)           +         /* aOrder array */
   147172     sizeof(int)           +         /* aSpare array */
   147173     sizeof(RtreeDValue)             /* aDistance array */
   147174   ));
   147175   if( !aCell ){
   147176     return SQLITE_NOMEM;
   147177   }
   147178   aOrder    = (int *)&aCell[n];
   147179   aSpare    = (int *)&aOrder[n];
   147180   aDistance = (RtreeDValue *)&aSpare[n];
   147181 
   147182   for(ii=0; ii<nCell; ii++){
   147183     if( ii==(nCell-1) ){
   147184       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
   147185     }else{
   147186       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
   147187     }
   147188     aOrder[ii] = ii;
   147189     for(iDim=0; iDim<pRtree->nDim; iDim++){
   147190       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
   147191       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
   147192     }
   147193   }
   147194   for(iDim=0; iDim<pRtree->nDim; iDim++){
   147195     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
   147196   }
   147197 
   147198   for(ii=0; ii<nCell; ii++){
   147199     aDistance[ii] = RTREE_ZERO;
   147200     for(iDim=0; iDim<pRtree->nDim; iDim++){
   147201       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
   147202                                DCOORD(aCell[ii].aCoord[iDim*2]));
   147203       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
   147204     }
   147205   }
   147206 
   147207   SortByDistance(aOrder, nCell, aDistance, aSpare);
   147208   nodeZero(pRtree, pNode);
   147209 
   147210   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
   147211     RtreeCell *p = &aCell[aOrder[ii]];
   147212     nodeInsertCell(pRtree, pNode, p);
   147213     if( p->iRowid==pCell->iRowid ){
   147214       if( iHeight==0 ){
   147215         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
   147216       }else{
   147217         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
   147218       }
   147219     }
   147220   }
   147221   if( rc==SQLITE_OK ){
   147222     rc = fixBoundingBox(pRtree, pNode);
   147223   }
   147224   for(; rc==SQLITE_OK && ii<nCell; ii++){
   147225     /* Find a node to store this cell in. pNode->iNode currently contains
   147226     ** the height of the sub-tree headed by the cell.
   147227     */
   147228     RtreeNode *pInsert;
   147229     RtreeCell *p = &aCell[aOrder[ii]];
   147230     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
   147231     if( rc==SQLITE_OK ){
   147232       int rc2;
   147233       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
   147234       rc2 = nodeRelease(pRtree, pInsert);
   147235       if( rc==SQLITE_OK ){
   147236         rc = rc2;
   147237       }
   147238     }
   147239   }
   147240 
   147241   sqlite3_free(aCell);
   147242   return rc;
   147243 }
   147244 
   147245 /*
   147246 ** Insert cell pCell into node pNode. Node pNode is the head of a
   147247 ** subtree iHeight high (leaf nodes have iHeight==0).
   147248 */
   147249 static int rtreeInsertCell(
   147250   Rtree *pRtree,
   147251   RtreeNode *pNode,
   147252   RtreeCell *pCell,
   147253   int iHeight
   147254 ){
   147255   int rc = SQLITE_OK;
   147256   if( iHeight>0 ){
   147257     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
   147258     if( pChild ){
   147259       nodeRelease(pRtree, pChild->pParent);
   147260       nodeReference(pNode);
   147261       pChild->pParent = pNode;
   147262     }
   147263   }
   147264   if( nodeInsertCell(pRtree, pNode, pCell) ){
   147265     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
   147266       rc = SplitNode(pRtree, pNode, pCell, iHeight);
   147267     }else{
   147268       pRtree->iReinsertHeight = iHeight;
   147269       rc = Reinsert(pRtree, pNode, pCell, iHeight);
   147270     }
   147271   }else{
   147272     rc = AdjustTree(pRtree, pNode, pCell);
   147273     if( rc==SQLITE_OK ){
   147274       if( iHeight==0 ){
   147275         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
   147276       }else{
   147277         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
   147278       }
   147279     }
   147280   }
   147281   return rc;
   147282 }
   147283 
   147284 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
   147285   int ii;
   147286   int rc = SQLITE_OK;
   147287   int nCell = NCELL(pNode);
   147288 
   147289   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
   147290     RtreeNode *pInsert;
   147291     RtreeCell cell;
   147292     nodeGetCell(pRtree, pNode, ii, &cell);
   147293 
   147294     /* Find a node to store this cell in. pNode->iNode currently contains
   147295     ** the height of the sub-tree headed by the cell.
   147296     */
   147297     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
   147298     if( rc==SQLITE_OK ){
   147299       int rc2;
   147300       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
   147301       rc2 = nodeRelease(pRtree, pInsert);
   147302       if( rc==SQLITE_OK ){
   147303         rc = rc2;
   147304       }
   147305     }
   147306   }
   147307   return rc;
   147308 }
   147309 
   147310 /*
   147311 ** Select a currently unused rowid for a new r-tree record.
   147312 */
   147313 static int newRowid(Rtree *pRtree, i64 *piRowid){
   147314   int rc;
   147315   sqlite3_bind_null(pRtree->pWriteRowid, 1);
   147316   sqlite3_bind_null(pRtree->pWriteRowid, 2);
   147317   sqlite3_step(pRtree->pWriteRowid);
   147318   rc = sqlite3_reset(pRtree->pWriteRowid);
   147319   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
   147320   return rc;
   147321 }
   147322 
   147323 /*
   147324 ** Remove the entry with rowid=iDelete from the r-tree structure.
   147325 */
   147326 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
   147327   int rc;                         /* Return code */
   147328   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
   147329   int iCell;                      /* Index of iDelete cell in pLeaf */
   147330   RtreeNode *pRoot;               /* Root node of rtree structure */
   147331 
   147332 
   147333   /* Obtain a reference to the root node to initialize Rtree.iDepth */
   147334   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   147335 
   147336   /* Obtain a reference to the leaf node that contains the entry
   147337   ** about to be deleted.
   147338   */
   147339   if( rc==SQLITE_OK ){
   147340     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
   147341   }
   147342 
   147343   /* Delete the cell in question from the leaf node. */
   147344   if( rc==SQLITE_OK ){
   147345     int rc2;
   147346     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
   147347     if( rc==SQLITE_OK ){
   147348       rc = deleteCell(pRtree, pLeaf, iCell, 0);
   147349     }
   147350     rc2 = nodeRelease(pRtree, pLeaf);
   147351     if( rc==SQLITE_OK ){
   147352       rc = rc2;
   147353     }
   147354   }
   147355 
   147356   /* Delete the corresponding entry in the <rtree>_rowid table. */
   147357   if( rc==SQLITE_OK ){
   147358     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
   147359     sqlite3_step(pRtree->pDeleteRowid);
   147360     rc = sqlite3_reset(pRtree->pDeleteRowid);
   147361   }
   147362 
   147363   /* Check if the root node now has exactly one child. If so, remove
   147364   ** it, schedule the contents of the child for reinsertion and
   147365   ** reduce the tree height by one.
   147366   **
   147367   ** This is equivalent to copying the contents of the child into
   147368   ** the root node (the operation that Gutman's paper says to perform
   147369   ** in this scenario).
   147370   */
   147371   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
   147372     int rc2;
   147373     RtreeNode *pChild;
   147374     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
   147375     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
   147376     if( rc==SQLITE_OK ){
   147377       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
   147378     }
   147379     rc2 = nodeRelease(pRtree, pChild);
   147380     if( rc==SQLITE_OK ) rc = rc2;
   147381     if( rc==SQLITE_OK ){
   147382       pRtree->iDepth--;
   147383       writeInt16(pRoot->zData, pRtree->iDepth);
   147384       pRoot->isDirty = 1;
   147385     }
   147386   }
   147387 
   147388   /* Re-insert the contents of any underfull nodes removed from the tree. */
   147389   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
   147390     if( rc==SQLITE_OK ){
   147391       rc = reinsertNodeContent(pRtree, pLeaf);
   147392     }
   147393     pRtree->pDeleted = pLeaf->pNext;
   147394     sqlite3_free(pLeaf);
   147395   }
   147396 
   147397   /* Release the reference to the root node. */
   147398   if( rc==SQLITE_OK ){
   147399     rc = nodeRelease(pRtree, pRoot);
   147400   }else{
   147401     nodeRelease(pRtree, pRoot);
   147402   }
   147403 
   147404   return rc;
   147405 }
   147406 
   147407 /*
   147408 ** Rounding constants for float->double conversion.
   147409 */
   147410 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
   147411 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
   147412 
   147413 #if !defined(SQLITE_RTREE_INT_ONLY)
   147414 /*
   147415 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
   147416 ** while taking care to round toward negative or positive, respectively.
   147417 */
   147418 static RtreeValue rtreeValueDown(sqlite3_value *v){
   147419   double d = sqlite3_value_double(v);
   147420   float f = (float)d;
   147421   if( f>d ){
   147422     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
   147423   }
   147424   return f;
   147425 }
   147426 static RtreeValue rtreeValueUp(sqlite3_value *v){
   147427   double d = sqlite3_value_double(v);
   147428   float f = (float)d;
   147429   if( f<d ){
   147430     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
   147431   }
   147432   return f;
   147433 }
   147434 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
   147435 
   147436 
   147437 /*
   147438 ** The xUpdate method for rtree module virtual tables.
   147439 */
   147440 static int rtreeUpdate(
   147441   sqlite3_vtab *pVtab,
   147442   int nData,
   147443   sqlite3_value **azData,
   147444   sqlite_int64 *pRowid
   147445 ){
   147446   Rtree *pRtree = (Rtree *)pVtab;
   147447   int rc = SQLITE_OK;
   147448   RtreeCell cell;                 /* New cell to insert if nData>1 */
   147449   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
   147450 
   147451   rtreeReference(pRtree);
   147452   assert(nData>=1);
   147453 
   147454   /* Constraint handling. A write operation on an r-tree table may return
   147455   ** SQLITE_CONSTRAINT for two reasons:
   147456   **
   147457   **   1. A duplicate rowid value, or
   147458   **   2. The supplied data violates the "x2>=x1" constraint.
   147459   **
   147460   ** In the first case, if the conflict-handling mode is REPLACE, then
   147461   ** the conflicting row can be removed before proceeding. In the second
   147462   ** case, SQLITE_CONSTRAINT must be returned regardless of the
   147463   ** conflict-handling mode specified by the user.
   147464   */
   147465   if( nData>1 ){
   147466     int ii;
   147467 
   147468     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
   147469     assert( nData==(pRtree->nDim*2 + 3) );
   147470 #ifndef SQLITE_RTREE_INT_ONLY
   147471     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   147472       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   147473         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
   147474         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
   147475         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
   147476           rc = SQLITE_CONSTRAINT;
   147477           goto constraint;
   147478         }
   147479       }
   147480     }else
   147481 #endif
   147482     {
   147483       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   147484         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
   147485         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
   147486         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
   147487           rc = SQLITE_CONSTRAINT;
   147488           goto constraint;
   147489         }
   147490       }
   147491     }
   147492 
   147493     /* If a rowid value was supplied, check if it is already present in
   147494     ** the table. If so, the constraint has failed. */
   147495     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
   147496       cell.iRowid = sqlite3_value_int64(azData[2]);
   147497       if( sqlite3_value_type(azData[0])==SQLITE_NULL
   147498        || sqlite3_value_int64(azData[0])!=cell.iRowid
   147499       ){
   147500         int steprc;
   147501         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
   147502         steprc = sqlite3_step(pRtree->pReadRowid);
   147503         rc = sqlite3_reset(pRtree->pReadRowid);
   147504         if( SQLITE_ROW==steprc ){
   147505           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
   147506             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
   147507           }else{
   147508             rc = SQLITE_CONSTRAINT;
   147509             goto constraint;
   147510           }
   147511         }
   147512       }
   147513       bHaveRowid = 1;
   147514     }
   147515   }
   147516 
   147517   /* If azData[0] is not an SQL NULL value, it is the rowid of a
   147518   ** record to delete from the r-tree table. The following block does
   147519   ** just that.
   147520   */
   147521   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
   147522     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
   147523   }
   147524 
   147525   /* If the azData[] array contains more than one element, elements
   147526   ** (azData[2]..azData[argc-1]) contain a new record to insert into
   147527   ** the r-tree structure.
   147528   */
   147529   if( rc==SQLITE_OK && nData>1 ){
   147530     /* Insert the new record into the r-tree */
   147531     RtreeNode *pLeaf = 0;
   147532 
   147533     /* Figure out the rowid of the new row. */
   147534     if( bHaveRowid==0 ){
   147535       rc = newRowid(pRtree, &cell.iRowid);
   147536     }
   147537     *pRowid = cell.iRowid;
   147538 
   147539     if( rc==SQLITE_OK ){
   147540       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
   147541     }
   147542     if( rc==SQLITE_OK ){
   147543       int rc2;
   147544       pRtree->iReinsertHeight = -1;
   147545       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
   147546       rc2 = nodeRelease(pRtree, pLeaf);
   147547       if( rc==SQLITE_OK ){
   147548         rc = rc2;
   147549       }
   147550     }
   147551   }
   147552 
   147553 constraint:
   147554   rtreeRelease(pRtree);
   147555   return rc;
   147556 }
   147557 
   147558 /*
   147559 ** The xRename method for rtree module virtual tables.
   147560 */
   147561 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
   147562   Rtree *pRtree = (Rtree *)pVtab;
   147563   int rc = SQLITE_NOMEM;
   147564   char *zSql = sqlite3_mprintf(
   147565     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
   147566     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
   147567     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
   147568     , pRtree->zDb, pRtree->zName, zNewName
   147569     , pRtree->zDb, pRtree->zName, zNewName
   147570     , pRtree->zDb, pRtree->zName, zNewName
   147571   );
   147572   if( zSql ){
   147573     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
   147574     sqlite3_free(zSql);
   147575   }
   147576   return rc;
   147577 }
   147578 
   147579 /*
   147580 ** This function populates the pRtree->nRowEst variable with an estimate
   147581 ** of the number of rows in the virtual table. If possible, this is based
   147582 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
   147583 */
   147584 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
   147585   const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
   147586   char *zSql;
   147587   sqlite3_stmt *p;
   147588   int rc;
   147589   i64 nRow = 0;
   147590 
   147591   zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
   147592   if( zSql==0 ){
   147593     rc = SQLITE_NOMEM;
   147594   }else{
   147595     rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
   147596     if( rc==SQLITE_OK ){
   147597       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
   147598       rc = sqlite3_finalize(p);
   147599     }else if( rc!=SQLITE_NOMEM ){
   147600       rc = SQLITE_OK;
   147601     }
   147602 
   147603     if( rc==SQLITE_OK ){
   147604       if( nRow==0 ){
   147605         pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
   147606       }else{
   147607         pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
   147608       }
   147609     }
   147610     sqlite3_free(zSql);
   147611   }
   147612 
   147613   return rc;
   147614 }
   147615 
   147616 static sqlite3_module rtreeModule = {
   147617   0,                          /* iVersion */
   147618   rtreeCreate,                /* xCreate - create a table */
   147619   rtreeConnect,               /* xConnect - connect to an existing table */
   147620   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
   147621   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
   147622   rtreeDestroy,               /* xDestroy - Drop a table */
   147623   rtreeOpen,                  /* xOpen - open a cursor */
   147624   rtreeClose,                 /* xClose - close a cursor */
   147625   rtreeFilter,                /* xFilter - configure scan constraints */
   147626   rtreeNext,                  /* xNext - advance a cursor */
   147627   rtreeEof,                   /* xEof */
   147628   rtreeColumn,                /* xColumn - read data */
   147629   rtreeRowid,                 /* xRowid - read data */
   147630   rtreeUpdate,                /* xUpdate - write data */
   147631   0,                          /* xBegin - begin transaction */
   147632   0,                          /* xSync - sync transaction */
   147633   0,                          /* xCommit - commit transaction */
   147634   0,                          /* xRollback - rollback transaction */
   147635   0,                          /* xFindFunction - function overloading */
   147636   rtreeRename,                /* xRename - rename the table */
   147637   0,                          /* xSavepoint */
   147638   0,                          /* xRelease */
   147639   0                           /* xRollbackTo */
   147640 };
   147641 
   147642 static int rtreeSqlInit(
   147643   Rtree *pRtree,
   147644   sqlite3 *db,
   147645   const char *zDb,
   147646   const char *zPrefix,
   147647   int isCreate
   147648 ){
   147649   int rc = SQLITE_OK;
   147650 
   147651   #define N_STATEMENT 9
   147652   static const char *azSql[N_STATEMENT] = {
   147653     /* Read and write the xxx_node table */
   147654     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
   147655     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
   147656     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
   147657 
   147658     /* Read and write the xxx_rowid table */
   147659     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
   147660     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
   147661     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
   147662 
   147663     /* Read and write the xxx_parent table */
   147664     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
   147665     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
   147666     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
   147667   };
   147668   sqlite3_stmt **appStmt[N_STATEMENT];
   147669   int i;
   147670 
   147671   pRtree->db = db;
   147672 
   147673   if( isCreate ){
   147674     char *zCreate = sqlite3_mprintf(
   147675 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
   147676 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
   147677 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
   147678                                   " parentnode INTEGER);"
   147679 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
   147680       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
   147681     );
   147682     if( !zCreate ){
   147683       return SQLITE_NOMEM;
   147684     }
   147685     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
   147686     sqlite3_free(zCreate);
   147687     if( rc!=SQLITE_OK ){
   147688       return rc;
   147689     }
   147690   }
   147691 
   147692   appStmt[0] = &pRtree->pReadNode;
   147693   appStmt[1] = &pRtree->pWriteNode;
   147694   appStmt[2] = &pRtree->pDeleteNode;
   147695   appStmt[3] = &pRtree->pReadRowid;
   147696   appStmt[4] = &pRtree->pWriteRowid;
   147697   appStmt[5] = &pRtree->pDeleteRowid;
   147698   appStmt[6] = &pRtree->pReadParent;
   147699   appStmt[7] = &pRtree->pWriteParent;
   147700   appStmt[8] = &pRtree->pDeleteParent;
   147701 
   147702   rc = rtreeQueryStat1(db, pRtree);
   147703   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
   147704     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
   147705     if( zSql ){
   147706       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
   147707     }else{
   147708       rc = SQLITE_NOMEM;
   147709     }
   147710     sqlite3_free(zSql);
   147711   }
   147712 
   147713   return rc;
   147714 }
   147715 
   147716 /*
   147717 ** The second argument to this function contains the text of an SQL statement
   147718 ** that returns a single integer value. The statement is compiled and executed
   147719 ** using database connection db. If successful, the integer value returned
   147720 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
   147721 ** code is returned and the value of *piVal after returning is not defined.
   147722 */
   147723 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
   147724   int rc = SQLITE_NOMEM;
   147725   if( zSql ){
   147726     sqlite3_stmt *pStmt = 0;
   147727     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   147728     if( rc==SQLITE_OK ){
   147729       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   147730         *piVal = sqlite3_column_int(pStmt, 0);
   147731       }
   147732       rc = sqlite3_finalize(pStmt);
   147733     }
   147734   }
   147735   return rc;
   147736 }
   147737 
   147738 /*
   147739 ** This function is called from within the xConnect() or xCreate() method to
   147740 ** determine the node-size used by the rtree table being created or connected
   147741 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
   147742 ** Otherwise, an SQLite error code is returned.
   147743 **
   147744 ** If this function is being called as part of an xConnect(), then the rtree
   147745 ** table already exists. In this case the node-size is determined by inspecting
   147746 ** the root node of the tree.
   147747 **
   147748 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
   147749 ** This ensures that each node is stored on a single database page. If the
   147750 ** database page-size is so large that more than RTREE_MAXCELLS entries
   147751 ** would fit in a single node, use a smaller node-size.
   147752 */
   147753 static int getNodeSize(
   147754   sqlite3 *db,                    /* Database handle */
   147755   Rtree *pRtree,                  /* Rtree handle */
   147756   int isCreate,                   /* True for xCreate, false for xConnect */
   147757   char **pzErr                    /* OUT: Error message, if any */
   147758 ){
   147759   int rc;
   147760   char *zSql;
   147761   if( isCreate ){
   147762     int iPageSize = 0;
   147763     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
   147764     rc = getIntFromStmt(db, zSql, &iPageSize);
   147765     if( rc==SQLITE_OK ){
   147766       pRtree->iNodeSize = iPageSize-64;
   147767       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
   147768         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
   147769       }
   147770     }else{
   147771       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   147772     }
   147773   }else{
   147774     zSql = sqlite3_mprintf(
   147775         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
   147776         pRtree->zDb, pRtree->zName
   147777     );
   147778     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
   147779     if( rc!=SQLITE_OK ){
   147780       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   147781     }
   147782   }
   147783 
   147784   sqlite3_free(zSql);
   147785   return rc;
   147786 }
   147787 
   147788 /*
   147789 ** This function is the implementation of both the xConnect and xCreate
   147790 ** methods of the r-tree virtual table.
   147791 **
   147792 **   argv[0]   -> module name
   147793 **   argv[1]   -> database name
   147794 **   argv[2]   -> table name
   147795 **   argv[...] -> column names...
   147796 */
   147797 static int rtreeInit(
   147798   sqlite3 *db,                        /* Database connection */
   147799   void *pAux,                         /* One of the RTREE_COORD_* constants */
   147800   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
   147801   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
   147802   char **pzErr,                       /* OUT: Error message, if any */
   147803   int isCreate                        /* True for xCreate, false for xConnect */
   147804 ){
   147805   int rc = SQLITE_OK;
   147806   Rtree *pRtree;
   147807   int nDb;              /* Length of string argv[1] */
   147808   int nName;            /* Length of string argv[2] */
   147809   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
   147810 
   147811   const char *aErrMsg[] = {
   147812     0,                                                    /* 0 */
   147813     "Wrong number of columns for an rtree table",         /* 1 */
   147814     "Too few columns for an rtree table",                 /* 2 */
   147815     "Too many columns for an rtree table"                 /* 3 */
   147816   };
   147817 
   147818   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
   147819   if( aErrMsg[iErr] ){
   147820     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
   147821     return SQLITE_ERROR;
   147822   }
   147823 
   147824   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   147825 
   147826   /* Allocate the sqlite3_vtab structure */
   147827   nDb = (int)strlen(argv[1]);
   147828   nName = (int)strlen(argv[2]);
   147829   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
   147830   if( !pRtree ){
   147831     return SQLITE_NOMEM;
   147832   }
   147833   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
   147834   pRtree->nBusy = 1;
   147835   pRtree->base.pModule = &rtreeModule;
   147836   pRtree->zDb = (char *)&pRtree[1];
   147837   pRtree->zName = &pRtree->zDb[nDb+1];
   147838   pRtree->nDim = (argc-4)/2;
   147839   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
   147840   pRtree->eCoordType = eCoordType;
   147841   memcpy(pRtree->zDb, argv[1], nDb);
   147842   memcpy(pRtree->zName, argv[2], nName);
   147843 
   147844   /* Figure out the node size to use. */
   147845   rc = getNodeSize(db, pRtree, isCreate, pzErr);
   147846 
   147847   /* Create/Connect to the underlying relational database schema. If
   147848   ** that is successful, call sqlite3_declare_vtab() to configure
   147849   ** the r-tree table schema.
   147850   */
   147851   if( rc==SQLITE_OK ){
   147852     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
   147853       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   147854     }else{
   147855       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
   147856       char *zTmp;
   147857       int ii;
   147858       for(ii=4; zSql && ii<argc; ii++){
   147859         zTmp = zSql;
   147860         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
   147861         sqlite3_free(zTmp);
   147862       }
   147863       if( zSql ){
   147864         zTmp = zSql;
   147865         zSql = sqlite3_mprintf("%s);", zTmp);
   147866         sqlite3_free(zTmp);
   147867       }
   147868       if( !zSql ){
   147869         rc = SQLITE_NOMEM;
   147870       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
   147871         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   147872       }
   147873       sqlite3_free(zSql);
   147874     }
   147875   }
   147876 
   147877   if( rc==SQLITE_OK ){
   147878     *ppVtab = (sqlite3_vtab *)pRtree;
   147879   }else{
   147880     assert( *ppVtab==0 );
   147881     assert( pRtree->nBusy==1 );
   147882     rtreeRelease(pRtree);
   147883   }
   147884   return rc;
   147885 }
   147886 
   147887 
   147888 /*
   147889 ** Implementation of a scalar function that decodes r-tree nodes to
   147890 ** human readable strings. This can be used for debugging and analysis.
   147891 **
   147892 ** The scalar function takes two arguments: (1) the number of dimensions
   147893 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
   147894 ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
   147895 ** deserialize all nodes, a statement like:
   147896 **
   147897 **   SELECT rtreenode(2, data) FROM rt_node;
   147898 **
   147899 ** The human readable string takes the form of a Tcl list with one
   147900 ** entry for each cell in the r-tree node. Each entry is itself a
   147901 ** list, containing the 8-byte rowid/pageno followed by the
   147902 ** <num-dimension>*2 coordinates.
   147903 */
   147904 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   147905   char *zText = 0;
   147906   RtreeNode node;
   147907   Rtree tree;
   147908   int ii;
   147909 
   147910   UNUSED_PARAMETER(nArg);
   147911   memset(&node, 0, sizeof(RtreeNode));
   147912   memset(&tree, 0, sizeof(Rtree));
   147913   tree.nDim = sqlite3_value_int(apArg[0]);
   147914   tree.nBytesPerCell = 8 + 8 * tree.nDim;
   147915   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
   147916 
   147917   for(ii=0; ii<NCELL(&node); ii++){
   147918     char zCell[512];
   147919     int nCell = 0;
   147920     RtreeCell cell;
   147921     int jj;
   147922 
   147923     nodeGetCell(&tree, &node, ii, &cell);
   147924     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
   147925     nCell = (int)strlen(zCell);
   147926     for(jj=0; jj<tree.nDim*2; jj++){
   147927 #ifndef SQLITE_RTREE_INT_ONLY
   147928       sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
   147929                        (double)cell.aCoord[jj].f);
   147930 #else
   147931       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
   147932                        cell.aCoord[jj].i);
   147933 #endif
   147934       nCell = (int)strlen(zCell);
   147935     }
   147936 
   147937     if( zText ){
   147938       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
   147939       sqlite3_free(zText);
   147940       zText = zTextNew;
   147941     }else{
   147942       zText = sqlite3_mprintf("{%s}", zCell);
   147943     }
   147944   }
   147945 
   147946   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
   147947 }
   147948 
   147949 /* This routine implements an SQL function that returns the "depth" parameter
   147950 ** from the front of a blob that is an r-tree node.  For example:
   147951 **
   147952 **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
   147953 **
   147954 ** The depth value is 0 for all nodes other than the root node, and the root
   147955 ** node always has nodeno=1, so the example above is the primary use for this
   147956 ** routine.  This routine is intended for testing and analysis only.
   147957 */
   147958 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   147959   UNUSED_PARAMETER(nArg);
   147960   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
   147961    || sqlite3_value_bytes(apArg[0])<2
   147962   ){
   147963     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   147964   }else{
   147965     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
   147966     sqlite3_result_int(ctx, readInt16(zBlob));
   147967   }
   147968 }
   147969 
   147970 /*
   147971 ** Register the r-tree module with database handle db. This creates the
   147972 ** virtual table module "rtree" and the debugging/analysis scalar
   147973 ** function "rtreenode".
   147974 */
   147975 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
   147976   const int utf8 = SQLITE_UTF8;
   147977   int rc;
   147978 
   147979   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
   147980   if( rc==SQLITE_OK ){
   147981     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
   147982   }
   147983   if( rc==SQLITE_OK ){
   147984 #ifdef SQLITE_RTREE_INT_ONLY
   147985     void *c = (void *)RTREE_COORD_INT32;
   147986 #else
   147987     void *c = (void *)RTREE_COORD_REAL32;
   147988 #endif
   147989     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
   147990   }
   147991   if( rc==SQLITE_OK ){
   147992     void *c = (void *)RTREE_COORD_INT32;
   147993     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
   147994   }
   147995 
   147996   return rc;
   147997 }
   147998 
   147999 /*
   148000 ** This routine deletes the RtreeGeomCallback object that was attached
   148001 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
   148002 ** or sqlite3_rtree_query_callback().  In other words, this routine is the
   148003 ** destructor for an RtreeGeomCallback objecct.  This routine is called when
   148004 ** the corresponding SQL function is deleted.
   148005 */
   148006 static void rtreeFreeCallback(void *p){
   148007   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
   148008   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
   148009   sqlite3_free(p);
   148010 }
   148011 
   148012 /*
   148013 ** Each call to sqlite3_rtree_geometry_callback() or
   148014 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
   148015 ** scalar function that is implemented by this routine.
   148016 **
   148017 ** All this function does is construct an RtreeMatchArg object that
   148018 ** contains the geometry-checking callback routines and a list of
   148019 ** parameters to this function, then return that RtreeMatchArg object
   148020 ** as a BLOB.
   148021 **
   148022 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
   148023 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
   148024 ** out which elements of the R-Tree should be returned by the query.
   148025 */
   148026 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
   148027   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
   148028   RtreeMatchArg *pBlob;
   148029   int nBlob;
   148030 
   148031   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
   148032   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
   148033   if( !pBlob ){
   148034     sqlite3_result_error_nomem(ctx);
   148035   }else{
   148036     int i;
   148037     pBlob->magic = RTREE_GEOMETRY_MAGIC;
   148038     pBlob->cb = pGeomCtx[0];
   148039     pBlob->nParam = nArg;
   148040     for(i=0; i<nArg; i++){
   148041 #ifdef SQLITE_RTREE_INT_ONLY
   148042       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
   148043 #else
   148044       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
   148045 #endif
   148046     }
   148047     sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
   148048   }
   148049 }
   148050 
   148051 /*
   148052 ** Register a new geometry function for use with the r-tree MATCH operator.
   148053 */
   148054 SQLITE_API int sqlite3_rtree_geometry_callback(
   148055   sqlite3 *db,                  /* Register SQL function on this connection */
   148056   const char *zGeom,            /* Name of the new SQL function */
   148057   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
   148058   void *pContext                /* Extra data associated with the callback */
   148059 ){
   148060   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   148061 
   148062   /* Allocate and populate the context object. */
   148063   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   148064   if( !pGeomCtx ) return SQLITE_NOMEM;
   148065   pGeomCtx->xGeom = xGeom;
   148066   pGeomCtx->xQueryFunc = 0;
   148067   pGeomCtx->xDestructor = 0;
   148068   pGeomCtx->pContext = pContext;
   148069   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
   148070       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
   148071   );
   148072 }
   148073 
   148074 /*
   148075 ** Register a new 2nd-generation geometry function for use with the
   148076 ** r-tree MATCH operator.
   148077 */
   148078 SQLITE_API int sqlite3_rtree_query_callback(
   148079   sqlite3 *db,                 /* Register SQL function on this connection */
   148080   const char *zQueryFunc,      /* Name of new SQL function */
   148081   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
   148082   void *pContext,              /* Extra data passed into the callback */
   148083   void (*xDestructor)(void*)   /* Destructor for the extra data */
   148084 ){
   148085   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   148086 
   148087   /* Allocate and populate the context object. */
   148088   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   148089   if( !pGeomCtx ) return SQLITE_NOMEM;
   148090   pGeomCtx->xGeom = 0;
   148091   pGeomCtx->xQueryFunc = xQueryFunc;
   148092   pGeomCtx->xDestructor = xDestructor;
   148093   pGeomCtx->pContext = pContext;
   148094   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
   148095       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
   148096   );
   148097 }
   148098 
   148099 #if !SQLITE_CORE
   148100 #ifdef _WIN32
   148101 __declspec(dllexport)
   148102 #endif
   148103 SQLITE_API int sqlite3_rtree_init(
   148104   sqlite3 *db,
   148105   char **pzErrMsg,
   148106   const sqlite3_api_routines *pApi
   148107 ){
   148108   SQLITE_EXTENSION_INIT2(pApi)
   148109   return sqlite3RtreeInit(db);
   148110 }
   148111 #endif
   148112 
   148113 #endif
   148114 
   148115 /************** End of rtree.c ***********************************************/
   148116 /************** Begin file icu.c *********************************************/
   148117 /*
   148118 ** 2007 May 6
   148119 **
   148120 ** The author disclaims copyright to this source code.  In place of
   148121 ** a legal notice, here is a blessing:
   148122 **
   148123 **    May you do good and not evil.
   148124 **    May you find forgiveness for yourself and forgive others.
   148125 **    May you share freely, never taking more than you give.
   148126 **
   148127 *************************************************************************
   148128 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
   148129 **
   148130 ** This file implements an integration between the ICU library
   148131 ** ("International Components for Unicode", an open-source library
   148132 ** for handling unicode data) and SQLite. The integration uses
   148133 ** ICU to provide the following to SQLite:
   148134 **
   148135 **   * An implementation of the SQL regexp() function (and hence REGEXP
   148136 **     operator) using the ICU uregex_XX() APIs.
   148137 **
   148138 **   * Implementations of the SQL scalar upper() and lower() functions
   148139 **     for case mapping.
   148140 **
   148141 **   * Integration of ICU and SQLite collation sequences.
   148142 **
   148143 **   * An implementation of the LIKE operator that uses ICU to
   148144 **     provide case-independent matching.
   148145 */
   148146 
   148147 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
   148148 
   148149 /* Include ICU headers */
   148150 #include <unicode/utypes.h>
   148151 #include <unicode/uregex.h>
   148152 #include <unicode/ustring.h>
   148153 #include <unicode/ucol.h>
   148154 
   148155 /* #include <assert.h> */
   148156 
   148157 #ifndef SQLITE_CORE
   148158   SQLITE_EXTENSION_INIT1
   148159 #else
   148160 #endif
   148161 
   148162 /*
   148163 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   148164 ** operator.
   148165 */
   148166 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   148167 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   148168 #endif
   148169 
   148170 /*
   148171 ** Version of sqlite3_free() that is always a function, never a macro.
   148172 */
   148173 static void xFree(void *p){
   148174   sqlite3_free(p);
   148175 }
   148176 
   148177 /*
   148178 ** Compare two UTF-8 strings for equality where the first string is
   148179 ** a "LIKE" expression. Return true (1) if they are the same and
   148180 ** false (0) if they are different.
   148181 */
   148182 static int icuLikeCompare(
   148183   const uint8_t *zPattern,   /* LIKE pattern */
   148184   const uint8_t *zString,    /* The UTF-8 string to compare against */
   148185   const UChar32 uEsc         /* The escape character */
   148186 ){
   148187   static const int MATCH_ONE = (UChar32)'_';
   148188   static const int MATCH_ALL = (UChar32)'%';
   148189 
   148190   int iPattern = 0;       /* Current byte index in zPattern */
   148191   int iString = 0;        /* Current byte index in zString */
   148192 
   148193   int prevEscape = 0;     /* True if the previous character was uEsc */
   148194 
   148195   while( zPattern[iPattern]!=0 ){
   148196 
   148197     /* Read (and consume) the next character from the input pattern. */
   148198     UChar32 uPattern;
   148199     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
   148200     assert(uPattern!=0);
   148201 
   148202     /* There are now 4 possibilities:
   148203     **
   148204     **     1. uPattern is an unescaped match-all character "%",
   148205     **     2. uPattern is an unescaped match-one character "_",
   148206     **     3. uPattern is an unescaped escape character, or
   148207     **     4. uPattern is to be handled as an ordinary character
   148208     */
   148209     if( !prevEscape && uPattern==MATCH_ALL ){
   148210       /* Case 1. */
   148211       uint8_t c;
   148212 
   148213       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
   148214       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
   148215       ** test string.
   148216       */
   148217       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
   148218         if( c==MATCH_ONE ){
   148219           if( zString[iString]==0 ) return 0;
   148220           U8_FWD_1_UNSAFE(zString, iString);
   148221         }
   148222         iPattern++;
   148223       }
   148224 
   148225       if( zPattern[iPattern]==0 ) return 1;
   148226 
   148227       while( zString[iString] ){
   148228         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
   148229           return 1;
   148230         }
   148231         U8_FWD_1_UNSAFE(zString, iString);
   148232       }
   148233       return 0;
   148234 
   148235     }else if( !prevEscape && uPattern==MATCH_ONE ){
   148236       /* Case 2. */
   148237       if( zString[iString]==0 ) return 0;
   148238       U8_FWD_1_UNSAFE(zString, iString);
   148239 
   148240     }else if( !prevEscape && uPattern==uEsc){
   148241       /* Case 3. */
   148242       prevEscape = 1;
   148243 
   148244     }else{
   148245       /* Case 4. */
   148246       UChar32 uString;
   148247       U8_NEXT_UNSAFE(zString, iString, uString);
   148248       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
   148249       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
   148250       if( uString!=uPattern ){
   148251         return 0;
   148252       }
   148253       prevEscape = 0;
   148254     }
   148255   }
   148256 
   148257   return zString[iString]==0;
   148258 }
   148259 
   148260 /*
   148261 ** Implementation of the like() SQL function.  This function implements
   148262 ** the build-in LIKE operator.  The first argument to the function is the
   148263 ** pattern and the second argument is the string.  So, the SQL statements:
   148264 **
   148265 **       A LIKE B
   148266 **
   148267 ** is implemented as like(B, A). If there is an escape character E,
   148268 **
   148269 **       A LIKE B ESCAPE E
   148270 **
   148271 ** is mapped to like(B, A, E).
   148272 */
   148273 static void icuLikeFunc(
   148274   sqlite3_context *context,
   148275   int argc,
   148276   sqlite3_value **argv
   148277 ){
   148278   const unsigned char *zA = sqlite3_value_text(argv[0]);
   148279   const unsigned char *zB = sqlite3_value_text(argv[1]);
   148280   UChar32 uEsc = 0;
   148281 
   148282   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   148283   ** of deep recursion and N*N behavior in patternCompare().
   148284   */
   148285   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
   148286     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   148287     return;
   148288   }
   148289 
   148290 
   148291   if( argc==3 ){
   148292     /* The escape character string must consist of a single UTF-8 character.
   148293     ** Otherwise, return an error.
   148294     */
   148295     int nE= sqlite3_value_bytes(argv[2]);
   148296     const unsigned char *zE = sqlite3_value_text(argv[2]);
   148297     int i = 0;
   148298     if( zE==0 ) return;
   148299     U8_NEXT(zE, i, nE, uEsc);
   148300     if( i!=nE){
   148301       sqlite3_result_error(context,
   148302           "ESCAPE expression must be a single character", -1);
   148303       return;
   148304     }
   148305   }
   148306 
   148307   if( zA && zB ){
   148308     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
   148309   }
   148310 }
   148311 
   148312 /*
   148313 ** This function is called when an ICU function called from within
   148314 ** the implementation of an SQL scalar function returns an error.
   148315 **
   148316 ** The scalar function context passed as the first argument is
   148317 ** loaded with an error message based on the following two args.
   148318 */
   148319 static void icuFunctionError(
   148320   sqlite3_context *pCtx,       /* SQLite scalar function context */
   148321   const char *zName,           /* Name of ICU function that failed */
   148322   UErrorCode e                 /* Error code returned by ICU function */
   148323 ){
   148324   char zBuf[128];
   148325   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
   148326   zBuf[127] = '\0';
   148327   sqlite3_result_error(pCtx, zBuf, -1);
   148328 }
   148329 
   148330 /*
   148331 ** Function to delete compiled regexp objects. Registered as
   148332 ** a destructor function with sqlite3_set_auxdata().
   148333 */
   148334 static void icuRegexpDelete(void *p){
   148335   URegularExpression *pExpr = (URegularExpression *)p;
   148336   uregex_close(pExpr);
   148337 }
   148338 
   148339 /*
   148340 ** Implementation of SQLite REGEXP operator. This scalar function takes
   148341 ** two arguments. The first is a regular expression pattern to compile
   148342 ** the second is a string to match against that pattern. If either
   148343 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
   148344 ** is 1 if the string matches the pattern, or 0 otherwise.
   148345 **
   148346 ** SQLite maps the regexp() function to the regexp() operator such
   148347 ** that the following two are equivalent:
   148348 **
   148349 **     zString REGEXP zPattern
   148350 **     regexp(zPattern, zString)
   148351 **
   148352 ** Uses the following ICU regexp APIs:
   148353 **
   148354 **     uregex_open()
   148355 **     uregex_matches()
   148356 **     uregex_close()
   148357 */
   148358 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   148359   UErrorCode status = U_ZERO_ERROR;
   148360   URegularExpression *pExpr;
   148361   UBool res;
   148362   const UChar *zString = sqlite3_value_text16(apArg[1]);
   148363 
   148364   (void)nArg;  /* Unused parameter */
   148365 
   148366   /* If the left hand side of the regexp operator is NULL,
   148367   ** then the result is also NULL.
   148368   */
   148369   if( !zString ){
   148370     return;
   148371   }
   148372 
   148373   pExpr = sqlite3_get_auxdata(p, 0);
   148374   if( !pExpr ){
   148375     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
   148376     if( !zPattern ){
   148377       return;
   148378     }
   148379     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
   148380 
   148381     if( U_SUCCESS(status) ){
   148382       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
   148383     }else{
   148384       assert(!pExpr);
   148385       icuFunctionError(p, "uregex_open", status);
   148386       return;
   148387     }
   148388   }
   148389 
   148390   /* Configure the text that the regular expression operates on. */
   148391   uregex_setText(pExpr, zString, -1, &status);
   148392   if( !U_SUCCESS(status) ){
   148393     icuFunctionError(p, "uregex_setText", status);
   148394     return;
   148395   }
   148396 
   148397   /* Attempt the match */
   148398   res = uregex_matches(pExpr, 0, &status);
   148399   if( !U_SUCCESS(status) ){
   148400     icuFunctionError(p, "uregex_matches", status);
   148401     return;
   148402   }
   148403 
   148404   /* Set the text that the regular expression operates on to a NULL
   148405   ** pointer. This is not really necessary, but it is tidier than
   148406   ** leaving the regular expression object configured with an invalid
   148407   ** pointer after this function returns.
   148408   */
   148409   uregex_setText(pExpr, 0, 0, &status);
   148410 
   148411   /* Return 1 or 0. */
   148412   sqlite3_result_int(p, res ? 1 : 0);
   148413 }
   148414 
   148415 /*
   148416 ** Implementations of scalar functions for case mapping - upper() and
   148417 ** lower(). Function upper() converts its input to upper-case (ABC).
   148418 ** Function lower() converts to lower-case (abc).
   148419 **
   148420 ** ICU provides two types of case mapping, "general" case mapping and
   148421 ** "language specific". Refer to ICU documentation for the differences
   148422 ** between the two.
   148423 **
   148424 ** To utilise "general" case mapping, the upper() or lower() scalar
   148425 ** functions are invoked with one argument:
   148426 **
   148427 **     upper('ABC') -> 'abc'
   148428 **     lower('abc') -> 'ABC'
   148429 **
   148430 ** To access ICU "language specific" case mapping, upper() or lower()
   148431 ** should be invoked with two arguments. The second argument is the name
   148432 ** of the locale to use. Passing an empty string ("") or SQL NULL value
   148433 ** as the second argument is the same as invoking the 1 argument version
   148434 ** of upper() or lower().
   148435 **
   148436 **     lower('I', 'en_us') -> 'i'
   148437 **     lower('I', 'tr_tr') -> '' (small dotless i)
   148438 **
   148439 ** http://www.icu-project.org/userguide/posix.html#case_mappings
   148440 */
   148441 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   148442   const UChar *zInput;
   148443   UChar *zOutput;
   148444   int nInput;
   148445   int nOutput;
   148446 
   148447   UErrorCode status = U_ZERO_ERROR;
   148448   const char *zLocale = 0;
   148449 
   148450   assert(nArg==1 || nArg==2);
   148451   if( nArg==2 ){
   148452     zLocale = (const char *)sqlite3_value_text(apArg[1]);
   148453   }
   148454 
   148455   zInput = sqlite3_value_text16(apArg[0]);
   148456   if( !zInput ){
   148457     return;
   148458   }
   148459   nInput = sqlite3_value_bytes16(apArg[0]);
   148460 
   148461   nOutput = nInput * 2 + 2;
   148462   zOutput = sqlite3_malloc(nOutput);
   148463   if( !zOutput ){
   148464     return;
   148465   }
   148466 
   148467   if( sqlite3_user_data(p) ){
   148468     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   148469   }else{
   148470     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   148471   }
   148472 
   148473   if( !U_SUCCESS(status) ){
   148474     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
   148475     return;
   148476   }
   148477 
   148478   sqlite3_result_text16(p, zOutput, -1, xFree);
   148479 }
   148480 
   148481 /*
   148482 ** Collation sequence destructor function. The pCtx argument points to
   148483 ** a UCollator structure previously allocated using ucol_open().
   148484 */
   148485 static void icuCollationDel(void *pCtx){
   148486   UCollator *p = (UCollator *)pCtx;
   148487   ucol_close(p);
   148488 }
   148489 
   148490 /*
   148491 ** Collation sequence comparison function. The pCtx argument points to
   148492 ** a UCollator structure previously allocated using ucol_open().
   148493 */
   148494 static int icuCollationColl(
   148495   void *pCtx,
   148496   int nLeft,
   148497   const void *zLeft,
   148498   int nRight,
   148499   const void *zRight
   148500 ){
   148501   UCollationResult res;
   148502   UCollator *p = (UCollator *)pCtx;
   148503   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
   148504   switch( res ){
   148505     case UCOL_LESS:    return -1;
   148506     case UCOL_GREATER: return +1;
   148507     case UCOL_EQUAL:   return 0;
   148508   }
   148509   assert(!"Unexpected return value from ucol_strcoll()");
   148510   return 0;
   148511 }
   148512 
   148513 /*
   148514 ** Implementation of the scalar function icu_load_collation().
   148515 **
   148516 ** This scalar function is used to add ICU collation based collation
   148517 ** types to an SQLite database connection. It is intended to be called
   148518 ** as follows:
   148519 **
   148520 **     SELECT icu_load_collation(<locale>, <collation-name>);
   148521 **
   148522 ** Where <locale> is a string containing an ICU locale identifier (i.e.
   148523 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
   148524 ** collation sequence to create.
   148525 */
   148526 static void icuLoadCollation(
   148527   sqlite3_context *p,
   148528   int nArg,
   148529   sqlite3_value **apArg
   148530 ){
   148531   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
   148532   UErrorCode status = U_ZERO_ERROR;
   148533   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
   148534   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
   148535   UCollator *pUCollator;    /* ICU library collation object */
   148536   int rc;                   /* Return code from sqlite3_create_collation_x() */
   148537 
   148538   assert(nArg==2);
   148539   zLocale = (const char *)sqlite3_value_text(apArg[0]);
   148540   zName = (const char *)sqlite3_value_text(apArg[1]);
   148541 
   148542   if( !zLocale || !zName ){
   148543     return;
   148544   }
   148545 
   148546   pUCollator = ucol_open(zLocale, &status);
   148547   if( !U_SUCCESS(status) ){
   148548     icuFunctionError(p, "ucol_open", status);
   148549     return;
   148550   }
   148551   assert(p);
   148552 
   148553   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
   148554       icuCollationColl, icuCollationDel
   148555   );
   148556   if( rc!=SQLITE_OK ){
   148557     ucol_close(pUCollator);
   148558     sqlite3_result_error(p, "Error registering collation function", -1);
   148559   }
   148560 }
   148561 
   148562 /*
   148563 ** Register the ICU extension functions with database db.
   148564 */
   148565 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
   148566   struct IcuScalar {
   148567     const char *zName;                        /* Function name */
   148568     int nArg;                                 /* Number of arguments */
   148569     int enc;                                  /* Optimal text encoding */
   148570     void *pContext;                           /* sqlite3_user_data() context */
   148571     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   148572   } scalars[] = {
   148573     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
   148574 
   148575     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
   148576     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
   148577     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   148578     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   148579 
   148580     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
   148581     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
   148582     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   148583     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   148584 
   148585     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
   148586     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
   148587 
   148588     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
   148589   };
   148590 
   148591   int rc = SQLITE_OK;
   148592   int i;
   148593 
   148594   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
   148595     struct IcuScalar *p = &scalars[i];
   148596     rc = sqlite3_create_function(
   148597         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
   148598     );
   148599   }
   148600 
   148601   return rc;
   148602 }
   148603 
   148604 #if !SQLITE_CORE
   148605 #ifdef _WIN32
   148606 __declspec(dllexport)
   148607 #endif
   148608 SQLITE_API int sqlite3_icu_init(
   148609   sqlite3 *db,
   148610   char **pzErrMsg,
   148611   const sqlite3_api_routines *pApi
   148612 ){
   148613   SQLITE_EXTENSION_INIT2(pApi)
   148614   return sqlite3IcuInit(db);
   148615 }
   148616 #endif
   148617 
   148618 #endif
   148619 
   148620 /************** End of icu.c *************************************************/
   148621 /************** Begin file fts3_icu.c ****************************************/
   148622 /*
   148623 ** 2007 June 22
   148624 **
   148625 ** The author disclaims copyright to this source code.  In place of
   148626 ** a legal notice, here is a blessing:
   148627 **
   148628 **    May you do good and not evil.
   148629 **    May you find forgiveness for yourself and forgive others.
   148630 **    May you share freely, never taking more than you give.
   148631 **
   148632 *************************************************************************
   148633 ** This file implements a tokenizer for fts3 based on the ICU library.
   148634 */
   148635 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   148636 #ifdef SQLITE_ENABLE_ICU
   148637 
   148638 /* #include <assert.h> */
   148639 /* #include <string.h> */
   148640 
   148641 #include <unicode/ubrk.h>
   148642 /* #include <unicode/ucol.h> */
   148643 /* #include <unicode/ustring.h> */
   148644 #include <unicode/utf16.h>
   148645 
   148646 typedef struct IcuTokenizer IcuTokenizer;
   148647 typedef struct IcuCursor IcuCursor;
   148648 
   148649 struct IcuTokenizer {
   148650   sqlite3_tokenizer base;
   148651   char *zLocale;
   148652 };
   148653 
   148654 struct IcuCursor {
   148655   sqlite3_tokenizer_cursor base;
   148656 
   148657   UBreakIterator *pIter;      /* ICU break-iterator object */
   148658   int nChar;                  /* Number of UChar elements in pInput */
   148659   UChar *aChar;               /* Copy of input using utf-16 encoding */
   148660   int *aOffset;               /* Offsets of each character in utf-8 input */
   148661 
   148662   int nBuffer;
   148663   char *zBuffer;
   148664 
   148665   int iToken;
   148666 };
   148667 
   148668 /*
   148669 ** Create a new tokenizer instance.
   148670 */
   148671 static int icuCreate(
   148672   int argc,                            /* Number of entries in argv[] */
   148673   const char * const *argv,            /* Tokenizer creation arguments */
   148674   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
   148675 ){
   148676   IcuTokenizer *p;
   148677   int n = 0;
   148678 
   148679   if( argc>0 ){
   148680     n = strlen(argv[0])+1;
   148681   }
   148682   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
   148683   if( !p ){
   148684     return SQLITE_NOMEM;
   148685   }
   148686   memset(p, 0, sizeof(IcuTokenizer));
   148687 
   148688   if( n ){
   148689     p->zLocale = (char *)&p[1];
   148690     memcpy(p->zLocale, argv[0], n);
   148691   }
   148692 
   148693   *ppTokenizer = (sqlite3_tokenizer *)p;
   148694 
   148695   return SQLITE_OK;
   148696 }
   148697 
   148698 /*
   148699 ** Destroy a tokenizer
   148700 */
   148701 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
   148702   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   148703   sqlite3_free(p);
   148704   return SQLITE_OK;
   148705 }
   148706 
   148707 /*
   148708 ** Prepare to begin tokenizing a particular string.  The input
   148709 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   148710 ** used to incrementally tokenize this string is returned in
   148711 ** *ppCursor.
   148712 */
   148713 static int icuOpen(
   148714   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   148715   const char *zInput,                    /* Input string */
   148716   int nInput,                            /* Length of zInput in bytes */
   148717   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   148718 ){
   148719   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   148720   IcuCursor *pCsr;
   148721 
   148722   const int32_t opt = U_FOLD_CASE_DEFAULT;
   148723   UErrorCode status = U_ZERO_ERROR;
   148724   int nChar;
   148725 
   148726   UChar32 c;
   148727   int iInput = 0;
   148728   int iOut = 0;
   148729 
   148730   *ppCursor = 0;
   148731 
   148732   if( zInput==0 ){
   148733     nInput = 0;
   148734     zInput = "";
   148735   }else if( nInput<0 ){
   148736     nInput = strlen(zInput);
   148737   }
   148738   nChar = nInput+1;
   148739   pCsr = (IcuCursor *)sqlite3_malloc(
   148740       sizeof(IcuCursor) +                /* IcuCursor */
   148741       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
   148742       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
   148743   );
   148744   if( !pCsr ){
   148745     return SQLITE_NOMEM;
   148746   }
   148747   memset(pCsr, 0, sizeof(IcuCursor));
   148748   pCsr->aChar = (UChar *)&pCsr[1];
   148749   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
   148750 
   148751   pCsr->aOffset[iOut] = iInput;
   148752   U8_NEXT(zInput, iInput, nInput, c);
   148753   while( c>0 ){
   148754     int isError = 0;
   148755     c = u_foldCase(c, opt);
   148756     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
   148757     if( isError ){
   148758       sqlite3_free(pCsr);
   148759       return SQLITE_ERROR;
   148760     }
   148761     pCsr->aOffset[iOut] = iInput;
   148762 
   148763     if( iInput<nInput ){
   148764       U8_NEXT(zInput, iInput, nInput, c);
   148765     }else{
   148766       c = 0;
   148767     }
   148768   }
   148769 
   148770   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
   148771   if( !U_SUCCESS(status) ){
   148772     sqlite3_free(pCsr);
   148773     return SQLITE_ERROR;
   148774   }
   148775   pCsr->nChar = iOut;
   148776 
   148777   ubrk_first(pCsr->pIter);
   148778   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
   148779   return SQLITE_OK;
   148780 }
   148781 
   148782 /*
   148783 ** Close a tokenization cursor previously opened by a call to icuOpen().
   148784 */
   148785 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
   148786   IcuCursor *pCsr = (IcuCursor *)pCursor;
   148787   ubrk_close(pCsr->pIter);
   148788   sqlite3_free(pCsr->zBuffer);
   148789   sqlite3_free(pCsr);
   148790   return SQLITE_OK;
   148791 }
   148792 
   148793 /*
   148794 ** Extract the next token from a tokenization cursor.
   148795 */
   148796 static int icuNext(
   148797   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   148798   const char **ppToken,               /* OUT: *ppToken is the token text */
   148799   int *pnBytes,                       /* OUT: Number of bytes in token */
   148800   int *piStartOffset,                 /* OUT: Starting offset of token */
   148801   int *piEndOffset,                   /* OUT: Ending offset of token */
   148802   int *piPosition                     /* OUT: Position integer of token */
   148803 ){
   148804   IcuCursor *pCsr = (IcuCursor *)pCursor;
   148805 
   148806   int iStart = 0;
   148807   int iEnd = 0;
   148808   int nByte = 0;
   148809 
   148810   while( iStart==iEnd ){
   148811     UChar32 c;
   148812 
   148813     iStart = ubrk_current(pCsr->pIter);
   148814     iEnd = ubrk_next(pCsr->pIter);
   148815     if( iEnd==UBRK_DONE ){
   148816       return SQLITE_DONE;
   148817     }
   148818 
   148819     while( iStart<iEnd ){
   148820       int iWhite = iStart;
   148821       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
   148822       if( u_isspace(c) ){
   148823         iStart = iWhite;
   148824       }else{
   148825         break;
   148826       }
   148827     }
   148828     assert(iStart<=iEnd);
   148829   }
   148830 
   148831   do {
   148832     UErrorCode status = U_ZERO_ERROR;
   148833     if( nByte ){
   148834       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
   148835       if( !zNew ){
   148836         return SQLITE_NOMEM;
   148837       }
   148838       pCsr->zBuffer = zNew;
   148839       pCsr->nBuffer = nByte;
   148840     }
   148841 
   148842     u_strToUTF8(
   148843         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
   148844         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
   148845         &status                                  /* Output success/failure */
   148846     );
   148847   } while( nByte>pCsr->nBuffer );
   148848 
   148849   *ppToken = pCsr->zBuffer;
   148850   *pnBytes = nByte;
   148851   *piStartOffset = pCsr->aOffset[iStart];
   148852   *piEndOffset = pCsr->aOffset[iEnd];
   148853   *piPosition = pCsr->iToken++;
   148854 
   148855   return SQLITE_OK;
   148856 }
   148857 
   148858 /*
   148859 ** The set of routines that implement the simple tokenizer
   148860 */
   148861 static const sqlite3_tokenizer_module icuTokenizerModule = {
   148862   0,                           /* iVersion */
   148863   icuCreate,                   /* xCreate  */
   148864   icuDestroy,                  /* xCreate  */
   148865   icuOpen,                     /* xOpen    */
   148866   icuClose,                    /* xClose   */
   148867   icuNext,                     /* xNext    */
   148868 };
   148869 
   148870 /*
   148871 ** Set *ppModule to point at the implementation of the ICU tokenizer.
   148872 */
   148873 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
   148874   sqlite3_tokenizer_module const**ppModule
   148875 ){
   148876   *ppModule = &icuTokenizerModule;
   148877 }
   148878 
   148879 #endif /* defined(SQLITE_ENABLE_ICU) */
   148880 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   148881 
   148882 /************** End of fts3_icu.c ********************************************/
   148883